diff --git a/.editorconfig b/.editorconfig index 952df53a..e6cef787 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,7 +13,7 @@ insert_final_newline = true indent_size = 2 [*.java] -# indent_style = tab +indent_style = tab ij_continuation_indent_size = 8 ij_java_class_count_to_use_import_on_demand = 99 ij_java_names_count_to_use_import_on_demand = 99 \ No newline at end of file diff --git a/src/main/java/com/fusionflux/portalcubed/PortalCubed.java b/src/main/java/com/fusionflux/portalcubed/PortalCubed.java index 63b8dfb3..8f471935 100644 --- a/src/main/java/com/fusionflux/portalcubed/PortalCubed.java +++ b/src/main/java/com/fusionflux/portalcubed/PortalCubed.java @@ -77,346 +77,346 @@ public class PortalCubed implements ModInitializer { - public static final String MOD_ID = "portalcubed"; - - public static final Logger LOGGER = LogUtils.getLogger(); - - public static final MenuType FAITH_PLATE_SCREEN_HANDLER = Registry.register( - BuiltInRegistries.MENU, id("faith_plate_screen"), - new ExtendedScreenHandlerType<>(FaithPlateScreenHandler::new) - ); - public static final MenuType VELOCITY_HELPER_SCREEN_HANDLER = BlockPosScreenHandler.registerNew("velocity_helper"); - - public static final double MAX_SPEED = 2225 / 64.0 / 20.0, MAX_SPEED_SQR = MAX_SPEED * MAX_SPEED; - - public static final Map> TOOLTIPS = new HashMap<>(); - - @Override - public void onInitialize(ModContainer mod) { - ServerPlayNetworking.registerGlobalReceiver(id("use_portal"), (server, player, handler, buf, responseSender) -> { - // read the velocity from the byte buf - final int targetEntityId = buf.readVarInt(); - float yawSet = buf.readFloat(); - float pitchSet = buf.readFloat(); - Optional currentAnimationDelta = buf.readOptional(b -> new IPQuaternion( - b.readDouble(), - b.readDouble(), - b.readDouble(), - b.readDouble() - )); - final Vec3 entityVelocity = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); - final Vec3 teleportOffset = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); - final Vec3 teleportOffsetNoRotate = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); - if (!Float.isFinite(yawSet)) { - handler.disconnect(Component.translatable("multiplayer.disconnect.invalid_player_movement")); - return; - } - server.execute(() -> { - boolean rubberband = false; - if (!(player.level().getEntity(targetEntityId) instanceof Portal portal)) { - LOGGER.warn("{} tried to teleport through nonexistent portal", player); - handler.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); - CalledValues.setIsTeleporting(player, false); - GravityChangerAPI.clearGravity(player); - return; - } - if (portal.position().distanceToSqr(player.position()) > 10 * 10) { - LOGGER.warn("{} tried to teleport through distant portal ({})", player, portal.position().distanceTo(player.position())); - rubberband = true; - } - if (portal.getDestination().isEmpty()) { - LOGGER.warn("{} tried to teleport through an inactive portal ({}).", player, portal); - rubberband = true; - } - if (teleportOffset.lengthSqr() > 10 * 10) { - LOGGER.warn("{} tried to use a huge teleportOffset ({}).", player, teleportOffset.length()); - rubberband = true; - } - if (rubberband) { - handler.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); - CalledValues.setIsTeleporting(player, false); - GravityChangerAPI.clearGravity(player); - return; - } - - final TeleportResult result = commonTeleport( - portal, - entityVelocity, - teleportOffset, - teleportOffsetNoRotate, - player, - currentAnimationDelta, - pitchSet, yawSet - ); -// CalledValues.setVelocityUpdateAfterTeleport(player, result.velocity()); - - final Vec3 dest = result.dest(); -// final IPQuaternion cameraAnimation = IPQuaternion.getCameraRotation(result.pitch(), result.yaw()) -// .getConjugated() -// .hamiltonProduct(result.immediateFinalRot()); -// player.connection.teleport(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); - player.moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); - player.setDeltaMovement(result.velocity()); - player.connection.resetPosition(); -// final FriendlyByteBuf buf2 = PacketByteBufs.create(); -// buf2.writeDouble(cameraAnimation.x); -// buf2.writeDouble(cameraAnimation.y); -// buf2.writeDouble(cameraAnimation.z); -// buf2.writeDouble(cameraAnimation.w); -// ServerPlayNetworking.send(player, PortalCubedClientPackets.SET_CAMERA_INTERPOLATE, buf2); - -// CalledValues.setHasTeleportationHappened(player, true); - GravityChangerAPI.clearGravity(player); - - }); - }); - - ServerPlayNetworking.registerGlobalReceiver(id("configure_faith_plate"), (server, player, handler, buf, responseSender) -> { - // read the velocity from the byte buf - BlockPos target = buf.readBlockPos(); - double x = buf.readDouble(); - double y = buf.readDouble(); - double z = buf.readDouble(); - server.execute(() -> { - final BlockEntity entity = player.level().getBlockEntity(target); - if (entity instanceof FaithPlateBlockEntity faithPlateBlockEntity) { - faithPlateBlockEntity.setVelX(x); - faithPlateBlockEntity.setVelY(y); - faithPlateBlockEntity.setVelZ(z); - faithPlateBlockEntity.updateListeners(); - } - }); - }); - - ServerPlayNetworking.registerGlobalReceiver(id("client_teleport_update"), (server, player, handler, buf, responseSender) -> - server.execute(() -> CalledValues.setHasTeleportationHappened(player, false)) - ); - - ServerPlayNetworking.registerGlobalReceiver(id("request_velocity_for_gel"), (server, player, handler, buf, responseSender) -> { - final Vec3 entityVelocity = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); - final boolean fireGel = buf.readBoolean(); - server.execute(() -> { - CalledValues.setServerVelForGel(player, entityVelocity); - CalledValues.setCanFireGel(player, fireGel); - - }); - }); - - ServerPlayNetworking.registerGlobalReceiver(id("cube_pos_update"), (server, player, handler, buf, responseSender) -> { - // read the velocity from the byte buf - double x = buf.readDouble(); - double y = buf.readDouble(); - double z = buf.readDouble(); - double lastX = buf.readDouble(); - double lastY = buf.readDouble(); - double lastZ = buf.readDouble(); - float rotYaw = buf.readFloat(); - UUID cubeuuid = buf.readUUID(); - server.execute(() -> { - if (!(player.serverLevel().getEntity(cubeuuid) instanceof CorePhysicsEntity cube)) { - LOGGER.warn("{} tried to drop nonexistent physics object", player); - return; - } - if (!player.getUUID().equals(cube.getHolderUUID().orElse(null))) { - LOGGER.warn("{} tried to drop another player's physics object (held by {})", player, cube.getHolderUUID()); - return; - } - cube.setRotYaw(rotYaw); - Vec3 cubePos = new Vec3(x, y, z); - Vec3 lastCubePos = new Vec3(lastX, lastY, lastZ); - if (cubePos.distanceToSqr(lastCubePos) > 10 * 10) { - LOGGER.warn("{} tried to throw a physics object really fast ({})", player, cubePos.distanceTo(lastCubePos)); - return; - } - - cube.setPos(cubePos); - cube.setDeltaMovement(RotationUtil.vecWorldToPlayer(cubePos.subtract(lastCubePos), GravityChangerAPI.getGravityDirection(cube)).scale(.5)); - }); - }); - - ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { - if (!handler.player.level().getGameRules().getBoolean(PortalCubedGameRules.ALLOW_CROUCH_FLY_GLITCH)) { - // Default is true on the client, so we don't need to send in that case - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBoolean(false); - handler.send(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_CFG, buf)); - } - if (handler.player.level().getGameRules().getBoolean(PortalCubedGameRules.USE_PORTAL_HUD)) { - // Same as above, but false - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBoolean(true); - handler.send(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_PORTAL_HUD, buf)); - } - syncFog(handler.player); - }); - - EntityWorldChangeEvents.AFTER_PLAYER_WORLD_CHANGE.register((player, origin, destination) -> syncFog(player)); - - ServerPlayerEntityCopyCallback.EVENT.register((copy, original, wasDeath) -> syncFog(copy)); - - UseBlockCallback.EVENT.register((player, world, hand, hitResult) -> - portalHudModeServerOrClient(world) && - (!(world.getBlockState(hitResult.getBlockPos()).getBlock() instanceof TallButtonVariant) || - hand != InteractionHand.OFF_HAND) - ? InteractionResult.FAIL : InteractionResult.PASS - ); - - MidnightConfig.init("portalcubed", PortalCubedConfig.class); - - PortalBlocksLoader.init(mod); - PortalCubedFluids.registerFluids(); - PortalCubedBlocks.registerBlocks(); - PortalCubedItems.registerItems(); - PortalCubedEntities.registerEntities(); - PortalCubedTrackedDataHandlers.register(); - PortalCubedServerPackets.registerPackets(); - PortalCubedSounds.registerSounds(); - PortalCubedGameRules.register(); - PortalCubedParticleTypes.register(); - PortalCubedAdvancements.register(); - - PortalTabsLoader.load(mod); - BlockContentRegistries.FLAMMABLE.put(PortalCubedBlocks.NEUROTOXIN_BLOCK, new FlammableBlockEntry(10000, 10000)); - GravityChannel.UPDATE_GRAVITY.getVerifierRegistry().register(AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, AdhesionGravityVerifier::check); - - CommandRegistrationCallback.EVENT.register(new PortalCubedCommands()); - - if (QuiltLoader.isModLoaded("create")) { - LOGGER.warn("Create is out for this game version! Go poke the Portal Cubed developers on Discord to re-enable this integration."); -// CreateIntegration.init(); - } - - RayonIntegration.INSTANCE.init(); - - CommandRegistrationCallback.EVENT.register(((dispatcher, buildContext, environment) -> SpawnArmorTrimsCommand.register(dispatcher))); - - final JsonObject tooltipData; - try { - tooltipData = GsonHelper.parse(Files.newBufferedReader(mod.getPath("tooltips.json"))); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - for (final var entry : tooltipData.entrySet()) { - final List output = TOOLTIPS.computeIfAbsent(id(entry.getKey()), k -> new ArrayList<>()); - for (final JsonElement value : GsonHelper.convertToJsonArray(entry.getValue(), "tooltips")) { - output.add(Component.Serializer.fromJson(value)); - } - } - } - - public static void syncFog(ServerPlayer player) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - FogSettings.encodeOptional(FogPersistentState.getOrCreate(player.serverLevel()).getSettings(), buf); - ServerPlayNetworking.send(player, PortalCubedClientPackets.SET_CUSTOM_FOG, buf); - } - - public static void syncFog(ServerLevel world) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - FogSettings.encodeOptional(FogPersistentState.getOrCreate(world).getSettings(), buf); - world.getServer().getPlayerList().broadcastAll( - ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.SET_CUSTOM_FOG, buf), - world.dimension() - ); - } - - public static void playBounceSound(Entity entity) { - entity.level().playSound( - null, - entity.position().x(), entity.position().y(), entity.position().z(), - PortalCubedSounds.GEL_BOUNCE_EVENT, SoundSource.BLOCKS, - 1f, 0.95f + entity.level().random.nextFloat() * 0.1f - ); - } - - @ClientOnly - public static void playBounceSoundRemotely() { - ClientPlayNetworking.send(PortalCubedServerPackets.PLAY_BOUNCE_SOUND, PacketByteBufs.empty()); - } - - public static TeleportResult commonTeleport( - Portal portal, - Vec3 entityVelocity, - Vec3 teleportOffset, - Vec3 teleportOffsetNoRotate, - Entity entity, - Optional currentAnimationDelta, - float pitchSet, float yawSet - ) { - assert portal.getDestination().isPresent(); - assert portal.getOtherNormal().isPresent(); - - final Direction direction = portal.getFacingDirection(); - final Vec3 otherNormal = portal.getOtherNormal().get(); - Direction otherDirec = Direction.getNearest(otherNormal.x(), otherNormal.y(), otherNormal.z()); - final IPQuaternion portalTransform = portal.getTransformQuat(); - - Vec3 rotatedVel = entityVelocity; - Vec3 rotatedOffsets = teleportOffset; - - rotatedVel = portalTransform.rotate(rotatedVel, false); - rotatedOffsets = portalTransform.rotate(rotatedOffsets, false); - - if (otherDirec == Direction.UP && rotatedVel.y < 0.48) { - rotatedVel = new Vec3(rotatedVel.x, 0.48, rotatedVel.z); - } - - if (direction.getAxis().isHorizontal() && otherDirec.getAxis().isHorizontal()) { - rotatedOffsets = rotatedOffsets.subtract(0, entity.getEyeY() - entity.getY(), 0); - if (rotatedOffsets.y < -0.95) { - rotatedOffsets = new Vec3(rotatedOffsets.x, -0.95, rotatedOffsets.z); - } else if (rotatedOffsets.y > -0.95 + (1.9 - entity.getBbHeight())) { - rotatedOffsets = new Vec3(rotatedOffsets.x, -0.95 + (1.9 - entity.getBbHeight()), rotatedOffsets.z); - } - } - - if (rotatedVel.lengthSqr() > PortalCubed.MAX_SPEED_SQR) { - rotatedVel = rotatedVel.scale(PortalCubed.MAX_SPEED / rotatedVel.length()); - } - - IPQuaternion oldCameraRotation = IPQuaternion.getCameraRotation(pitchSet, yawSet); - if (currentAnimationDelta.isPresent()) { - oldCameraRotation = oldCameraRotation.hamiltonProduct(currentAnimationDelta.get()); - } - IPQuaternion immediateFinalRot = oldCameraRotation.hamiltonProduct(portalTransform.getConjugated()); - final Vector3d euler = immediateFinalRot.toQuaterniond().getEulerAnglesZXY(new Vector3d()); - float finalYaw = (float)Math.toDegrees(euler.y) + 180; - float finalPitch = (float)Math.toDegrees(euler.x); - - if (entity instanceof Player) { - boolean tweak = false; - if (finalPitch <= -50 && pitchSet >= 50) { - finalPitch = -90; - tweak = true; - } else if (finalPitch >= 50 && pitchSet <= -50) { - finalPitch = 90; - tweak = true; - } - if (tweak) { - if (portal.getNormal().y > 0 && otherNormal.y > 0) { - immediateFinalRot = immediateFinalRot.hamiltonProduct(IPQuaternion.rotationByDegrees(new Vec3(0, 1, 0), 180)); - } else { - finalYaw -= 180; - } - } - } - - final Vec3 dest = portal.getDestination().get().add(rotatedOffsets).add(teleportOffsetNoRotate); - - return new TeleportResult( - dest, - finalYaw, - finalPitch, - rotatedVel, - immediateFinalRot - ); - } - - public static boolean portalHudModeServerOrClient(Level level) { - return level.getGameRules().getRule(PortalCubedGameRules.USE_PORTAL_HUD).get() || (level.isClientSide && PortalCubedClient.isPortalHudModeServer()); - } - - public static ResourceLocation id(String path) { - return path.indexOf(':') >= 0 ? new ResourceLocation(path) : new ResourceLocation(MOD_ID, path); - } + public static final String MOD_ID = "portalcubed"; + + public static final Logger LOGGER = LogUtils.getLogger(); + + public static final MenuType FAITH_PLATE_SCREEN_HANDLER = Registry.register( + BuiltInRegistries.MENU, id("faith_plate_screen"), + new ExtendedScreenHandlerType<>(FaithPlateScreenHandler::new) + ); + public static final MenuType VELOCITY_HELPER_SCREEN_HANDLER = BlockPosScreenHandler.registerNew("velocity_helper"); + + public static final double MAX_SPEED = 2225 / 64.0 / 20.0, MAX_SPEED_SQR = MAX_SPEED * MAX_SPEED; + + public static final Map> TOOLTIPS = new HashMap<>(); + + @Override + public void onInitialize(ModContainer mod) { + ServerPlayNetworking.registerGlobalReceiver(id("use_portal"), (server, player, handler, buf, responseSender) -> { + // read the velocity from the byte buf + final int targetEntityId = buf.readVarInt(); + float yawSet = buf.readFloat(); + float pitchSet = buf.readFloat(); + Optional currentAnimationDelta = buf.readOptional(b -> new IPQuaternion( + b.readDouble(), + b.readDouble(), + b.readDouble(), + b.readDouble() + )); + final Vec3 entityVelocity = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); + final Vec3 teleportOffset = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); + final Vec3 teleportOffsetNoRotate = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); + if (!Float.isFinite(yawSet)) { + handler.disconnect(Component.translatable("multiplayer.disconnect.invalid_player_movement")); + return; + } + server.execute(() -> { + boolean rubberband = false; + if (!(player.level().getEntity(targetEntityId) instanceof Portal portal)) { + LOGGER.warn("{} tried to teleport through nonexistent portal", player); + handler.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + CalledValues.setIsTeleporting(player, false); + GravityChangerAPI.clearGravity(player); + return; + } + if (portal.position().distanceToSqr(player.position()) > 10 * 10) { + LOGGER.warn("{} tried to teleport through distant portal ({})", player, portal.position().distanceTo(player.position())); + rubberband = true; + } + if (portal.getDestination().isEmpty()) { + LOGGER.warn("{} tried to teleport through an inactive portal ({}).", player, portal); + rubberband = true; + } + if (teleportOffset.lengthSqr() > 10 * 10) { + LOGGER.warn("{} tried to use a huge teleportOffset ({}).", player, teleportOffset.length()); + rubberband = true; + } + if (rubberband) { + handler.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + CalledValues.setIsTeleporting(player, false); + GravityChangerAPI.clearGravity(player); + return; + } + + final TeleportResult result = commonTeleport( + portal, + entityVelocity, + teleportOffset, + teleportOffsetNoRotate, + player, + currentAnimationDelta, + pitchSet, yawSet + ); +// CalledValues.setVelocityUpdateAfterTeleport(player, result.velocity()); + + final Vec3 dest = result.dest(); +// final IPQuaternion cameraAnimation = IPQuaternion.getCameraRotation(result.pitch(), result.yaw()) +// .getConjugated() +// .hamiltonProduct(result.immediateFinalRot()); +// player.connection.teleport(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); + player.moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); + player.setDeltaMovement(result.velocity()); + player.connection.resetPosition(); +// final FriendlyByteBuf buf2 = PacketByteBufs.create(); +// buf2.writeDouble(cameraAnimation.x); +// buf2.writeDouble(cameraAnimation.y); +// buf2.writeDouble(cameraAnimation.z); +// buf2.writeDouble(cameraAnimation.w); +// ServerPlayNetworking.send(player, PortalCubedClientPackets.SET_CAMERA_INTERPOLATE, buf2); + +// CalledValues.setHasTeleportationHappened(player, true); + GravityChangerAPI.clearGravity(player); + + }); + }); + + ServerPlayNetworking.registerGlobalReceiver(id("configure_faith_plate"), (server, player, handler, buf, responseSender) -> { + // read the velocity from the byte buf + BlockPos target = buf.readBlockPos(); + double x = buf.readDouble(); + double y = buf.readDouble(); + double z = buf.readDouble(); + server.execute(() -> { + final BlockEntity entity = player.level().getBlockEntity(target); + if (entity instanceof FaithPlateBlockEntity faithPlateBlockEntity) { + faithPlateBlockEntity.setVelX(x); + faithPlateBlockEntity.setVelY(y); + faithPlateBlockEntity.setVelZ(z); + faithPlateBlockEntity.updateListeners(); + } + }); + }); + + ServerPlayNetworking.registerGlobalReceiver(id("client_teleport_update"), (server, player, handler, buf, responseSender) -> + server.execute(() -> CalledValues.setHasTeleportationHappened(player, false)) + ); + + ServerPlayNetworking.registerGlobalReceiver(id("request_velocity_for_gel"), (server, player, handler, buf, responseSender) -> { + final Vec3 entityVelocity = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); + final boolean fireGel = buf.readBoolean(); + server.execute(() -> { + CalledValues.setServerVelForGel(player, entityVelocity); + CalledValues.setCanFireGel(player, fireGel); + + }); + }); + + ServerPlayNetworking.registerGlobalReceiver(id("cube_pos_update"), (server, player, handler, buf, responseSender) -> { + // read the velocity from the byte buf + double x = buf.readDouble(); + double y = buf.readDouble(); + double z = buf.readDouble(); + double lastX = buf.readDouble(); + double lastY = buf.readDouble(); + double lastZ = buf.readDouble(); + float rotYaw = buf.readFloat(); + UUID cubeuuid = buf.readUUID(); + server.execute(() -> { + if (!(player.serverLevel().getEntity(cubeuuid) instanceof CorePhysicsEntity cube)) { + LOGGER.warn("{} tried to drop nonexistent physics object", player); + return; + } + if (!player.getUUID().equals(cube.getHolderUUID().orElse(null))) { + LOGGER.warn("{} tried to drop another player's physics object (held by {})", player, cube.getHolderUUID()); + return; + } + cube.setRotYaw(rotYaw); + Vec3 cubePos = new Vec3(x, y, z); + Vec3 lastCubePos = new Vec3(lastX, lastY, lastZ); + if (cubePos.distanceToSqr(lastCubePos) > 10 * 10) { + LOGGER.warn("{} tried to throw a physics object really fast ({})", player, cubePos.distanceTo(lastCubePos)); + return; + } + + cube.setPos(cubePos); + cube.setDeltaMovement(RotationUtil.vecWorldToPlayer(cubePos.subtract(lastCubePos), GravityChangerAPI.getGravityDirection(cube)).scale(.5)); + }); + }); + + ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { + if (!handler.player.level().getGameRules().getBoolean(PortalCubedGameRules.ALLOW_CROUCH_FLY_GLITCH)) { + // Default is true on the client, so we don't need to send in that case + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBoolean(false); + handler.send(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_CFG, buf)); + } + if (handler.player.level().getGameRules().getBoolean(PortalCubedGameRules.USE_PORTAL_HUD)) { + // Same as above, but false + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBoolean(true); + handler.send(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_PORTAL_HUD, buf)); + } + syncFog(handler.player); + }); + + EntityWorldChangeEvents.AFTER_PLAYER_WORLD_CHANGE.register((player, origin, destination) -> syncFog(player)); + + ServerPlayerEntityCopyCallback.EVENT.register((copy, original, wasDeath) -> syncFog(copy)); + + UseBlockCallback.EVENT.register((player, world, hand, hitResult) -> + portalHudModeServerOrClient(world) && + (!(world.getBlockState(hitResult.getBlockPos()).getBlock() instanceof TallButtonVariant) || + hand != InteractionHand.OFF_HAND) + ? InteractionResult.FAIL : InteractionResult.PASS + ); + + MidnightConfig.init("portalcubed", PortalCubedConfig.class); + + PortalBlocksLoader.init(mod); + PortalCubedFluids.registerFluids(); + PortalCubedBlocks.registerBlocks(); + PortalCubedItems.registerItems(); + PortalCubedEntities.registerEntities(); + PortalCubedTrackedDataHandlers.register(); + PortalCubedServerPackets.registerPackets(); + PortalCubedSounds.registerSounds(); + PortalCubedGameRules.register(); + PortalCubedParticleTypes.register(); + PortalCubedAdvancements.register(); + + PortalTabsLoader.load(mod); + BlockContentRegistries.FLAMMABLE.put(PortalCubedBlocks.NEUROTOXIN_BLOCK, new FlammableBlockEntry(10000, 10000)); + GravityChannel.UPDATE_GRAVITY.getVerifierRegistry().register(AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, AdhesionGravityVerifier::check); + + CommandRegistrationCallback.EVENT.register(new PortalCubedCommands()); + + if (QuiltLoader.isModLoaded("create")) { + LOGGER.warn("Create is out for this game version! Go poke the Portal Cubed developers on Discord to re-enable this integration."); +// CreateIntegration.init(); + } + + RayonIntegration.INSTANCE.init(); + + CommandRegistrationCallback.EVENT.register(((dispatcher, buildContext, environment) -> SpawnArmorTrimsCommand.register(dispatcher))); + + final JsonObject tooltipData; + try { + tooltipData = GsonHelper.parse(Files.newBufferedReader(mod.getPath("tooltips.json"))); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + for (final var entry : tooltipData.entrySet()) { + final List output = TOOLTIPS.computeIfAbsent(id(entry.getKey()), k -> new ArrayList<>()); + for (final JsonElement value : GsonHelper.convertToJsonArray(entry.getValue(), "tooltips")) { + output.add(Component.Serializer.fromJson(value)); + } + } + } + + public static void syncFog(ServerPlayer player) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + FogSettings.encodeOptional(FogPersistentState.getOrCreate(player.serverLevel()).getSettings(), buf); + ServerPlayNetworking.send(player, PortalCubedClientPackets.SET_CUSTOM_FOG, buf); + } + + public static void syncFog(ServerLevel world) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + FogSettings.encodeOptional(FogPersistentState.getOrCreate(world).getSettings(), buf); + world.getServer().getPlayerList().broadcastAll( + ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.SET_CUSTOM_FOG, buf), + world.dimension() + ); + } + + public static void playBounceSound(Entity entity) { + entity.level().playSound( + null, + entity.position().x(), entity.position().y(), entity.position().z(), + PortalCubedSounds.GEL_BOUNCE_EVENT, SoundSource.BLOCKS, + 1f, 0.95f + entity.level().random.nextFloat() * 0.1f + ); + } + + @ClientOnly + public static void playBounceSoundRemotely() { + ClientPlayNetworking.send(PortalCubedServerPackets.PLAY_BOUNCE_SOUND, PacketByteBufs.empty()); + } + + public static TeleportResult commonTeleport( + Portal portal, + Vec3 entityVelocity, + Vec3 teleportOffset, + Vec3 teleportOffsetNoRotate, + Entity entity, + Optional currentAnimationDelta, + float pitchSet, float yawSet + ) { + assert portal.getDestination().isPresent(); + assert portal.getOtherNormal().isPresent(); + + final Direction direction = portal.getFacingDirection(); + final Vec3 otherNormal = portal.getOtherNormal().get(); + Direction otherDirec = Direction.getNearest(otherNormal.x(), otherNormal.y(), otherNormal.z()); + final IPQuaternion portalTransform = portal.getTransformQuat(); + + Vec3 rotatedVel = entityVelocity; + Vec3 rotatedOffsets = teleportOffset; + + rotatedVel = portalTransform.rotate(rotatedVel, false); + rotatedOffsets = portalTransform.rotate(rotatedOffsets, false); + + if (otherDirec == Direction.UP && rotatedVel.y < 0.48) { + rotatedVel = new Vec3(rotatedVel.x, 0.48, rotatedVel.z); + } + + if (direction.getAxis().isHorizontal() && otherDirec.getAxis().isHorizontal()) { + rotatedOffsets = rotatedOffsets.subtract(0, entity.getEyeY() - entity.getY(), 0); + if (rotatedOffsets.y < -0.95) { + rotatedOffsets = new Vec3(rotatedOffsets.x, -0.95, rotatedOffsets.z); + } else if (rotatedOffsets.y > -0.95 + (1.9 - entity.getBbHeight())) { + rotatedOffsets = new Vec3(rotatedOffsets.x, -0.95 + (1.9 - entity.getBbHeight()), rotatedOffsets.z); + } + } + + if (rotatedVel.lengthSqr() > PortalCubed.MAX_SPEED_SQR) { + rotatedVel = rotatedVel.scale(PortalCubed.MAX_SPEED / rotatedVel.length()); + } + + IPQuaternion oldCameraRotation = IPQuaternion.getCameraRotation(pitchSet, yawSet); + if (currentAnimationDelta.isPresent()) { + oldCameraRotation = oldCameraRotation.hamiltonProduct(currentAnimationDelta.get()); + } + IPQuaternion immediateFinalRot = oldCameraRotation.hamiltonProduct(portalTransform.getConjugated()); + final Vector3d euler = immediateFinalRot.toQuaterniond().getEulerAnglesZXY(new Vector3d()); + float finalYaw = (float)Math.toDegrees(euler.y) + 180; + float finalPitch = (float)Math.toDegrees(euler.x); + + if (entity instanceof Player) { + boolean tweak = false; + if (finalPitch <= -50 && pitchSet >= 50) { + finalPitch = -90; + tweak = true; + } else if (finalPitch >= 50 && pitchSet <= -50) { + finalPitch = 90; + tweak = true; + } + if (tweak) { + if (portal.getNormal().y > 0 && otherNormal.y > 0) { + immediateFinalRot = immediateFinalRot.hamiltonProduct(IPQuaternion.rotationByDegrees(new Vec3(0, 1, 0), 180)); + } else { + finalYaw -= 180; + } + } + } + + final Vec3 dest = portal.getDestination().get().add(rotatedOffsets).add(teleportOffsetNoRotate); + + return new TeleportResult( + dest, + finalYaw, + finalPitch, + rotatedVel, + immediateFinalRot + ); + } + + public static boolean portalHudModeServerOrClient(Level level) { + return level.getGameRules().getRule(PortalCubedGameRules.USE_PORTAL_HUD).get() || (level.isClientSide && PortalCubedClient.isPortalHudModeServer()); + } + + public static ResourceLocation id(String path) { + return path.indexOf(':') >= 0 ? new ResourceLocation(path) : new ResourceLocation(MOD_ID, path); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/PortalCubedConfig.java b/src/main/java/com/fusionflux/portalcubed/PortalCubedConfig.java index b3a355db..8ec64838 100644 --- a/src/main/java/com/fusionflux/portalcubed/PortalCubedConfig.java +++ b/src/main/java/com/fusionflux/portalcubed/PortalCubedConfig.java @@ -6,17 +6,17 @@ @SuppressWarnings("CanBeFinal") public class PortalCubedConfig extends MidnightConfig { - @Entry @Client public static boolean enableRoundPortals = false; - @Entry public static boolean enableAccurateMovement = true; - @Entry public static int maxBridgeLength = 127; - @Entry public static float fizzlerDamage = 35; - @Entry public static float rocketDamage = 35; - @Entry public static float pelletDamage = 35; - @Entry public static float laserDamage = 3; - @Entry @Client public static boolean portalHudMode = false; - @Entry(min = 0, max = 100, isSlider = true) @Client public static int gelOverlayOpacity = 100; - @Entry @Client public static boolean staticPortalItemDrops = true; - @Entry @Client public static PortalRenderers renderer = PortalRenderers.DISABLED; - @Entry @Client public static boolean crossPortalEntityRendering = true; - @Entry(min = 0, max = 1000, isSlider = true) @Client public static int portalSmoothTime = 250; + @Entry @Client public static boolean enableRoundPortals = false; + @Entry public static boolean enableAccurateMovement = true; + @Entry public static int maxBridgeLength = 127; + @Entry public static float fizzlerDamage = 35; + @Entry public static float rocketDamage = 35; + @Entry public static float pelletDamage = 35; + @Entry public static float laserDamage = 3; + @Entry @Client public static boolean portalHudMode = false; + @Entry(min = 0, max = 100, isSlider = true) @Client public static int gelOverlayOpacity = 100; + @Entry @Client public static boolean staticPortalItemDrops = true; + @Entry @Client public static PortalRenderers renderer = PortalRenderers.DISABLED; + @Entry @Client public static boolean crossPortalEntityRendering = true; + @Entry(min = 0, max = 1000, isSlider = true) @Client public static int portalSmoothTime = 250; } diff --git a/src/main/java/com/fusionflux/portalcubed/PortalCubedGameRules.java b/src/main/java/com/fusionflux/portalcubed/PortalCubedGameRules.java index b68969d8..d8d0cca1 100644 --- a/src/main/java/com/fusionflux/portalcubed/PortalCubedGameRules.java +++ b/src/main/java/com/fusionflux/portalcubed/PortalCubedGameRules.java @@ -14,33 +14,33 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedGameRules { - public static final CustomGameRuleCategory CATEGORY = new CustomGameRuleCategory( - id(PortalCubed.MOD_ID), - Component.translatable("gamerule.category.portalcubed") - .withStyle(ChatFormatting.BOLD, ChatFormatting.YELLOW) - ); + public static final CustomGameRuleCategory CATEGORY = new CustomGameRuleCategory( + id(PortalCubed.MOD_ID), + Component.translatable("gamerule.category.portalcubed") + .withStyle(ChatFormatting.BOLD, ChatFormatting.YELLOW) + ); - public static final GameRules.Key ALLOW_CROUCH_FLY_GLITCH = GameRuleRegistry.register( - "allowCrouchFlyGlitch", CATEGORY, GameRuleFactory.createBooleanRule(true, (server, rule) -> { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBoolean(rule.get()); - server.getPlayerList().broadcastAll(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_CFG, buf)); - }) - ); - public static final GameRules.Key PORTAL_ALIGNMENT = GameRuleRegistry.register( - "portalAlignment", CATEGORY, GameRuleFactory.createIntRule(16, 0) - ); - public static final GameRules.Key DISABLE_PORTAL_VALIDATION = GameRuleRegistry.register( - "disablePortalValidation", CATEGORY, GameRuleFactory.createBooleanRule(false) - ); - public static final GameRules.Key USE_PORTAL_HUD = GameRuleRegistry.register( - "usePortalHud", CATEGORY, GameRuleFactory.createBooleanRule(false, (server, rule) -> { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBoolean(rule.get()); - server.getPlayerList().broadcastAll(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_PORTAL_HUD, buf)); - }) - ); + public static final GameRules.Key ALLOW_CROUCH_FLY_GLITCH = GameRuleRegistry.register( + "allowCrouchFlyGlitch", CATEGORY, GameRuleFactory.createBooleanRule(true, (server, rule) -> { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBoolean(rule.get()); + server.getPlayerList().broadcastAll(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_CFG, buf)); + }) + ); + public static final GameRules.Key PORTAL_ALIGNMENT = GameRuleRegistry.register( + "portalAlignment", CATEGORY, GameRuleFactory.createIntRule(16, 0) + ); + public static final GameRules.Key DISABLE_PORTAL_VALIDATION = GameRuleRegistry.register( + "disablePortalValidation", CATEGORY, GameRuleFactory.createBooleanRule(false) + ); + public static final GameRules.Key USE_PORTAL_HUD = GameRuleRegistry.register( + "usePortalHud", CATEGORY, GameRuleFactory.createBooleanRule(false, (server, rule) -> { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBoolean(rule.get()); + server.getPlayerList().broadcastAll(ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.ENABLE_PORTAL_HUD, buf)); + }) + ); - public static void register() { - } + public static void register() { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/PortalTabsLoader.java b/src/main/java/com/fusionflux/portalcubed/PortalTabsLoader.java index 7fb7d085..198fe5b5 100644 --- a/src/main/java/com/fusionflux/portalcubed/PortalTabsLoader.java +++ b/src/main/java/com/fusionflux/portalcubed/PortalTabsLoader.java @@ -35,135 +35,135 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalTabsLoader { - private static final Map>> CONDITION_TYPES = Map.of( - "and", o -> GsonHelper.getAsJsonArray(o, "conditions") - .asList() - .stream() - .map(PortalTabsLoader::parseCondition) - .reduce(Predicate::and) - .orElse(e -> true), - "or", o -> GsonHelper.getAsJsonArray(o, "conditions") - .asList() - .stream() - .map(PortalTabsLoader::parseCondition) - .reduce(Predicate::or) - .orElse(e -> false), - "not", o -> parseCondition(o.get("condition")).negate(), - "hasPermissions", o -> CreativeModeTab.ItemDisplayParameters::hasPermissions, - "hasFeatures", o -> { - final FeatureFlagSet flags = FeatureFlags.REGISTRY.fromNames( - GsonHelper.getAsJsonArray(o, "flags") - .asList() - .stream() - .map(e -> new ResourceLocation(GsonHelper.convertToString(e, "flag"))) - ::iterator - ); - return p -> flags.isSubsetOf(p.enabledFeatures()); - } - ); + private static final Map>> CONDITION_TYPES = Map.of( + "and", o -> GsonHelper.getAsJsonArray(o, "conditions") + .asList() + .stream() + .map(PortalTabsLoader::parseCondition) + .reduce(Predicate::and) + .orElse(e -> true), + "or", o -> GsonHelper.getAsJsonArray(o, "conditions") + .asList() + .stream() + .map(PortalTabsLoader::parseCondition) + .reduce(Predicate::or) + .orElse(e -> false), + "not", o -> parseCondition(o.get("condition")).negate(), + "hasPermissions", o -> CreativeModeTab.ItemDisplayParameters::hasPermissions, + "hasFeatures", o -> { + final FeatureFlagSet flags = FeatureFlags.REGISTRY.fromNames( + GsonHelper.getAsJsonArray(o, "flags") + .asList() + .stream() + .map(e -> new ResourceLocation(GsonHelper.convertToString(e, "flag"))) + ::iterator + ); + return p -> flags.isSubsetOf(p.enabledFeatures()); + } + ); - public static void load(ModContainer mod) { - final JsonObject jsonObject; - try (Reader reader = Files.newBufferedReader(mod.getPath("portal_tabs.json"))) { - jsonObject = GsonHelper.parse(reader); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - load(jsonObject); - } + public static void load(ModContainer mod) { + final JsonObject jsonObject; + try (Reader reader = Files.newBufferedReader(mod.getPath("portal_tabs.json"))) { + jsonObject = GsonHelper.parse(reader); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + load(jsonObject); + } - private static void load(JsonObject jsonObject) { - for (final var entry : jsonObject.entrySet()) { - final CreativeModeTab.Builder builder = FabricItemGroup.builder(); - final JsonObject entryData = GsonHelper.convertToJsonObject(entry.getValue(), "tab"); - if (entryData.has("title")) { - builder.title(Component.Serializer.fromJson(entryData.get("title"))); - } - if (entryData.has("icon")) { - builder.icon(parseItemStack(entryData.get("icon"), "icon")); - } - if (entryData.has("rightAlign") && GsonHelper.getAsBoolean(entryData, "rightAlign")) { - builder.alignedRight(); - } - if (entryData.has("showTitle") && !GsonHelper.getAsBoolean(entryData, "showTitle")) { - builder.hideTitle(); - } - if (entryData.has("scrollBar") && !GsonHelper.getAsBoolean(entryData, "scrollBar")) { - builder.noScrollBar(); - } - if (entryData.has("backgroundImage")) { - builder.backgroundSuffix(GsonHelper.getAsString(entryData, "backgroundImage")); - } - if (entryData.has("items")) { - final var items = GsonHelper.getAsJsonArray(entryData, "items") - .asList() - .stream() - .map(e -> { - if (e.isJsonPrimitive() || (e.isJsonObject() && !e.getAsJsonObject().has("condition"))) { - return Pair.of( - (Predicate)p -> true, - List.of(parseItemStack(e, "item").get()) - ); - } - return Pair.of(parseCondition(e), parseItemArray((JsonObject)e)); - }) - .toList(); - builder.displayItems((itemDisplayParameters, output) -> { - for (final var condition : items) { - if (condition.key().test(itemDisplayParameters)) { - output.acceptAll(condition.value()); - } - } - }); - } - Registry.register(BuiltInRegistries.CREATIVE_MODE_TAB, id(entry.getKey()), builder.build()); - } - } + private static void load(JsonObject jsonObject) { + for (final var entry : jsonObject.entrySet()) { + final CreativeModeTab.Builder builder = FabricItemGroup.builder(); + final JsonObject entryData = GsonHelper.convertToJsonObject(entry.getValue(), "tab"); + if (entryData.has("title")) { + builder.title(Component.Serializer.fromJson(entryData.get("title"))); + } + if (entryData.has("icon")) { + builder.icon(parseItemStack(entryData.get("icon"), "icon")); + } + if (entryData.has("rightAlign") && GsonHelper.getAsBoolean(entryData, "rightAlign")) { + builder.alignedRight(); + } + if (entryData.has("showTitle") && !GsonHelper.getAsBoolean(entryData, "showTitle")) { + builder.hideTitle(); + } + if (entryData.has("scrollBar") && !GsonHelper.getAsBoolean(entryData, "scrollBar")) { + builder.noScrollBar(); + } + if (entryData.has("backgroundImage")) { + builder.backgroundSuffix(GsonHelper.getAsString(entryData, "backgroundImage")); + } + if (entryData.has("items")) { + final var items = GsonHelper.getAsJsonArray(entryData, "items") + .asList() + .stream() + .map(e -> { + if (e.isJsonPrimitive() || (e.isJsonObject() && !e.getAsJsonObject().has("condition"))) { + return Pair.of( + (Predicate)p -> true, + List.of(parseItemStack(e, "item").get()) + ); + } + return Pair.of(parseCondition(e), parseItemArray((JsonObject)e)); + }) + .toList(); + builder.displayItems((itemDisplayParameters, output) -> { + for (final var condition : items) { + if (condition.key().test(itemDisplayParameters)) { + output.acceptAll(condition.value()); + } + } + }); + } + Registry.register(BuiltInRegistries.CREATIVE_MODE_TAB, id(entry.getKey()), builder.build()); + } + } - private static List parseItemArray(JsonObject owner) { - return GsonHelper.getAsJsonArray(owner, "items", new JsonArray()) - .asList() - .stream() - .map(e -> parseItemStack(e, "item").get()) - .toList(); - } + private static List parseItemArray(JsonObject owner) { + return GsonHelper.getAsJsonArray(owner, "items", new JsonArray()) + .asList() + .stream() + .map(e -> parseItemStack(e, "item").get()) + .toList(); + } - private static Supplier parseItemStack(JsonElement element, String memberName) { - if (element.isJsonPrimitive()) { - final Item item = getItem(GsonHelper.convertToString(element, memberName)); - return () -> new ItemStack(item); - } - final JsonObject object = GsonHelper.convertToJsonObject(element, memberName); - final Item item = getItem(GsonHelper.getAsString(object, "id")); - final int count = object.has("count") ? GsonHelper.getAsInt(object, "count") : 1; - final CompoundTag tag; - try { - tag = object.has("nbt") - ? new TagParser(new StringReader(GsonHelper.getAsString(object, "nbt"))).readStruct() - : null; - } catch (CommandSyntaxException e) { - throw new RuntimeException(e); - } - return () -> { - final ItemStack stack = new ItemStack(item, count); - if (tag != null) { - stack.setTag(tag); - } - return stack; - }; - } + private static Supplier parseItemStack(JsonElement element, String memberName) { + if (element.isJsonPrimitive()) { + final Item item = getItem(GsonHelper.convertToString(element, memberName)); + return () -> new ItemStack(item); + } + final JsonObject object = GsonHelper.convertToJsonObject(element, memberName); + final Item item = getItem(GsonHelper.getAsString(object, "id")); + final int count = object.has("count") ? GsonHelper.getAsInt(object, "count") : 1; + final CompoundTag tag; + try { + tag = object.has("nbt") + ? new TagParser(new StringReader(GsonHelper.getAsString(object, "nbt"))).readStruct() + : null; + } catch (CommandSyntaxException e) { + throw new RuntimeException(e); + } + return () -> { + final ItemStack stack = new ItemStack(item, count); + if (tag != null) { + stack.setTag(tag); + } + return stack; + }; + } - private static Predicate parseCondition(JsonElement element) { - final JsonObject object = GsonHelper.convertToJsonObject(element, "condition"); - return CONDITION_TYPES.get(GsonHelper.getAsString(object, "condition")).apply(object); - } + private static Predicate parseCondition(JsonElement element) { + final JsonObject object = GsonHelper.convertToJsonObject(element, "condition"); + return CONDITION_TYPES.get(GsonHelper.getAsString(object, "condition")).apply(object); + } - private static Item getItem(String id) { - final ResourceLocation path = new ResourceLocation(id); - final Item item = BuiltInRegistries.ITEM.get(path); - if (item == Items.AIR) { - throw new IllegalArgumentException("Unknown item " + id); - } - return item; - } + private static Item getItem(String id) { + final ResourceLocation path = new ResourceLocation(id); + final Item item = BuiltInRegistries.ITEM.get(path); + if (item == Items.AIR) { + throw new IllegalArgumentException("Unknown item " + id); + } + return item; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/TeleportResult.java b/src/main/java/com/fusionflux/portalcubed/TeleportResult.java index 9efc1032..d3b80137 100644 --- a/src/main/java/com/fusionflux/portalcubed/TeleportResult.java +++ b/src/main/java/com/fusionflux/portalcubed/TeleportResult.java @@ -4,10 +4,10 @@ import net.minecraft.world.phys.Vec3; public record TeleportResult( - Vec3 dest, - float yaw, - float pitch, - Vec3 velocity, - IPQuaternion immediateFinalRot + Vec3 dest, + float yaw, + float pitch, + Vec3 velocity, + IPQuaternion immediateFinalRot ) { } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/AdvancedRaycastResultHolder.java b/src/main/java/com/fusionflux/portalcubed/accessor/AdvancedRaycastResultHolder.java index 2d131e79..cc8790a5 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/AdvancedRaycastResultHolder.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/AdvancedRaycastResultHolder.java @@ -5,6 +5,6 @@ import java.util.Optional; public interface AdvancedRaycastResultHolder { - Optional getResult(); - void setResult(Optional result); + Optional getResult(); + void setResult(Optional result); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/BakedQuadExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/BakedQuadExt.java index 747c3b42..fb91e66f 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/BakedQuadExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/BakedQuadExt.java @@ -3,8 +3,8 @@ import org.jetbrains.annotations.Nullable; public interface BakedQuadExt { - @Nullable - String portalcubed$getRenderType(); + @Nullable + String portalcubed$getRenderType(); - void portalcubed$setRenderType(String type); + void portalcubed$setRenderType(String type); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionTrigger.java b/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionTrigger.java index 9e0f2da0..c671d530 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionTrigger.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionTrigger.java @@ -9,11 +9,11 @@ import net.minecraft.world.phys.shapes.VoxelShape; public interface BlockCollisionTrigger { - default void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { - } + default void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { + } - default void onEntityLeave(BlockState state, Level world, BlockPos pos, Entity entity) { - } + default void onEntityLeave(BlockState state, Level world, BlockPos pos, Entity entity) { + } - VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context); + VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionsExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionsExt.java index 4cddbe32..f338044b 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionsExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/BlockCollisionsExt.java @@ -4,5 +4,5 @@ import net.minecraft.world.phys.shapes.VoxelShape; public interface BlockCollisionsExt { - BlockCollisions setExtraShapes(VoxelShape cutout, VoxelShape crossCollision); + BlockCollisions setExtraShapes(VoxelShape cutout, VoxelShape crossCollision); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/BlockElementExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/BlockElementExt.java index 26fd6709..8e82b272 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/BlockElementExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/BlockElementExt.java @@ -3,8 +3,8 @@ import org.jetbrains.annotations.Nullable; public interface BlockElementExt { - @Nullable - String portalcubed$getRenderType(); + @Nullable + String portalcubed$getRenderType(); - void portalcubed$setRenderType(String type); + void portalcubed$setRenderType(String type); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/CalledValues.java b/src/main/java/com/fusionflux/portalcubed/accessor/CalledValues.java index 17c783b2..e8155fa2 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/CalledValues.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/CalledValues.java @@ -17,84 +17,84 @@ public abstract class CalledValues { - // workaround for a CCA bug; maybeGet throws an NPE in internal code if the DataTracker isn't initialized - // null check the component container to avoid it - // TODO: Check if this is still needed - @SuppressWarnings({"ConstantValue", "UnstableApiUsage"}) - private static Optional maybeGetSafe(ComponentKey key, @Nullable V provider) { - if (provider instanceof ComponentProvider p) { - var cc = p.getComponentContainer(); - if (cc != null) { - return Optional.ofNullable(key.getInternal(cc)); - } - } - return Optional.empty(); - } - - public static VoxelShape getPortalCutout(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getPortalCutout).orElse(Shapes.empty()); - } - - public static void setPortalCutout(Entity entity, VoxelShape setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setPortalCutout(setValue)); - } - - public static VoxelShape getCrossPortalCollision(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getCrossPortalCollision).orElse(Shapes.empty()); - } - - public static void setCrossPortalCollision(Entity entity, VoxelShape setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setCrossPortalCollision(setValue)); - } - - public static boolean getHasTeleportationHappened(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getHasTeleportationHappened).orElse(false); - } - - public static void setHasTeleportationHappened(Entity entity, boolean setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setHasTeleportationHappened(setValue)); - } - - public static boolean getIsTeleporting(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getWasInfiniteFalling).orElse(false); - } - public static void setIsTeleporting(Entity entity, boolean setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setWasInfiniteFalling(setValue)); - } - - public static Vec3 getVelocityUpdateAfterTeleport(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getVelocityUpdateAfterTeleport).orElse(null); - } - - public static void setVelocityUpdateAfterTeleport(Entity entity, Vec3 setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setVelocityUpdateAfterTeleport(setValue)); - } - - public static boolean getCanFireGel(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getCanFireGel).orElse(false); - } - public static void setCanFireGel(Entity entity, boolean setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setCanFireGel(setValue)); - } - - public static Vec3 getServerVelForGel(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getServerVelForGel).orElse(null); - } - - public static void setServerVelForGel(Entity entity, Vec3 setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setServerVelForGel(setValue)); - } - - public static Set getPortals(Entity entity) { - return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getPortals).orElse(Set.of()); - } - - public static void addPortals(Entity entity, UUID setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.addPortals(setValue)); - } - - public static void removePortals(Entity entity, UUID setValue) { - maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.removePortals(setValue)); - } + // workaround for a CCA bug; maybeGet throws an NPE in internal code if the DataTracker isn't initialized + // null check the component container to avoid it + // TODO: Check if this is still needed + @SuppressWarnings({"ConstantValue", "UnstableApiUsage"}) + private static Optional maybeGetSafe(ComponentKey key, @Nullable V provider) { + if (provider instanceof ComponentProvider p) { + var cc = p.getComponentContainer(); + if (cc != null) { + return Optional.ofNullable(key.getInternal(cc)); + } + } + return Optional.empty(); + } + + public static VoxelShape getPortalCutout(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getPortalCutout).orElse(Shapes.empty()); + } + + public static void setPortalCutout(Entity entity, VoxelShape setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setPortalCutout(setValue)); + } + + public static VoxelShape getCrossPortalCollision(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getCrossPortalCollision).orElse(Shapes.empty()); + } + + public static void setCrossPortalCollision(Entity entity, VoxelShape setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setCrossPortalCollision(setValue)); + } + + public static boolean getHasTeleportationHappened(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getHasTeleportationHappened).orElse(false); + } + + public static void setHasTeleportationHappened(Entity entity, boolean setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setHasTeleportationHappened(setValue)); + } + + public static boolean getIsTeleporting(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getWasInfiniteFalling).orElse(false); + } + public static void setIsTeleporting(Entity entity, boolean setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setWasInfiniteFalling(setValue)); + } + + public static Vec3 getVelocityUpdateAfterTeleport(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getVelocityUpdateAfterTeleport).orElse(null); + } + + public static void setVelocityUpdateAfterTeleport(Entity entity, Vec3 setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setVelocityUpdateAfterTeleport(setValue)); + } + + public static boolean getCanFireGel(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getCanFireGel).orElse(false); + } + public static void setCanFireGel(Entity entity, boolean setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setCanFireGel(setValue)); + } + + public static Vec3 getServerVelForGel(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getServerVelForGel).orElse(null); + } + + public static void setServerVelForGel(Entity entity, Vec3 setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.setServerVelForGel(setValue)); + } + + public static Set getPortals(Entity entity) { + return maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).map(PortalCubedComponent::getPortals).orElse(Set.of()); + } + + public static void addPortals(Entity entity, UUID setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.addPortals(setValue)); + } + + public static void removePortals(Entity entity, UUID setValue) { + maybeGetSafe(PortalCubedComponents.ENTITY_COMPONENT, entity).ifPresent(gc -> gc.removePortals(setValue)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/CameraExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/CameraExt.java index 67f68def..62e50d3e 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/CameraExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/CameraExt.java @@ -6,9 +6,9 @@ import net.minecraft.world.phys.Vec3; public interface CameraExt { - FluidState portalcubed$getSubmergedFluidState(); + FluidState portalcubed$getSubmergedFluidState(); - void updateSimple(BlockGetter area, Entity focusedEntity); + void updateSimple(BlockGetter area, Entity focusedEntity); - void backCameraUp(Vec3 from); + void backCameraUp(Vec3 from); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/EntityExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/EntityExt.java index 269f7e4f..13ab044a 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/EntityExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/EntityExt.java @@ -6,37 +6,37 @@ public interface EntityExt { - boolean isBounced(); + boolean isBounced(); - void setBounced(boolean bounced); + void setBounced(boolean bounced); - boolean isInFunnel(); + boolean isInFunnel(); - void setInFunnel(boolean inFunnel); + void setInFunnel(boolean inFunnel); - int getFunnelTimer(); + int getFunnelTimer(); - void setFunnelTimer(int funnelTimer); + void setFunnelTimer(int funnelTimer); - double getMaxFallSpeed(); + double getMaxFallSpeed(); - void setMaxFallSpeed(double maxFallSpeed); + void setMaxFallSpeed(double maxFallSpeed); - double getMaxFallHeight(); + double getMaxFallHeight(); - int getGelTimer(); + int getGelTimer(); - void setGelTimer(int funnelTimer); + void setGelTimer(int funnelTimer); - Vec3 getLastVel(); + Vec3 getLastVel(); - void setMaxFallHeight(double maxFallHeight); + void setMaxFallHeight(double maxFallHeight); - boolean cfg(); + boolean cfg(); - void setCFG(); + void setCFG(); - void collidedWithVelocityHelper(VelocityHelperBlockEntity block); + void collidedWithVelocityHelper(VelocityHelperBlockEntity block); - void collidedWithCatapult(CatapultBlockEntity block); + void collidedWithCatapult(CatapultBlockEntity block); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/GameRendererExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/GameRendererExt.java index 5fce25ca..ef6c49f3 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/GameRendererExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/GameRendererExt.java @@ -5,5 +5,5 @@ @ClientOnly public interface GameRendererExt { - void setMainCamera(Camera camera); + void setMainCamera(Camera camera); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/HasMovementInputAccessor.java b/src/main/java/com/fusionflux/portalcubed/accessor/HasMovementInputAccessor.java index 9dd43c09..f2114605 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/HasMovementInputAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/HasMovementInputAccessor.java @@ -2,6 +2,6 @@ public interface HasMovementInputAccessor { - boolean hasMovementInputPublic(); + boolean hasMovementInputPublic(); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/ItemInHandRendererExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/ItemInHandRendererExt.java index ab08fdec..301c71cd 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/ItemInHandRendererExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/ItemInHandRendererExt.java @@ -1,5 +1,5 @@ package com.fusionflux.portalcubed.accessor; public interface ItemInHandRendererExt { - void startHandFaker(); + void startHandFaker(); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/LevelExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/LevelExt.java index 21f90ad5..6bb1b35d 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/LevelExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/LevelExt.java @@ -8,12 +8,12 @@ import java.util.UUID; public interface LevelExt { - PortalCubedDamageSources pcDamageSources(); + PortalCubedDamageSources pcDamageSources(); - @Nullable - Entity getEntityByUuid(UUID uuid); + @Nullable + Entity getEntityByUuid(UUID uuid); - void pc$addBlockChangeListener(long sectionPos, EmittedEntity entity); + void pc$addBlockChangeListener(long sectionPos, EmittedEntity entity); - void pc$removeBlockChangeListener(long sectionPos, EmittedEntity entity); + void pc$removeBlockChangeListener(long sectionPos, EmittedEntity entity); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/LevelRendererExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/LevelRendererExt.java index 8d3078a4..f45976a8 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/LevelRendererExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/LevelRendererExt.java @@ -6,11 +6,11 @@ @ClientOnly public interface LevelRendererExt { - Frustum getCullingFrustum(); + Frustum getCullingFrustum(); - void setCullingFrustum(Frustum frustum); + void setCullingFrustum(Frustum frustum); - RenderBuffers getRenderBuffers(); + RenderBuffers getRenderBuffers(); - void setRenderBuffers(RenderBuffers buffers); + void setRenderBuffers(RenderBuffers buffers); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/LivingEntityAccessor.java b/src/main/java/com/fusionflux/portalcubed/accessor/LivingEntityAccessor.java index a171d4d9..9e7b5924 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/LivingEntityAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/LivingEntityAccessor.java @@ -1,5 +1,5 @@ package com.fusionflux.portalcubed.accessor; public interface LivingEntityAccessor { - boolean isJumping(); + boolean isJumping(); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/MinecraftExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/MinecraftExt.java index 3c727efb..f34f5610 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/MinecraftExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/MinecraftExt.java @@ -5,5 +5,5 @@ @ClientOnly public interface MinecraftExt { - void setRenderBuffers(RenderBuffers buffers); + void setRenderBuffers(RenderBuffers buffers); } diff --git a/src/main/java/com/fusionflux/portalcubed/accessor/RenderTargetExt.java b/src/main/java/com/fusionflux/portalcubed/accessor/RenderTargetExt.java index ade08737..6abc4c6c 100644 --- a/src/main/java/com/fusionflux/portalcubed/accessor/RenderTargetExt.java +++ b/src/main/java/com/fusionflux/portalcubed/accessor/RenderTargetExt.java @@ -1,7 +1,7 @@ package com.fusionflux.portalcubed.accessor; public interface RenderTargetExt { - boolean isStencilBufferEnabled(); + boolean isStencilBufferEnabled(); - void setStencilBufferEnabled(boolean enabled); + void setStencilBufferEnabled(boolean enabled); } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/PortalCubedAdvancements.java b/src/main/java/com/fusionflux/portalcubed/advancements/PortalCubedAdvancements.java index 3b5584b1..4b88b8aa 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/PortalCubedAdvancements.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/PortalCubedAdvancements.java @@ -5,9 +5,9 @@ import com.fusionflux.portalcubed.advancements.triggers.PortalCubedTriggers; public class PortalCubedAdvancements { - public static void register() { - PortalCubedConditions.register(); - PortalCubedPredicates.register(); - PortalCubedTriggers.register(); - } + public static void register() { + PortalCubedConditions.register(); + PortalCubedPredicates.register(); + PortalCubedTriggers.register(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/FunnelCondition.java b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/FunnelCondition.java index fbefd40b..3a069ade 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/FunnelCondition.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/FunnelCondition.java @@ -16,60 +16,60 @@ import java.util.Set; public class FunnelCondition implements LootItemCondition { - private final Boolean inFunnel; - private final Boolean inCfg; + private final Boolean inFunnel; + private final Boolean inCfg; - public FunnelCondition(Boolean inFunnel, Boolean inCfg) { - this.inFunnel = inFunnel; - this.inCfg = inCfg; - } + public FunnelCondition(Boolean inFunnel, Boolean inCfg) { + this.inFunnel = inFunnel; + this.inCfg = inCfg; + } - @NotNull - @Override - public LootItemConditionType getType() { - return PortalCubedConditions.FUNNEL; - } + @NotNull + @Override + public LootItemConditionType getType() { + return PortalCubedConditions.FUNNEL; + } - @NotNull - @Override - public Set> getReferencedContextParams() { - return ImmutableSet.of(LootContextParams.THIS_ENTITY); - } + @NotNull + @Override + public Set> getReferencedContextParams() { + return ImmutableSet.of(LootContextParams.THIS_ENTITY); + } - @Override - public boolean test(LootContext lootContext) { - if (inFunnel != null && ((EntityExt)lootContext.getParam(LootContextParams.THIS_ENTITY)).isInFunnel() != inFunnel) { - return false; - } - //noinspection RedundantIfStatement - if (inCfg != null && ((EntityExt)lootContext.getParam(LootContextParams.THIS_ENTITY)).cfg() != inCfg) { - return false; - } - return true; - } + @Override + public boolean test(LootContext lootContext) { + if (inFunnel != null && ((EntityExt)lootContext.getParam(LootContextParams.THIS_ENTITY)).isInFunnel() != inFunnel) { + return false; + } + //noinspection RedundantIfStatement + if (inCfg != null && ((EntityExt)lootContext.getParam(LootContextParams.THIS_ENTITY)).cfg() != inCfg) { + return false; + } + return true; + } - public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer { - @Override - public void serialize(JsonObject json, FunnelCondition value, JsonSerializationContext serializationContext) { - if (value.inFunnel != null) { - json.addProperty("in_funnel", value.inFunnel); - } - if (value.inCfg != null) { - json.addProperty("in_cfg", value.inCfg); - } - } + public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer { + @Override + public void serialize(JsonObject json, FunnelCondition value, JsonSerializationContext serializationContext) { + if (value.inFunnel != null) { + json.addProperty("in_funnel", value.inFunnel); + } + if (value.inCfg != null) { + json.addProperty("in_cfg", value.inCfg); + } + } - @NotNull - @Override - public FunnelCondition deserialize(JsonObject json, JsonDeserializationContext serializationContext) { - return new FunnelCondition( - getAsOptionalBoolean(json, "in_funnel"), - getAsOptionalBoolean(json, "in_cfg") - ); - } + @NotNull + @Override + public FunnelCondition deserialize(JsonObject json, JsonDeserializationContext serializationContext) { + return new FunnelCondition( + getAsOptionalBoolean(json, "in_funnel"), + getAsOptionalBoolean(json, "in_cfg") + ); + } - private static Boolean getAsOptionalBoolean(JsonObject json, String name) { - return json.has(name) ? GsonHelper.convertToBoolean(json.get(name), name) : null; - } - } + private static Boolean getAsOptionalBoolean(JsonObject json, String name) { + return json.has(name) ? GsonHelper.convertToBoolean(json.get(name), name) : null; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/LauncherCondition.java b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/LauncherCondition.java index 96a2846c..0ebee80b 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/LauncherCondition.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/LauncherCondition.java @@ -20,64 +20,64 @@ import java.util.Set; public class LauncherCondition implements LootItemCondition { - private final LocationPredicate location; - private final DistancePredicate distance; + private final LocationPredicate location; + private final DistancePredicate distance; - public LauncherCondition(LocationPredicate location, DistancePredicate distance) { - this.location = location; - this.distance = distance; - } + public LauncherCondition(LocationPredicate location, DistancePredicate distance) { + this.location = location; + this.distance = distance; + } - @NotNull - @Override - public LootItemConditionType getType() { - return PortalCubedConditions.LAUNCHER; - } + @NotNull + @Override + public LootItemConditionType getType() { + return PortalCubedConditions.LAUNCHER; + } - @NotNull - @Override - public Set> getReferencedContextParams() { - return ImmutableSet.of(LootContextParams.THIS_ENTITY); - } + @NotNull + @Override + public Set> getReferencedContextParams() { + return ImmutableSet.of(LootContextParams.THIS_ENTITY); + } - @Override - public boolean test(LootContext lootContext) { - final Entity thisEntity = lootContext.getParam(LootContextParams.THIS_ENTITY); - final BlockPos launcher = PortalCubedComponents.ENTITY_COMPONENT.get(thisEntity).getLauncher(); - if (launcher == null) { - return false; - } - if (!location.matches((ServerLevel)thisEntity.level(), launcher.getX() + 0.5, launcher.getY() + 0.5, launcher.getZ() + 0.5)) { - return false; - } - //noinspection RedundantIfStatement - if (!distance.matches( - thisEntity.getX(), thisEntity.getY(), thisEntity.getZ(), - launcher.getX() + 0.5, launcher.getY() + 0.5, launcher.getZ() + 0.5 - )) { - return false; - } - return true; - } + @Override + public boolean test(LootContext lootContext) { + final Entity thisEntity = lootContext.getParam(LootContextParams.THIS_ENTITY); + final BlockPos launcher = PortalCubedComponents.ENTITY_COMPONENT.get(thisEntity).getLauncher(); + if (launcher == null) { + return false; + } + if (!location.matches((ServerLevel)thisEntity.level(), launcher.getX() + 0.5, launcher.getY() + 0.5, launcher.getZ() + 0.5)) { + return false; + } + //noinspection RedundantIfStatement + if (!distance.matches( + thisEntity.getX(), thisEntity.getY(), thisEntity.getZ(), + launcher.getX() + 0.5, launcher.getY() + 0.5, launcher.getZ() + 0.5 + )) { + return false; + } + return true; + } - public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer { - @Override - public void serialize(JsonObject json, LauncherCondition value, JsonSerializationContext serializationContext) { - if (value.location != LocationPredicate.ANY) { - json.add("location", value.location.serializeToJson()); - } - if (value.distance != DistancePredicate.ANY) { - json.add("distance", value.distance.serializeToJson()); - } - } + public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer { + @Override + public void serialize(JsonObject json, LauncherCondition value, JsonSerializationContext serializationContext) { + if (value.location != LocationPredicate.ANY) { + json.add("location", value.location.serializeToJson()); + } + if (value.distance != DistancePredicate.ANY) { + json.add("distance", value.distance.serializeToJson()); + } + } - @NotNull - @Override - public LauncherCondition deserialize(JsonObject json, JsonDeserializationContext serializationContext) { - return new LauncherCondition( - LocationPredicate.fromJson(json.get("location")), - DistancePredicate.fromJson(json.get("distance")) - ); - } - } + @NotNull + @Override + public LauncherCondition deserialize(JsonObject json, JsonDeserializationContext serializationContext) { + return new LauncherCondition( + LocationPredicate.fromJson(json.get("location")), + DistancePredicate.fromJson(json.get("distance")) + ); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/PortalCubedConditions.java b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/PortalCubedConditions.java index 9c186d64..a7547339 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/conditions/PortalCubedConditions.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/conditions/PortalCubedConditions.java @@ -7,11 +7,11 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedConditions { - public static final LootItemConditionType FUNNEL = new LootItemConditionType(new FunnelCondition.Serializer()); - public static final LootItemConditionType LAUNCHER = new LootItemConditionType(new LauncherCondition.Serializer()); + public static final LootItemConditionType FUNNEL = new LootItemConditionType(new FunnelCondition.Serializer()); + public static final LootItemConditionType LAUNCHER = new LootItemConditionType(new LauncherCondition.Serializer()); - public static void register() { - Registry.register(BuiltInRegistries.LOOT_CONDITION_TYPE, id("funnel"), FUNNEL); - Registry.register(BuiltInRegistries.LOOT_CONDITION_TYPE, id("launcher"), LAUNCHER); - } + public static void register() { + Registry.register(BuiltInRegistries.LOOT_CONDITION_TYPE, id("funnel"), FUNNEL); + Registry.register(BuiltInRegistries.LOOT_CONDITION_TYPE, id("launcher"), LAUNCHER); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/predicates/EnergyPelletPredicate.java b/src/main/java/com/fusionflux/portalcubed/advancements/predicates/EnergyPelletPredicate.java index bcd781de..c4ae3c11 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/predicates/EnergyPelletPredicate.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/predicates/EnergyPelletPredicate.java @@ -12,70 +12,70 @@ import org.jetbrains.annotations.Nullable; public class EnergyPelletPredicate implements EntitySubPredicate { - private final MinMaxBounds.Ints startingLife; - private final MinMaxBounds.Ints life; - private final MinMaxBounds.Ints bounces; - private final EntityPredicate thrower; + private final MinMaxBounds.Ints startingLife; + private final MinMaxBounds.Ints life; + private final MinMaxBounds.Ints bounces; + private final EntityPredicate thrower; - public EnergyPelletPredicate(MinMaxBounds.Ints startingLife, MinMaxBounds.Ints life, MinMaxBounds.Ints bounces, EntityPredicate thrower) { - this.startingLife = startingLife; - this.life = life; - this.bounces = bounces; - this.thrower = thrower; - } + public EnergyPelletPredicate(MinMaxBounds.Ints startingLife, MinMaxBounds.Ints life, MinMaxBounds.Ints bounces, EntityPredicate thrower) { + this.startingLife = startingLife; + this.life = life; + this.bounces = bounces; + this.thrower = thrower; + } - public static EnergyPelletPredicate fromJson(JsonObject json) { - return new EnergyPelletPredicate( - MinMaxBounds.Ints.fromJson(json.get("starting_life")), - MinMaxBounds.Ints.fromJson(json.get("life")), - MinMaxBounds.Ints.fromJson(json.get("bounces")), - EntityPredicate.fromJson(json.get("thrower")) - ); - } + public static EnergyPelletPredicate fromJson(JsonObject json) { + return new EnergyPelletPredicate( + MinMaxBounds.Ints.fromJson(json.get("starting_life")), + MinMaxBounds.Ints.fromJson(json.get("life")), + MinMaxBounds.Ints.fromJson(json.get("bounces")), + EntityPredicate.fromJson(json.get("thrower")) + ); + } - @Override - public boolean matches(Entity entity, ServerLevel level, @Nullable Vec3 pos) { - if (!(entity instanceof EnergyPellet energyPellet)) { - return false; - } - if (!startingLife.matches(energyPellet.getStartingLife())) { - return false; - } - if (!life.matches(energyPellet.getLife())) { - return false; - } - if (!bounces.matches(energyPellet.getBounces())) { - return false; - } - //noinspection RedundantIfStatement - if (!thrower.matches(level, pos, energyPellet.getThrower())) { - return false; - } - return true; - } + @Override + public boolean matches(Entity entity, ServerLevel level, @Nullable Vec3 pos) { + if (!(entity instanceof EnergyPellet energyPellet)) { + return false; + } + if (!startingLife.matches(energyPellet.getStartingLife())) { + return false; + } + if (!life.matches(energyPellet.getLife())) { + return false; + } + if (!bounces.matches(energyPellet.getBounces())) { + return false; + } + //noinspection RedundantIfStatement + if (!thrower.matches(level, pos, energyPellet.getThrower())) { + return false; + } + return true; + } - @NotNull - @Override - public JsonObject serializeCustomData() { - final JsonObject result = new JsonObject(); - if (!startingLife.isAny()) { - result.add("starting_life", bounces.serializeToJson()); - } - if (!life.isAny()) { - result.add("life", bounces.serializeToJson()); - } - if (!bounces.isAny()) { - result.add("bounces", bounces.serializeToJson()); - } - if (thrower != EntityPredicate.ANY) { - result.add("thrower", thrower.serializeToJson()); - } - return result; - } + @NotNull + @Override + public JsonObject serializeCustomData() { + final JsonObject result = new JsonObject(); + if (!startingLife.isAny()) { + result.add("starting_life", bounces.serializeToJson()); + } + if (!life.isAny()) { + result.add("life", bounces.serializeToJson()); + } + if (!bounces.isAny()) { + result.add("bounces", bounces.serializeToJson()); + } + if (thrower != EntityPredicate.ANY) { + result.add("thrower", thrower.serializeToJson()); + } + return result; + } - @NotNull - @Override - public Type type() { - return PortalCubedPredicates.ENERGY_PELLET; - } + @NotNull + @Override + public Type type() { + return PortalCubedPredicates.ENERGY_PELLET; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/predicates/PortalCubedPredicates.java b/src/main/java/com/fusionflux/portalcubed/advancements/predicates/PortalCubedPredicates.java index 5e75a6ff..a8a3dd49 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/predicates/PortalCubedPredicates.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/predicates/PortalCubedPredicates.java @@ -3,9 +3,9 @@ import net.minecraft.advancements.critereon.EntitySubPredicate; public class PortalCubedPredicates { - public static final EntitySubPredicate.Type ENERGY_PELLET = EnergyPelletPredicate::fromJson; + public static final EntitySubPredicate.Type ENERGY_PELLET = EnergyPelletPredicate::fromJson; - public static void register() { - EntitySubPredicate.Types.TYPES.put("portalcubed:energy_pellet", ENERGY_PELLET); - } + public static void register() { + EntitySubPredicate.Types.TYPES.put("portalcubed:energy_pellet", ENERGY_PELLET); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/BounceTrigger.java b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/BounceTrigger.java index 7b3414c3..619f8b24 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/BounceTrigger.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/BounceTrigger.java @@ -13,44 +13,44 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BounceTrigger extends SimpleCriterionTrigger { - public static final ResourceLocation ID = id("bounce"); - - @NotNull - @Override - public ResourceLocation getId() { - return ID; - } - - @NotNull - @Override - protected TriggerInstance createInstance(JsonObject json, ContextAwarePredicate predicate, DeserializationContext deserializationContext) { - return new TriggerInstance(predicate, EntityPredicate.fromJson(json.get("pellet"))); - } - - public void trigger(ServerPlayer player, EnergyPellet pellet) { - trigger(player, conditions -> conditions.matches(player.serverLevel(), player.position(), pellet)); - } - - public static class TriggerInstance extends AbstractCriterionTriggerInstance { - private final EntityPredicate pellet; - - public TriggerInstance(ContextAwarePredicate player, EntityPredicate pellet) { - super(ID, player); - this.pellet = pellet; - } - - public boolean matches(ServerLevel level, @Nullable Vec3 position, EnergyPellet pellet) { - return this.pellet.matches(level, position, pellet); - } - - @NotNull - @Override - public JsonObject serializeToJson(SerializationContext context) { - final JsonObject result = super.serializeToJson(context); - if (pellet != EntityPredicate.ANY) { - result.add("pellet", pellet.serializeToJson()); - } - return result; - } - } + public static final ResourceLocation ID = id("bounce"); + + @NotNull + @Override + public ResourceLocation getId() { + return ID; + } + + @NotNull + @Override + protected TriggerInstance createInstance(JsonObject json, ContextAwarePredicate predicate, DeserializationContext deserializationContext) { + return new TriggerInstance(predicate, EntityPredicate.fromJson(json.get("pellet"))); + } + + public void trigger(ServerPlayer player, EnergyPellet pellet) { + trigger(player, conditions -> conditions.matches(player.serverLevel(), player.position(), pellet)); + } + + public static class TriggerInstance extends AbstractCriterionTriggerInstance { + private final EntityPredicate pellet; + + public TriggerInstance(ContextAwarePredicate player, EntityPredicate pellet) { + super(ID, player); + this.pellet = pellet; + } + + public boolean matches(ServerLevel level, @Nullable Vec3 position, EnergyPellet pellet) { + return this.pellet.matches(level, position, pellet); + } + + @NotNull + @Override + public JsonObject serializeToJson(SerializationContext context) { + final JsonObject result = super.serializeToJson(context); + if (pellet != EntityPredicate.ANY) { + result.add("pellet", pellet.serializeToJson()); + } + return result; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/FlingTrigger.java b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/FlingTrigger.java index 3742ba64..511a5769 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/FlingTrigger.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/FlingTrigger.java @@ -12,54 +12,54 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class FlingTrigger extends SimpleCriterionTrigger { - public static final ResourceLocation ID = id("fling"); + public static final ResourceLocation ID = id("fling"); - @NotNull - @Override - public ResourceLocation getId() { - return ID; - } + @NotNull + @Override + public ResourceLocation getId() { + return ID; + } - @NotNull - @Override - protected TriggerInstance createInstance(JsonObject json, ContextAwarePredicate predicate, DeserializationContext deserializationContext) { - return new TriggerInstance( - predicate, - LocationPredicate.fromJson(json.get("launcher")), - DistancePredicate.fromJson(json.get("force")) - ); - } + @NotNull + @Override + protected TriggerInstance createInstance(JsonObject json, ContextAwarePredicate predicate, DeserializationContext deserializationContext) { + return new TriggerInstance( + predicate, + LocationPredicate.fromJson(json.get("launcher")), + DistancePredicate.fromJson(json.get("force")) + ); + } - public void trigger(ServerPlayer player, BlockPos launcherPos, Vec3 launcherForce) { - trigger(player, conditions -> conditions.matches(player.serverLevel(), launcherPos, launcherForce)); - } + public void trigger(ServerPlayer player, BlockPos launcherPos, Vec3 launcherForce) { + trigger(player, conditions -> conditions.matches(player.serverLevel(), launcherPos, launcherForce)); + } - public static class TriggerInstance extends AbstractCriterionTriggerInstance { - private final LocationPredicate launcher; - private final DistancePredicate force; + public static class TriggerInstance extends AbstractCriterionTriggerInstance { + private final LocationPredicate launcher; + private final DistancePredicate force; - public TriggerInstance(ContextAwarePredicate player, LocationPredicate launcher, DistancePredicate force) { - super(ID, player); - this.launcher = launcher; - this.force = force; - } + public TriggerInstance(ContextAwarePredicate player, LocationPredicate launcher, DistancePredicate force) { + super(ID, player); + this.launcher = launcher; + this.force = force; + } - public boolean matches(ServerLevel level, BlockPos launcherPos, Vec3 launcherForce) { - return launcher.matches(level, launcherPos.getX() + 0.5, launcherPos.getY() + 0.5, launcherPos.getZ() + 0.5) && - force.matches(0, 0, 0, launcherForce.x, launcherForce.y, launcherForce.z); - } + public boolean matches(ServerLevel level, BlockPos launcherPos, Vec3 launcherForce) { + return launcher.matches(level, launcherPos.getX() + 0.5, launcherPos.getY() + 0.5, launcherPos.getZ() + 0.5) && + force.matches(0, 0, 0, launcherForce.x, launcherForce.y, launcherForce.z); + } - @NotNull - @Override - public JsonObject serializeToJson(SerializationContext context) { - final JsonObject result = super.serializeToJson(context); - if (launcher != LocationPredicate.ANY) { - result.add("launcher", launcher.serializeToJson()); - } - if (force != DistancePredicate.ANY) { - result.add("force", force.serializeToJson()); - } - return result; - } - } + @NotNull + @Override + public JsonObject serializeToJson(SerializationContext context) { + final JsonObject result = super.serializeToJson(context); + if (launcher != LocationPredicate.ANY) { + result.add("launcher", launcher.serializeToJson()); + } + if (force != DistancePredicate.ANY) { + result.add("force", force.serializeToJson()); + } + return result; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/PortalCubedTriggers.java b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/PortalCubedTriggers.java index e9edb798..1b4540ac 100644 --- a/src/main/java/com/fusionflux/portalcubed/advancements/triggers/PortalCubedTriggers.java +++ b/src/main/java/com/fusionflux/portalcubed/advancements/triggers/PortalCubedTriggers.java @@ -3,11 +3,11 @@ import net.minecraft.advancements.CriteriaTriggers; public class PortalCubedTriggers { - public static final BounceTrigger BOUNCE = new BounceTrigger(); - public static final FlingTrigger FLING = new FlingTrigger(); + public static final BounceTrigger BOUNCE = new BounceTrigger(); + public static final FlingTrigger FLING = new FlingTrigger(); - public static void register() { - CriteriaTriggers.register(BOUNCE); - CriteriaTriggers.register(FLING); - } + public static void register() { + CriteriaTriggers.register(BOUNCE); + CriteriaTriggers.register(FLING); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/AbstractLaserNodeBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/AbstractLaserNodeBlock.java index 86c057c5..8b5cef5b 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/AbstractLaserNodeBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/AbstractLaserNodeBlock.java @@ -23,73 +23,73 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public abstract class AbstractLaserNodeBlock extends BaseEntityBlock { - public static final BooleanProperty ENABLED = BlockStateProperties.ENABLED; + public static final BooleanProperty ENABLED = BlockStateProperties.ENABLED; - protected AbstractLaserNodeBlock(Properties settings) { - super(settings); - } + protected AbstractLaserNodeBlock(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public boolean isSignalSource(BlockState state) { - return state.getValue(BlockStateProperties.ENABLED); - } + @Override + @SuppressWarnings("deprecation") + public boolean isSignalSource(BlockState state) { + return state.getValue(BlockStateProperties.ENABLED); + } - @Override - @SuppressWarnings("deprecation") - public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - if (state.getValue(BlockStateProperties.ENABLED)) { - return 15; - } - return 0; - } + @Override + @SuppressWarnings("deprecation") + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + if (state.getValue(BlockStateProperties.ENABLED)) { + return 15; + } + return 0; + } - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { - return 1.0F; - } + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { + return 1.0F; + } - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } - @NotNull - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @NotNull + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new LaserNodeBlockEntity(pos, state); - } + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new LaserNodeBlockEntity(pos, state); + } - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return createTickerHelper(type, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY, LaserNodeBlockEntity::tick); - } + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY, LaserNodeBlockEntity::tick); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { - return InteractionResult.PASS; - } - if (world.isClientSide) { - return InteractionResult.SUCCESS; - } - world.getBlockEntity(pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).ifPresent(entity -> entity.setSound( - switch (entity.getSound().toString()) { - case "portalcubed:laser/node_music" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_1; - case "portalcubed:laser/triple_laser_sound_demo_1" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_2; - case "portalcubed:laser/triple_laser_sound_demo_2" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_3; - default -> PortalCubedSounds.LASER_NODE_MUSIC; - } - )); - return InteractionResult.CONSUME; - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { + return InteractionResult.PASS; + } + if (world.isClientSide) { + return InteractionResult.SUCCESS; + } + world.getBlockEntity(pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).ifPresent(entity -> entity.setSound( + switch (entity.getSound().toString()) { + case "portalcubed:laser/node_music" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_1; + case "portalcubed:laser/triple_laser_sound_demo_1" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_2; + case "portalcubed:laser/triple_laser_sound_demo_2" -> PortalCubedSounds.LASER_TRIPLE_LASER_SOUND_DEMO_3; + default -> PortalCubedSounds.LASER_NODE_MUSIC; + } + )); + return InteractionResult.CONSUME; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/AdhesionGel.java b/src/main/java/com/fusionflux/portalcubed/blocks/AdhesionGel.java index a53cff51..d27aeb06 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/AdhesionGel.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/AdhesionGel.java @@ -17,95 +17,95 @@ import java.util.ArrayList; public class AdhesionGel extends BaseGel { - public AdhesionGel(Properties settings) { - super(settings); - } + public AdhesionGel(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { - AABB block = new AABB(pos); - AABB player = getPlayerBox(entity.getBoundingBox(), GravityChangerAPI.getGravityDirection(entity), -(entity.getBbHeight() - 1)); - if (block.intersects(player)) { - this.addCollisionEffects(world, entity, pos, state); - } - } + @Override + @SuppressWarnings("deprecation") + public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { + AABB block = new AABB(pos); + AABB player = getPlayerBox(entity.getBoundingBox(), GravityChangerAPI.getGravityDirection(entity), -(entity.getBbHeight() - 1)); + if (block.intersects(player)) { + this.addCollisionEffects(world, entity, pos, state); + } + } - private void addCollisionEffects(Level world, Entity entity, BlockPos pos, BlockState state) { - FriendlyByteBuf info = AdhesionGravityVerifier.packInfo(pos); - if ((entity.onGround() && entity.horizontalCollision) || (!entity.onGround() && entity.horizontalCollision) || (!entity.onGround() && !entity.horizontalCollision)) { - if (((EntityExt) entity).getGelTimer() == 0) { - Direction current = GravityChangerAPI.getGravityDirection(entity); + private void addCollisionEffects(Level world, Entity entity, BlockPos pos, BlockState state) { + FriendlyByteBuf info = AdhesionGravityVerifier.packInfo(pos); + if ((entity.onGround() && entity.horizontalCollision) || (!entity.onGround() && entity.horizontalCollision) || (!entity.onGround() && !entity.horizontalCollision)) { + if (((EntityExt) entity).getGelTimer() == 0) { + Direction current = GravityChangerAPI.getGravityDirection(entity); - double delta = -.9; - ArrayList gravList = GravityChangerAPI.getGravityList(entity); - for (Gravity grav : gravList) { - if (grav.source().equals("portalcubed:adhesion_gel")) { - delta = -.1; - break; - } - } - for (Direction direc : availableFaces(state)) { - if (direc != current) { - AABB gravbox = getGravityEffectBox(pos, direc, delta); - if (gravbox.intersects(entity.getBoundingBox())) { - if (world.isClientSide && entity instanceof Player) { - GravityChangerAPI.addGravityClient((LocalPlayer) entity, AdhesionGravityVerifier.newFieldGravity(direc), AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, info); - ((EntityExt) entity).setGelTimer(10); - break; - } else { - if (!(entity instanceof Player) && !world.isClientSide) { - GravityChangerAPI.addGravity(entity, new Gravity(direc, 10, 2, "adhesion_gel")); - ((EntityExt) entity).setGelTimer(10); - break; - } - } - } - } - } - } - } - if (world.isClientSide && entity instanceof Player) { - GravityChangerAPI.addGravityClient((LocalPlayer) entity, AdhesionGravityVerifier.newFieldGravity(GravityChangerAPI.getGravityDirection(entity)), AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, info); - } else { - if (!(entity instanceof Player) && !world.isClientSide) - GravityChangerAPI.addGravity(entity, new Gravity(GravityChangerAPI.getGravityDirection(entity), 10, 2, "adhesion_gel")); - } - } + double delta = -.9; + ArrayList gravList = GravityChangerAPI.getGravityList(entity); + for (Gravity grav : gravList) { + if (grav.source().equals("portalcubed:adhesion_gel")) { + delta = -.1; + break; + } + } + for (Direction direc : availableFaces(state)) { + if (direc != current) { + AABB gravbox = getGravityEffectBox(pos, direc, delta); + if (gravbox.intersects(entity.getBoundingBox())) { + if (world.isClientSide && entity instanceof Player) { + GravityChangerAPI.addGravityClient((LocalPlayer) entity, AdhesionGravityVerifier.newFieldGravity(direc), AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, info); + ((EntityExt) entity).setGelTimer(10); + break; + } else { + if (!(entity instanceof Player) && !world.isClientSide) { + GravityChangerAPI.addGravity(entity, new Gravity(direc, 10, 2, "adhesion_gel")); + ((EntityExt) entity).setGelTimer(10); + break; + } + } + } + } + } + } + } + if (world.isClientSide && entity instanceof Player) { + GravityChangerAPI.addGravityClient((LocalPlayer) entity, AdhesionGravityVerifier.newFieldGravity(GravityChangerAPI.getGravityDirection(entity)), AdhesionGravityVerifier.FIELD_GRAVITY_SOURCE, info); + } else { + if (!(entity instanceof Player) && !world.isClientSide) + GravityChangerAPI.addGravity(entity, new Gravity(GravityChangerAPI.getGravityDirection(entity), 10, 2, "adhesion_gel")); + } + } - public AABB getGravityEffectBox(BlockPos blockPos, Direction direction, double delta) { - double minX = blockPos.getX(); - double minY = blockPos.getY(); - double minZ = blockPos.getZ(); - double maxX = blockPos.getX() + 1; - double maxY = blockPos.getY() + 1; - double maxZ = blockPos.getZ() + 1; - switch (direction) { - case DOWN -> maxY += delta; - case UP -> minY -= delta; - case NORTH -> maxZ += delta; - case SOUTH -> minZ -= delta; - case WEST -> maxX += delta; - case EAST -> minX -= delta; - } - return new AABB(minX, minY, minZ, maxX, maxY, maxZ); - } + public AABB getGravityEffectBox(BlockPos blockPos, Direction direction, double delta) { + double minX = blockPos.getX(); + double minY = blockPos.getY(); + double minZ = blockPos.getZ(); + double maxX = blockPos.getX() + 1; + double maxY = blockPos.getY() + 1; + double maxZ = blockPos.getZ() + 1; + switch (direction) { + case DOWN -> maxY += delta; + case UP -> minY -= delta; + case NORTH -> maxZ += delta; + case SOUTH -> minZ -= delta; + case WEST -> maxX += delta; + case EAST -> minX -= delta; + } + return new AABB(minX, minY, minZ, maxX, maxY, maxZ); + } - public AABB getPlayerBox(AABB playerBox, Direction direction, double delta) { - double minX = playerBox.minX; - double minY = playerBox.minY; - double minZ = playerBox.minZ; - double maxX = playerBox.maxX; - double maxY = playerBox.maxY; - double maxZ = playerBox.maxZ; - switch (direction) { - case DOWN -> maxY += delta; - case UP -> minY -= delta; - case NORTH -> maxZ += delta; - case SOUTH -> minZ -= delta; - case WEST -> maxX += delta; - case EAST -> minX -= delta; - } - return new AABB(minX, minY, minZ, maxX, maxY, maxZ); - } + public AABB getPlayerBox(AABB playerBox, Direction direction, double delta) { + double minX = playerBox.minX; + double minY = playerBox.minY; + double minZ = playerBox.minZ; + double maxX = playerBox.maxX; + double maxY = playerBox.maxY; + double maxZ = playerBox.maxZ; + switch (direction) { + case DOWN -> maxY += delta; + case UP -> minY -= delta; + case NORTH -> maxZ += delta; + case SOUTH -> minZ -= delta; + case WEST -> maxX += delta; + case EAST -> minX -= delta; + } + return new AABB(minX, minY, minZ, maxX, maxY, maxZ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/AutoPortalBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/AutoPortalBlock.java index a1a997b9..c73e5123 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/AutoPortalBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/AutoPortalBlock.java @@ -43,280 +43,280 @@ import java.util.Optional; public class AutoPortalBlock extends BaseEntityBlock { - public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - public static final EnumProperty TYPE = EnumProperty.create("type", PortalType.class); - public static final BooleanProperty OPEN = BlockStateProperties.OPEN; + public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; + public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final EnumProperty TYPE = EnumProperty.create("type", PortalType.class); + public static final BooleanProperty OPEN = BlockStateProperties.OPEN; - private static final VoxelShape PILLAR_SHAPE_NS = box(-2, 0, 0, 1, 16, 2); - private static final VoxelShape PILLAR_SHAPE_EW = box(0, 0, -2, 2, 16, 1); - public static final VoxelShape SOUTH_SHAPE = Shapes.or(PILLAR_SHAPE_NS, PILLAR_SHAPE_NS.move(17 / 16.0, 0, 0)); - public static final VoxelShape NORTH_SHAPE = SOUTH_SHAPE.move(0, 0, 14 / 16.0); - public static final VoxelShape EAST_SHAPE = Shapes.or(PILLAR_SHAPE_EW, PILLAR_SHAPE_EW.move(0, 0, 17 / 16.0)); - public static final VoxelShape WEST_SHAPE = EAST_SHAPE.move(14 / 16.0, 0, 0); + private static final VoxelShape PILLAR_SHAPE_NS = box(-2, 0, 0, 1, 16, 2); + private static final VoxelShape PILLAR_SHAPE_EW = box(0, 0, -2, 2, 16, 1); + public static final VoxelShape SOUTH_SHAPE = Shapes.or(PILLAR_SHAPE_NS, PILLAR_SHAPE_NS.move(17 / 16.0, 0, 0)); + public static final VoxelShape NORTH_SHAPE = SOUTH_SHAPE.move(0, 0, 14 / 16.0); + public static final VoxelShape EAST_SHAPE = Shapes.or(PILLAR_SHAPE_EW, PILLAR_SHAPE_EW.move(0, 0, 17 / 16.0)); + public static final VoxelShape WEST_SHAPE = EAST_SHAPE.move(14 / 16.0, 0, 0); - public AutoPortalBlock(Properties settings) { - super(settings); - registerDefaultState( - getStateDefinition().any() - .setValue(FACING, Direction.NORTH) - .setValue(HALF, DoubleBlockHalf.LOWER) - .setValue(POWERED, false) - .setValue(OPEN, false) - ); - } + public AutoPortalBlock(Properties settings) { + super(settings); + registerDefaultState( + getStateDefinition().any() + .setValue(FACING, Direction.NORTH) + .setValue(HALF, DoubleBlockHalf.LOWER) + .setValue(POWERED, false) + .setValue(OPEN, false) + ); + } - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new AutoPortalBlockEntity(pos, state); - } + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new AutoPortalBlockEntity(pos, state); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case NORTH -> NORTH_SHAPE; - case SOUTH -> SOUTH_SHAPE; - case WEST -> WEST_SHAPE; - case EAST -> EAST_SHAPE; - default -> throw new AssertionError(); - }; - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return switch (state.getValue(FACING)) { + case NORTH -> NORTH_SHAPE; + case SOUTH -> SOUTH_SHAPE; + case WEST -> WEST_SHAPE; + case EAST -> EAST_SHAPE; + default -> throw new AssertionError(); + }; + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { - final DoubleBlockHalf half = state.getValue(HALF); - if (direction.getAxis() != Direction.Axis.Y || half == DoubleBlockHalf.LOWER != (direction == Direction.UP)) { - return half == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) - ? Blocks.AIR.defaultBlockState() - : super.updateShape(state, direction, neighborState, world, pos, neighborPos); - } - return neighborState.is(this) && neighborState.getValue(HALF) != half - ? state.setValue(FACING, neighborState.getValue(FACING)) - .setValue(POWERED, neighborState.getValue(POWERED)) - : Blocks.AIR.defaultBlockState(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { + final DoubleBlockHalf half = state.getValue(HALF); + if (direction.getAxis() != Direction.Axis.Y || half == DoubleBlockHalf.LOWER != (direction == Direction.UP)) { + return half == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) + ? Blocks.AIR.defaultBlockState() + : super.updateShape(state, direction, neighborState, world, pos, neighborPos); + } + return neighborState.is(this) && neighborState.getValue(HALF) != half + ? state.setValue(FACING, neighborState.getValue(FACING)) + .setValue(POWERED, neighborState.getValue(POWERED)) + : Blocks.AIR.defaultBlockState(); + } - @Override - public void playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { - if (!world.isClientSide && player.isCreative()) { - SlidingDoorBlock.onBreakInCreative(world, pos, state, player); - } + @Override + public void playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { + if (!world.isClientSide && player.isCreative()) { + SlidingDoorBlock.onBreakInCreative(world, pos, state, player); + } - super.playerWillDestroy(world, pos, state, player); - } + super.playerWillDestroy(world, pos, state, player); + } - @Override - @SuppressWarnings("deprecation") - public boolean isPathfindable(BlockState state, BlockGetter world, BlockPos pos, PathComputationType type) { - return true; - } + @Override + @SuppressWarnings("deprecation") + public boolean isPathfindable(BlockState state, BlockGetter world, BlockPos pos, PathComputationType type) { + return true; + } - @Nullable - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - final BlockPos pos = ctx.getClickedPos(); - final Level world = ctx.getLevel(); - if (pos.getY() >= world.getMaxBuildHeight() - 1 || !world.getBlockState(pos.above()).canBeReplaced(ctx)) { - return null; - } - final boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.above()); - return defaultBlockState() - .setValue(FACING, ctx.getHorizontalDirection().getOpposite()) - .setValue(HALF, DoubleBlockHalf.LOWER) - .setValue(POWERED, powered); - } + @Nullable + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + final BlockPos pos = ctx.getClickedPos(); + final Level world = ctx.getLevel(); + if (pos.getY() >= world.getMaxBuildHeight() - 1 || !world.getBlockState(pos.above()).canBeReplaced(ctx)) { + return null; + } + final boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.above()); + return defaultBlockState() + .setValue(FACING, ctx.getHorizontalDirection().getOpposite()) + .setValue(HALF, DoubleBlockHalf.LOWER) + .setValue(POWERED, powered); + } - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) { - world.setBlock(pos.above(), state.setValue(HALF, DoubleBlockHalf.UPPER), Block.UPDATE_ALL); - openOrClosePortal(world, pos, state, true); - } + @Override + public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) { + world.setBlock(pos.above(), state.setValue(HALF, DoubleBlockHalf.UPPER), Block.UPDATE_ALL); + openOrClosePortal(world, pos, state, true); + } - @Override - @SuppressWarnings("deprecation") - public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { - final boolean poweredNow = level.hasNeighborSignal(pos) || - level.hasNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN)); - if (!defaultBlockState().is(block) && poweredNow != state.getValue(POWERED)) { - if (poweredNow) { - openOrClosePortal(level, state.getValue(HALF) == DoubleBlockHalf.LOWER ? pos : pos.below(), state, false); - } - level.setBlockAndUpdate(pos, level.getBlockState(pos).setValue(POWERED, poweredNow)); - } - } + @Override + @SuppressWarnings("deprecation") + public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { + final boolean poweredNow = level.hasNeighborSignal(pos) || + level.hasNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN)); + if (!defaultBlockState().is(block) && poweredNow != state.getValue(POWERED)) { + if (poweredNow) { + openOrClosePortal(level, state.getValue(HALF) == DoubleBlockHalf.LOWER ? pos : pos.below(), state, false); + } + level.setBlockAndUpdate(pos, level.getBlockState(pos).setValue(POWERED, poweredNow)); + } + } - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - final Direction facing = state.getValue(FACING); - final BlockPos onPos = pos.relative(facing.getOpposite()); - if (!world.getBlockState(onPos).isFaceSturdy(world, onPos, facing)) { - return false; - } - final BlockPos otherPos = state.getValue(HALF) == DoubleBlockHalf.UPPER ? pos.below() : pos.above(); - final BlockPos otherOnPos = otherPos.relative(facing.getOpposite()); - if (!world.getBlockState(otherOnPos).isFaceSturdy(world, otherOnPos, facing)) { - return false; - } - return state.getValue(HALF) == DoubleBlockHalf.LOWER || world.getBlockState(otherPos).is(this); - } + @Override + @SuppressWarnings("deprecation") + public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { + final Direction facing = state.getValue(FACING); + final BlockPos onPos = pos.relative(facing.getOpposite()); + if (!world.getBlockState(onPos).isFaceSturdy(world, onPos, facing)) { + return false; + } + final BlockPos otherPos = state.getValue(HALF) == DoubleBlockHalf.UPPER ? pos.below() : pos.above(); + final BlockPos otherOnPos = otherPos.relative(facing.getOpposite()); + if (!world.getBlockState(otherOnPos).isFaceSturdy(world, otherOnPos, facing)) { + return false; + } + return state.getValue(HALF) == DoubleBlockHalf.LOWER || world.getBlockState(otherPos).is(this); + } - public static void openOrClosePortal(Level level, BlockPos lower, BlockState state, boolean forceClose) { - if (level.isClientSide) return; - final boolean open = state.getValue(OPEN); - final int color = getColor(level, lower); - final BlockPos upper = lower.above(); - final List portals = level.getEntities( - PortalCubedEntities.PORTAL, - state.getCollisionShape(level, lower).bounds().move(lower).expandTowards(0, 1, 0), - p -> true - ); - if (!portals.isEmpty()) { - portals.forEach(Portal::kill); - level.playSound(null, lower.getX(), lower.getY(), lower.getZ(), PortalCubedSounds.ENTITY_PORTAL_CLOSE, SoundSource.NEUTRAL, .1F, 1F); - } - if (forceClose) return; - level.setBlockAndUpdate(lower, level.getBlockState(lower).setValue(OPEN, !open)); - level.setBlockAndUpdate(upper, level.getBlockState(upper).setValue(OPEN, !open)); - if (open) { - return; - } - final Direction facing = state.getValue(FACING); - final Direction facingOpposite = facing.getOpposite(); - final BlockPos placeOn = upper.relative(facingOpposite); - final Portal portal = PortalCubedEntities.PORTAL.create(level); - assert portal != null; - final Vec3 portalPos = new Vec3( - placeOn.getX() + 0.5 - 0.510 * facingOpposite.getStepX(), - placeOn.getY(), - placeOn.getZ() + 0.5 - 0.510 * facingOpposite.getStepZ() - ); - portal.setOriginPos(portalPos); - portal.setDestination(Optional.of(portalPos)); - portal.setColor(color); - portal.setRotation(IPQuaternion.matrixToQuaternion( - Vec3.atLowerCornerOf(Direction.UP.getNormal().cross(facingOpposite.getNormal())), - Vec3.atLowerCornerOf(Direction.UP.getNormal()), - Vec3.atLowerCornerOf(facingOpposite.getNormal()) - ).toQuaternionf()); - portal.setLinkedPortalUUID(Optional.empty()); - level.addFreshEntity(portal); - PortalGun.getPotentialOpposite(level, portalPos, portal, color, true) - .ifPresent(other -> PortalGun.linkPortals(portal, other, 0.9f)); - } + public static void openOrClosePortal(Level level, BlockPos lower, BlockState state, boolean forceClose) { + if (level.isClientSide) return; + final boolean open = state.getValue(OPEN); + final int color = getColor(level, lower); + final BlockPos upper = lower.above(); + final List portals = level.getEntities( + PortalCubedEntities.PORTAL, + state.getCollisionShape(level, lower).bounds().move(lower).expandTowards(0, 1, 0), + p -> true + ); + if (!portals.isEmpty()) { + portals.forEach(Portal::kill); + level.playSound(null, lower.getX(), lower.getY(), lower.getZ(), PortalCubedSounds.ENTITY_PORTAL_CLOSE, SoundSource.NEUTRAL, .1F, 1F); + } + if (forceClose) return; + level.setBlockAndUpdate(lower, level.getBlockState(lower).setValue(OPEN, !open)); + level.setBlockAndUpdate(upper, level.getBlockState(upper).setValue(OPEN, !open)); + if (open) { + return; + } + final Direction facing = state.getValue(FACING); + final Direction facingOpposite = facing.getOpposite(); + final BlockPos placeOn = upper.relative(facingOpposite); + final Portal portal = PortalCubedEntities.PORTAL.create(level); + assert portal != null; + final Vec3 portalPos = new Vec3( + placeOn.getX() + 0.5 - 0.510 * facingOpposite.getStepX(), + placeOn.getY(), + placeOn.getZ() + 0.5 - 0.510 * facingOpposite.getStepZ() + ); + portal.setOriginPos(portalPos); + portal.setDestination(Optional.of(portalPos)); + portal.setColor(color); + portal.setRotation(IPQuaternion.matrixToQuaternion( + Vec3.atLowerCornerOf(Direction.UP.getNormal().cross(facingOpposite.getNormal())), + Vec3.atLowerCornerOf(Direction.UP.getNormal()), + Vec3.atLowerCornerOf(facingOpposite.getNormal()) + ).toQuaternionf()); + portal.setLinkedPortalUUID(Optional.empty()); + level.addFreshEntity(portal); + PortalGun.getPotentialOpposite(level, portalPos, portal, color, true) + .ifPresent(other -> PortalGun.linkPortals(portal, other, 0.9f)); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - final boolean upper = state.getValue(HALF) == DoubleBlockHalf.UPPER; - final BlockPos otherPos = upper ? pos.below() : pos.above(); - final BlockPos lowerPos = upper ? otherPos : pos; - final ItemStack stack = player.getItemInHand(hand); - if (stack.is(PortalCubedItems.WRENCHES)) { - openOrClosePortal(level, lowerPos, state, true); - if (player.isShiftKeyDown()) { - for (BlockPos usePos = pos; usePos != null; usePos = usePos == pos ? otherPos : null) { - level.getBlockEntity(usePos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) - .ifPresent(entity -> entity.setColor(0x1d86db)); - } - player.displayClientMessage( - Component.translatable("portalcubed.auto_portal.set_portal_color.default") - .withStyle(s -> s.withColor(getColor(level, pos))), - true - ); - return InteractionResult.sidedSuccess(level.isClientSide); - } - final PortalType newType = state.cycle(TYPE).getValue(TYPE); - level.setBlockAndUpdate(pos, level.getBlockState(pos).cycle(TYPE)); - level.setBlockAndUpdate(otherPos, level.getBlockState(otherPos).cycle(TYPE)); - player.displayClientMessage( - Component.translatable( - "portalcubed.auto_portal.set_portal_type", - Component.translatable("portalcubed.portal_type." + newType.getSerializedName()) - ).withStyle(s -> s.withColor(getColor(level, pos))), - true - ); - return InteractionResult.sidedSuccess(level.isClientSide); - } - if (stack.getItem() instanceof DyeItem dye) { - openOrClosePortal(level, lowerPos, state, true); - final int dyeColor = PortalCubedItems.PORTAL_GUN.getColor(DyeableLeatherItem.dyeArmor( - new ItemStack(PortalCubedItems.PORTAL_GUN), List.of(dye) - )); - for (BlockPos usePos = pos; usePos != null; usePos = usePos == pos ? otherPos : null) { - level.getBlockEntity(usePos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) - .ifPresent(entity -> entity.setColor(dyeColor)); - } - player.displayClientMessage( - Component.translatable( - "portalcubed.auto_portal.set_portal_color", - Component.translatable("color.minecraft." + dye.getDyeColor().getName()) - ).withStyle(s -> s.withColor(getColor(level, pos))), - true - ); - if (!player.getAbilities().instabuild) { - stack.shrink(1); - } - return InteractionResult.sidedSuccess(level.isClientSide); - } - return InteractionResult.PASS; - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + final boolean upper = state.getValue(HALF) == DoubleBlockHalf.UPPER; + final BlockPos otherPos = upper ? pos.below() : pos.above(); + final BlockPos lowerPos = upper ? otherPos : pos; + final ItemStack stack = player.getItemInHand(hand); + if (stack.is(PortalCubedItems.WRENCHES)) { + openOrClosePortal(level, lowerPos, state, true); + if (player.isShiftKeyDown()) { + for (BlockPos usePos = pos; usePos != null; usePos = usePos == pos ? otherPos : null) { + level.getBlockEntity(usePos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) + .ifPresent(entity -> entity.setColor(0x1d86db)); + } + player.displayClientMessage( + Component.translatable("portalcubed.auto_portal.set_portal_color.default") + .withStyle(s -> s.withColor(getColor(level, pos))), + true + ); + return InteractionResult.sidedSuccess(level.isClientSide); + } + final PortalType newType = state.cycle(TYPE).getValue(TYPE); + level.setBlockAndUpdate(pos, level.getBlockState(pos).cycle(TYPE)); + level.setBlockAndUpdate(otherPos, level.getBlockState(otherPos).cycle(TYPE)); + player.displayClientMessage( + Component.translatable( + "portalcubed.auto_portal.set_portal_type", + Component.translatable("portalcubed.portal_type." + newType.getSerializedName()) + ).withStyle(s -> s.withColor(getColor(level, pos))), + true + ); + return InteractionResult.sidedSuccess(level.isClientSide); + } + if (stack.getItem() instanceof DyeItem dye) { + openOrClosePortal(level, lowerPos, state, true); + final int dyeColor = PortalCubedItems.PORTAL_GUN.getColor(DyeableLeatherItem.dyeArmor( + new ItemStack(PortalCubedItems.PORTAL_GUN), List.of(dye) + )); + for (BlockPos usePos = pos; usePos != null; usePos = usePos == pos ? otherPos : null) { + level.getBlockEntity(usePos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) + .ifPresent(entity -> entity.setColor(dyeColor)); + } + player.displayClientMessage( + Component.translatable( + "portalcubed.auto_portal.set_portal_color", + Component.translatable("color.minecraft." + dye.getDyeColor().getName()) + ).withStyle(s -> s.withColor(getColor(level, pos))), + true + ); + if (!player.getAbilities().instabuild) { + stack.shrink(1); + } + return InteractionResult.sidedSuccess(level.isClientSide); + } + return InteractionResult.PASS; + } - public static int getColor(Level world, BlockPos pos) { - return world.getBlockState(pos).getValue(TYPE).colorTransformer.applyAsInt( - world.getBlockEntity(pos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) - .map(AutoPortalBlockEntity::getColor) - .orElse(0x1d86db) - ); - } + public static int getColor(Level world, BlockPos pos) { + return world.getBlockState(pos).getValue(TYPE).colorTransformer.applyAsInt( + world.getBlockEntity(pos, PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY) + .map(AutoPortalBlockEntity::getColor) + .orElse(0x1d86db) + ); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState mirror(BlockState state, Mirror mirror) { - return mirror == Mirror.NONE ? state : state.rotate(mirror.getRotation(state.getValue(FACING))); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState mirror(BlockState state, Mirror mirror) { + return mirror == Mirror.NONE ? state : state.rotate(mirror.getRotation(state.getValue(FACING))); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, HALF, POWERED, TYPE, OPEN); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, HALF, POWERED, TYPE, OPEN); + } - @NotNull - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @NotNull + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - public enum PortalType implements StringRepresentable { - PRIMARY("primary", Int2IntFunction.identity()), - SECONDARY("secondary", c -> 0xffffff - c + 1); + public enum PortalType implements StringRepresentable { + PRIMARY("primary", Int2IntFunction.identity()), + SECONDARY("secondary", c -> 0xffffff - c + 1); - private final String id; - public final Int2IntFunction colorTransformer; + private final String id; + public final Int2IntFunction colorTransformer; - PortalType(String id, Int2IntFunction colorTransformer) { - this.id = id; - this.colorTransformer = colorTransformer; - } + PortalType(String id, Int2IntFunction colorTransformer) { + this.id = id; + this.colorTransformer = colorTransformer; + } - @NotNull - @Override - public String getSerializedName() { - return id; - } - } + @NotNull + @Override + public String getSerializedName() { + return id; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/BaseGel.java b/src/main/java/com/fusionflux/portalcubed/blocks/BaseGel.java index e37fb76a..16bd3d37 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/BaseGel.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/BaseGel.java @@ -12,28 +12,28 @@ import net.minecraft.world.phys.shapes.Shapes; public class BaseGel extends SimpleMultiSidedBlock { - public BaseGel(Properties settings) { - super(settings); - } + public BaseGel(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - if (world.isRainingAt(pos.above())) { - world.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState()); - } - } + @Override + @SuppressWarnings("deprecation") + public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { + if (world.isRainingAt(pos.above())) { + world.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState()); + } + } - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } - public static boolean collides(Entity entity, BlockPos pos, BlockState state) { - return Shapes.joinIsNotEmpty( - state.getShape(entity.level(), pos, CollisionContext.of(entity)).move(pos.getX(), pos.getY(), pos.getZ()), - Shapes.create(entity.getBoundingBox()), - BooleanOp.AND - ); - } + public static boolean collides(Entity entity, BlockPos pos, BlockState state) { + return Shapes.joinIsNotEmpty( + state.getShape(entity.level(), pos, CollisionContext.of(entity)).move(pos.getX(), pos.getY(), pos.getZ()), + Shapes.create(entity.getBoundingBox()), + BooleanOp.AND + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/BucketPickupEx.java b/src/main/java/com/fusionflux/portalcubed/blocks/BucketPickupEx.java index 0938e346..16a3bc27 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/BucketPickupEx.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/BucketPickupEx.java @@ -8,12 +8,12 @@ import java.util.Optional; public interface BucketPickupEx extends BucketPickup { - @NotNull - Optional getPickupSound(BlockState state); + @NotNull + Optional getPickupSound(BlockState state); - @NotNull - @Override - default Optional getPickupSound() { - return Optional.empty(); - } + @NotNull + @Override + default Optional getPickupSound() { + return Optional.empty(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/CatapultBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/CatapultBlock.java index a92a59d1..c6191966 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/CatapultBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/CatapultBlock.java @@ -22,47 +22,47 @@ import org.jetbrains.annotations.Nullable; public class CatapultBlock extends SpecialHiddenBlockWithEntity implements BlockCollisionTrigger { - private static final VoxelShape SHAPE = box(3, 3, 3, 13, 13, 13); + private static final VoxelShape SHAPE = box(3, 3, 3, 13, 13, 13); - public CatapultBlock(Properties settings) { - super(settings); - } + public CatapultBlock(Properties settings) { + super(settings); + } - @Nullable - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new CatapultBlockEntity(pos, state); - } + @Nullable + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new CatapultBlockEntity(pos, state); + } - @Override - protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } + @Override + protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } - @Override - public VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return Shapes.block(); - } + @Override + public VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return Shapes.block(); + } - @Override - public void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { - if (entity instanceof EntityExt ext && !(entity instanceof EnergyPellet)) { - world.getBlockEntity(pos, PortalCubedBlocks.CATAPULT_BLOCK_ENTITY).ifPresent(ext::collidedWithCatapult); - } - } + @Override + public void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { + if (entity instanceof EntityExt ext && !(entity instanceof EnergyPellet)) { + world.getBlockEntity(pos, PortalCubedBlocks.CATAPULT_BLOCK_ENTITY).ifPresent(ext::collidedWithCatapult); + } + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.isCreative()) return InteractionResult.PASS; - if (!world.isClientSide) { - final MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.isCreative()) return InteractionResult.PASS; + if (!world.isClientSide) { + final MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); - if (screenHandlerFactory != null) { - player.openMenu(screenHandlerFactory); - } - } - return InteractionResult.SUCCESS; - } + if (screenHandlerFactory != null) { + player.openMenu(screenHandlerFactory); + } + } + return InteractionResult.SUCCESS; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/DirectionalBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/DirectionalBlock.java index 8de52193..ce1fec37 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/DirectionalBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/DirectionalBlock.java @@ -8,21 +8,21 @@ import org.jetbrains.annotations.Nullable; public class DirectionalBlock extends Block { - public DirectionalBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.defaultBlockState()); - } + public DirectionalBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.defaultBlockState()); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(BlockStateProperties.HORIZONTAL_FACING); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(BlockStateProperties.HORIZONTAL_FACING); + } - @Override - public @Nullable BlockState getStateForPlacement(BlockPlaceContext ctx) { + @Override + public @Nullable BlockState getStateForPlacement(BlockPlaceContext ctx) { - return this.defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_FACING, ctx.getHorizontalDirection().getOpposite()); - } + return this.defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_FACING, ctx.getHorizontalDirection().getOpposite()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/FacadeBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/FacadeBlock.java index a705e60d..6d0dc4f9 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/FacadeBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/FacadeBlock.java @@ -9,14 +9,14 @@ import org.jetbrains.annotations.NotNull; public class FacadeBlock extends SimpleMultiSidedBlock { - public FacadeBlock(Properties settings) { - super(settings); - } + public FacadeBlock(Properties settings) { + super(settings); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return Shapes.empty(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return Shapes.empty(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateBlock.java index f1028de7..6931e56e 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateBlock.java @@ -33,105 +33,105 @@ import java.util.function.Supplier; public class FaithPlateBlock extends BaseEntityBlock { - public static final DirectionProperty FACING = BlockStateProperties.FACING; - public static final DirectionProperty HORIFACING = PortalCubedProperties.HORIFACING; - - private final Supplier> blockEntityType; - - public FaithPlateBlock(Properties settings, Supplier> blockEntityType) { - super(settings); - this.registerDefaultState( - stateDefinition.any() - .setValue(FACING, Direction.UP) - .setValue(HORIFACING, Direction.NORTH) - ); - this.blockEntityType = blockEntityType; - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!world.isClientSide && canConfigure(player, hand)) { - //This will call the createScreenHandlerFactory method from BlockWithEntity, which will return our blockEntity cast to - //a namedScreenHandlerFactory. If your block class does not extend BlockWithEntity, it needs to implement createScreenHandlerFactory. - MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); - - if (screenHandlerFactory != null) { - //With this call the server will request the client to open the appropriate ScreenHandler - player.openMenu(screenHandlerFactory); - } - } - return InteractionResult.SUCCESS; - } - - public boolean canConfigure(Player player, InteractionHand hand) { - if (player.isCreative()) - return true; - return player.getAbilities().mayBuild && player.getItemInHand(hand).is(PortalCubedItems.WRENCHES); - } - - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { - return 1.0F; - } - - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } - - @NotNull - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, HORIFACING); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - final Direction look = ctx.getNearestLookingDirection(); - if (look.getAxis().isVertical()) { - return defaultBlockState() - .setValue(FACING, look.getOpposite()) - .setValue(HORIFACING, ctx.getHorizontalDirection()); - } - return defaultBlockState() - .setValue(FACING, look.getOpposite()); - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) { - world.getBlockEntity(pos, blockEntityType.get()).ifPresent(entity -> { - entity.setVelY(1.25); - final Direction facing = state.getValue(FACING).getAxis().isVertical() ? state.getValue(HORIFACING) : state.getValue(FACING); - entity.setVelX(facing.getStepX() * 0.75); - entity.setVelZ(facing.getStepZ() * 0.75); - }); - } - - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return blockEntityType.get().create(pos, state); - } - - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return type == blockEntityType.get() - ? (world1, pos, state1, entity) -> ((FaithPlateBlockEntity)entity).tick(world1, pos, state1) - : null; - } + public static final DirectionProperty FACING = BlockStateProperties.FACING; + public static final DirectionProperty HORIFACING = PortalCubedProperties.HORIFACING; + + private final Supplier> blockEntityType; + + public FaithPlateBlock(Properties settings, Supplier> blockEntityType) { + super(settings); + this.registerDefaultState( + stateDefinition.any() + .setValue(FACING, Direction.UP) + .setValue(HORIFACING, Direction.NORTH) + ); + this.blockEntityType = blockEntityType; + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!world.isClientSide && canConfigure(player, hand)) { + //This will call the createScreenHandlerFactory method from BlockWithEntity, which will return our blockEntity cast to + //a namedScreenHandlerFactory. If your block class does not extend BlockWithEntity, it needs to implement createScreenHandlerFactory. + MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); + + if (screenHandlerFactory != null) { + //With this call the server will request the client to open the appropriate ScreenHandler + player.openMenu(screenHandlerFactory); + } + } + return InteractionResult.SUCCESS; + } + + public boolean canConfigure(Player player, InteractionHand hand) { + if (player.isCreative()) + return true; + return player.getAbilities().mayBuild && player.getItemInHand(hand).is(PortalCubedItems.WRENCHES); + } + + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { + return 1.0F; + } + + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } + + @NotNull + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, HORIFACING); + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + final Direction look = ctx.getNearestLookingDirection(); + if (look.getAxis().isVertical()) { + return defaultBlockState() + .setValue(FACING, look.getOpposite()) + .setValue(HORIFACING, ctx.getHorizontalDirection()); + } + return defaultBlockState() + .setValue(FACING, look.getOpposite()); + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } + + @Override + public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) { + world.getBlockEntity(pos, blockEntityType.get()).ifPresent(entity -> { + entity.setVelY(1.25); + final Direction facing = state.getValue(FACING).getAxis().isVertical() ? state.getValue(HORIFACING) : state.getValue(FACING); + entity.setVelX(facing.getStepX() * 0.75); + entity.setVelZ(facing.getStepZ() * 0.75); + }); + } + + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return blockEntityType.get().create(pos, state); + } + + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return type == blockEntityType.get() + ? (world1, pos, state1, entity) -> ((FaithPlateBlockEntity)entity).tick(world1, pos, state1) + : null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateTargetBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateTargetBlock.java index 7fe51342..68e921d8 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateTargetBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/FaithPlateTargetBlock.java @@ -20,49 +20,49 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class FaithPlateTargetBlock extends SimpleMultiSidedBlock { - public FaithPlateTargetBlock(Properties settings) { - super(settings); - } + public FaithPlateTargetBlock(Properties settings) { + super(settings); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.getAbilities().instabuild || !world.isClientSide) return InteractionResult.PASS; - final ItemStack held = player.getItemInHand(hand); - if (!held.is(PortalCubedItems.WRENCHES)) return InteractionResult.PASS; + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.getAbilities().instabuild || !world.isClientSide) return InteractionResult.PASS; + final ItemStack held = player.getItemInHand(hand); + if (!held.is(PortalCubedItems.WRENCHES)) return InteractionResult.PASS; - final ItemStack result = new ItemStack(PortalCubedBlocks.CATAPULT.asItem()); + final ItemStack result = new ItemStack(PortalCubedBlocks.CATAPULT.asItem()); - final Vec3 destPos = Vec3.atCenterOf(hit.getBlockPos()) - .add(Vec3.atLowerCornerOf(hit.getDirection().getNormal()).scale(-0.5)); - final CompoundTag catapultNbt = new CompoundTag(); - catapultNbt.putDouble("DestX", destPos.x); - catapultNbt.putDouble("DestY", destPos.y); - catapultNbt.putDouble("DestZ", destPos.z); - BlockItem.setBlockEntityData(result, PortalCubedBlocks.CATAPULT_BLOCK_ENTITY, catapultNbt); + final Vec3 destPos = Vec3.atCenterOf(hit.getBlockPos()) + .add(Vec3.atLowerCornerOf(hit.getDirection().getNormal()).scale(-0.5)); + final CompoundTag catapultNbt = new CompoundTag(); + catapultNbt.putDouble("DestX", destPos.x); + catapultNbt.putDouble("DestY", destPos.y); + catapultNbt.putDouble("DestZ", destPos.z); + BlockItem.setBlockEntityData(result, PortalCubedBlocks.CATAPULT_BLOCK_ENTITY, catapultNbt); - final CompoundTag display = new CompoundTag(); - final ListTag lore = new ListTag(); - lore.add(StringTag.valueOf("\"(+NBT)\"")); - display.put("Lore", lore); - result.addTagElement("display", display); + final CompoundTag display = new CompoundTag(); + final ListTag lore = new ListTag(); + lore.add(StringTag.valueOf("\"(+NBT)\"")); + display.put("Lore", lore); + result.addTagElement("display", display); - final Inventory inventory = player.getInventory(); - inventory.setPickedItem(result); - setPickBlock(); + final Inventory inventory = player.getInventory(); + inventory.setPickedItem(result); + setPickBlock(); - return InteractionResult.SUCCESS; - } + return InteractionResult.SUCCESS; + } - @ClientOnly - private void setPickBlock() { - final Minecraft client = Minecraft.getInstance(); - assert client.gameMode != null; - assert client.player != null; - client.gameMode.handleCreativeModeItemAdd( - client.player.getItemInHand(InteractionHand.MAIN_HAND), - 36 + client.player.getInventory().selected - ); - } + @ClientOnly + private void setPickBlock() { + final Minecraft client = Minecraft.getInstance(); + assert client.gameMode != null; + assert client.player != null; + client.gameMode.handleCreativeModeItemAdd( + client.player.getItemInHand(InteractionHand.MAIN_HAND), + 36 + client.player.getInventory().selected + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/FloorButtonBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/FloorButtonBlock.java index 90b98fe2..50438ba7 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/FloorButtonBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/FloorButtonBlock.java @@ -25,173 +25,173 @@ public class FloorButtonBlock extends BaseEntityBlock { - public static final BooleanProperty ENABLE; - protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); + public static final BooleanProperty ENABLE; + protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape SHAPE_UP = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 18.0D, 15.0D); + protected static final VoxelShape SHAPE_UP = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 18.0D, 15.0D); - protected static final VoxelShape SHAPE_UP_2 = Block.box(-1.0D, 16.0D, -1.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_UP_2 = Block.box(-1.0D, 16.0D, -1.0D, 17.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_DOWN = Block.box(1.0D, -2.0D, 1.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_DOWN = Block.box(1.0D, -2.0D, 1.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_DOWN_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 0.0D, 17.0D); + protected static final VoxelShape SHAPE_DOWN_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 0.0D, 17.0D); - protected static final VoxelShape SHAPE_NORTH = Block.box(1.0D, 1.0D, -2.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_NORTH = Block.box(1.0D, 1.0D, -2.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_NORTH_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 17.0D, 0.0D); + protected static final VoxelShape SHAPE_NORTH_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 17.0D, 0.0D); - protected static final VoxelShape SHAPE_SOUTH = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 18.0D); + protected static final VoxelShape SHAPE_SOUTH = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 18.0D); - protected static final VoxelShape SHAPE_SOUTH_2 = Block.box(-1.0D, -1.0D, 16.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_SOUTH_2 = Block.box(-1.0D, -1.0D, 16.0D, 17.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_WEST = Block.box(-2.0D, 1.0D, 1.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_WEST = Block.box(-2.0D, 1.0D, 1.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_WEST_2 = Block.box(-1.0D, -1.0D, -1.0D, 0.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_WEST_2 = Block.box(-1.0D, -1.0D, -1.0D, 0.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_EAST = Block.box(0.0D, 1.0D, 1.0D, 18.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_EAST = Block.box(0.0D, 1.0D, 1.0D, 18.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_EAST_2 = Block.box(16.0D, -1.0D, -1.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_EAST_2 = Block.box(16.0D, -1.0D, -1.0D, 17.0D, 17.0D, 17.0D); - public static boolean enableEasterEgg = false; + public static boolean enableEasterEgg = false; - public FloorButtonBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any().setValue(ENABLE, false)); - } + public FloorButtonBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any().setValue(ENABLE, false)); + } - static { - ENABLE = BlockStateProperties.ENABLED; - } + static { + ENABLE = BlockStateProperties.ENABLED; + } - @Override - @SuppressWarnings("deprecation") - public boolean isSignalSource(BlockState state) { - return state.getValue(BlockStateProperties.ENABLED); - } + @Override + @SuppressWarnings("deprecation") + public boolean isSignalSource(BlockState state) { + return state.getValue(BlockStateProperties.ENABLED); + } - @Override - @SuppressWarnings("deprecation") - public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - if (state.getValue(BlockStateProperties.ENABLED)) { - return 15; - } - return 0; - } + @Override + @SuppressWarnings("deprecation") + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + if (state.getValue(BlockStateProperties.ENABLED)) { + return 15; + } + return 0; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(BlockStateProperties.FACING); + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction facing = state.getValue(BlockStateProperties.FACING); - VoxelShape voxelShape = Shapes.empty(); + VoxelShape voxelShape = Shapes.empty(); - if (facing == Direction.UP) - voxelShape = Shapes.or(voxelShape, SHAPE_UP); - if (facing == Direction.DOWN) - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); - if (facing == Direction.NORTH) - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); - if (facing == Direction.SOUTH) - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); - if (facing == Direction.EAST) - voxelShape = Shapes.or(voxelShape, SHAPE_EAST); - if (facing == Direction.WEST) - voxelShape = Shapes.or(voxelShape, SHAPE_WEST); + if (facing == Direction.UP) + voxelShape = Shapes.or(voxelShape, SHAPE_UP); + if (facing == Direction.DOWN) + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); + if (facing == Direction.NORTH) + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); + if (facing == Direction.SOUTH) + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); + if (facing == Direction.EAST) + voxelShape = Shapes.or(voxelShape, SHAPE_EAST); + if (facing == Direction.WEST) + voxelShape = Shapes.or(voxelShape, SHAPE_WEST); - voxelShape = Shapes.or(voxelShape, SHAPE); - return voxelShape; - } + voxelShape = Shapes.or(voxelShape, SHAPE); + return voxelShape; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(BlockStateProperties.FACING); + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction facing = state.getValue(BlockStateProperties.FACING); - VoxelShape voxelShape = Shapes.empty(); + VoxelShape voxelShape = Shapes.empty(); - if (facing == Direction.UP) { - voxelShape = Shapes.or(voxelShape, SHAPE_UP); - voxelShape = Shapes.or(voxelShape, SHAPE_UP_2); - } - if (facing == Direction.DOWN) { - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN_2); - } - if (facing == Direction.NORTH) { - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH_2); - } - if (facing == Direction.SOUTH) { - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH_2); - } - if (facing == Direction.EAST) { - voxelShape = Shapes.or(voxelShape, SHAPE_EAST); - voxelShape = Shapes.or(voxelShape, SHAPE_EAST_2); - } - if (facing == Direction.WEST) { - voxelShape = Shapes.or(voxelShape, SHAPE_WEST); - voxelShape = Shapes.or(voxelShape, SHAPE_WEST_2); - } - - voxelShape = Shapes.or(voxelShape, SHAPE); - - return voxelShape; - } - - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { - return 1.0F; - } - - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } - - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - - - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(BlockStateProperties.FACING, BlockStateProperties.ENABLED); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return PortalCubedBlocks.FLOOR_BUTTON.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); - } - - @Override - public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new FloorButtonBlockEntity(pos, state); - } - - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return createTickerHelper(type, PortalCubedBlocks.FLOOR_BUTTON_BLOCK_ENTITY, FloorButtonBlockEntity::tick1); - } - - @Override - public String getDescriptionId() { - return enableEasterEgg ? "block.portalcubed.floor_button.easter_egg" : "block.portalcubed.floor_button"; - } + if (facing == Direction.UP) { + voxelShape = Shapes.or(voxelShape, SHAPE_UP); + voxelShape = Shapes.or(voxelShape, SHAPE_UP_2); + } + if (facing == Direction.DOWN) { + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN_2); + } + if (facing == Direction.NORTH) { + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH_2); + } + if (facing == Direction.SOUTH) { + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH_2); + } + if (facing == Direction.EAST) { + voxelShape = Shapes.or(voxelShape, SHAPE_EAST); + voxelShape = Shapes.or(voxelShape, SHAPE_EAST_2); + } + if (facing == Direction.WEST) { + voxelShape = Shapes.or(voxelShape, SHAPE_WEST); + voxelShape = Shapes.or(voxelShape, SHAPE_WEST_2); + } + + voxelShape = Shapes.or(voxelShape, SHAPE); + + return voxelShape; + } + + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { + return 1.0F; + } + + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } + + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } + + + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(BlockStateProperties.FACING, BlockStateProperties.ENABLED); + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return PortalCubedBlocks.FLOOR_BUTTON.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()); + } + + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); + } + + @Override + public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new FloorButtonBlockEntity(pos, state); + } + + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PortalCubedBlocks.FLOOR_BUTTON_BLOCK_ENTITY, FloorButtonBlockEntity::tick1); + } + + @Override + public String getDescriptionId() { + return enableEasterEgg ? "block.portalcubed.floor_button.easter_egg" : "block.portalcubed.floor_button"; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/LaserCatcherBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/LaserCatcherBlock.java index a98ef3c3..cf335ad8 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/LaserCatcherBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/LaserCatcherBlock.java @@ -15,46 +15,46 @@ public class LaserCatcherBlock extends AbstractLaserNodeBlock { - public static final DirectionProperty FACING = BlockStateProperties.FACING; - - protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - - public LaserCatcherBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any().setValue(ENABLED, false)); - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ENABLED); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return PortalCubedBlocks.LASER_CATCHER.defaultBlockState().setValue(FACING, ctx.getNearestLookingDirection().getOpposite()); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); - } + public static final DirectionProperty FACING = BlockStateProperties.FACING; + + protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); + + public LaserCatcherBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any().setValue(ENABLED, false)); + } + + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } + + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, ENABLED); + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return PortalCubedBlocks.LASER_CATCHER.defaultBlockState().setValue(FACING, ctx.getNearestLookingDirection().getOpposite()); + } + + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } + + @Override + @SuppressWarnings("deprecation") + public BlockState mirror(BlockState state, Mirror mirror) { + return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/LaserEmitterBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/LaserEmitterBlock.java index fd9cfa79..da8a2326 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/LaserEmitterBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/LaserEmitterBlock.java @@ -19,79 +19,79 @@ public class LaserEmitterBlock extends BaseEntityBlock { - public static final DirectionProperty FACING = BlockStateProperties.FACING; - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final DirectionProperty FACING = BlockStateProperties.FACING; + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - public LaserEmitterBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any()); - } + public LaserEmitterBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any()); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, POWERED); + } - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new LaserEmitterBlockEntity(pos, state); - } + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new LaserEmitterBlockEntity(pos, state); + } - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return defaultBlockState() - .setValue(FACING, ctx.getNearestLookingDirection().getOpposite()) - .setValue(POWERED, ctx.getLevel().hasNeighborSignal(ctx.getClickedPos())); - } + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return defaultBlockState() + .setValue(FACING, ctx.getNearestLookingDirection().getOpposite()) + .setValue(POWERED, ctx.getLevel().hasNeighborSignal(ctx.getClickedPos())); + } - @Override - @SuppressWarnings("deprecation") - public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { - final boolean powered = world.hasNeighborSignal(pos); - if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { - world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); - if (powered && !world.isClientSide) { - world.playSound(null, pos, PortalCubedSounds.LASER_EMITTER_ACTIVATE_EVENT, SoundSource.BLOCKS, 0.25f, 1f); - } - } - } + @Override + @SuppressWarnings("deprecation") + public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { + final boolean powered = world.hasNeighborSignal(pos); + if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { + world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); + if (powered && !world.isClientSide) { + world.playSound(null, pos, PortalCubedSounds.LASER_EMITTER_ACTIVATE_EVENT, SoundSource.BLOCKS, 0.25f, 1f); + } + } + } - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } - @Override - @SuppressWarnings("deprecation") - public BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); - } + @Override + @SuppressWarnings("deprecation") + public BlockState mirror(BlockState state, Mirror mirror) { + return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + } - @Override - @SuppressWarnings("deprecation") - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - if (stateFrom.is(PortalCubedBlocks.LASER_EMITTER)) { - return stateFrom.getValue(BlockStateProperties.POWERED); - } else return stateFrom.is(PortalCubedBlocks.HLB_BLOCK); - } + @Override + @SuppressWarnings("deprecation") + public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { + if (stateFrom.is(PortalCubedBlocks.LASER_EMITTER)) { + return stateFrom.getValue(BlockStateProperties.POWERED); + } else return stateFrom.is(PortalCubedBlocks.HLB_BLOCK); + } - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return type == PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY - ? (world1, pos, state1, entity) -> ((LaserEmitterBlockEntity)entity).tick(world1, pos, state1) - : null; - } + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return type == PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY + ? (world1, pos, state1, entity) -> ((LaserEmitterBlockEntity)entity).tick(world1, pos, state1) + : null; + } - @Override - @SuppressWarnings("deprecation") - public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) { - level.getBlockEntity(pos, PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY).ifPresent(LaserEmitterBlockEntity::clearTargets); - super.onRemove(state, level, pos, newState, movedByPiston); - } + @Override + @SuppressWarnings("deprecation") + public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) { + level.getBlockEntity(pos, PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY).ifPresent(LaserEmitterBlockEntity::clearTargets); + super.onRemove(state, level, pos, newState, movedByPiston); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/LaserRelayBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/LaserRelayBlock.java index 465d09c6..7ca51dfe 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/LaserRelayBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/LaserRelayBlock.java @@ -21,57 +21,57 @@ import java.util.stream.Collectors; public class LaserRelayBlock extends AbstractLaserNodeBlock { - public static final DirectionProperty FACING = BlockStateProperties.FACING; + public static final DirectionProperty FACING = BlockStateProperties.FACING; - private static final VoxelShape UP_SHAPE = Shapes.or( - box(4, 0, 4, 12, 11, 12) - ); - private static final VoxelShape DOWN_SHAPE = Shapes.or( - box(4, 6, 4, 12, 16, 12) - ); - private static final VoxelShape NORTH_SHAPE = Shapes.or( - box(4, 4, 6, 12, 12, 16) - ); - private static final Map DIRECTION_TO_SHAPE = Direction.stream() - .filter(d -> d.getAxis().isHorizontal()) - .collect(Collectors.toMap( - Function.identity(), - d -> GeneralUtil.rotate(NORTH_SHAPE, d), - (m1, m2) -> { - throw new AssertionError("Sequential stream"); - }, - () -> new EnumMap<>(Direction.class) - )); + private static final VoxelShape UP_SHAPE = Shapes.or( + box(4, 0, 4, 12, 11, 12) + ); + private static final VoxelShape DOWN_SHAPE = Shapes.or( + box(4, 6, 4, 12, 16, 12) + ); + private static final VoxelShape NORTH_SHAPE = Shapes.or( + box(4, 4, 6, 12, 12, 16) + ); + private static final Map DIRECTION_TO_SHAPE = Direction.stream() + .filter(d -> d.getAxis().isHorizontal()) + .collect(Collectors.toMap( + Function.identity(), + d -> GeneralUtil.rotate(NORTH_SHAPE, d), + (m1, m2) -> { + throw new AssertionError("Sequential stream"); + }, + () -> new EnumMap<>(Direction.class) + )); - static { - DIRECTION_TO_SHAPE.put(Direction.UP, UP_SHAPE); - DIRECTION_TO_SHAPE.put(Direction.DOWN, DOWN_SHAPE); - } + static { + DIRECTION_TO_SHAPE.put(Direction.UP, UP_SHAPE); + DIRECTION_TO_SHAPE.put(Direction.DOWN, DOWN_SHAPE); + } - public LaserRelayBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any().setValue(ENABLED, false)); - } + public LaserRelayBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any().setValue(ENABLED, false)); + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return DIRECTION_TO_SHAPE.get(state.getValue(FACING)); - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return DIRECTION_TO_SHAPE.get(state.getValue(FACING)); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ENABLED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, ENABLED); + } - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return PortalCubedBlocks.LASER_RELAY.defaultBlockState().setValue(FACING, ctx.getClickedFace()); - } + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return PortalCubedBlocks.LASER_RELAY.defaultBlockState().setValue(FACING, ctx.getClickedFace()); + } - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/MapColorNames.java b/src/main/java/com/fusionflux/portalcubed/blocks/MapColorNames.java index 2cfad968..011fcc35 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/MapColorNames.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/MapColorNames.java @@ -6,71 +6,71 @@ import java.util.Map; public class MapColorNames { - public static final Map COLORS = ImmutableMap.builder() - .put("none", MapColor.NONE) - .put("grass", MapColor.GRASS) - .put("sand", MapColor.SAND) - .put("wool", MapColor.WOOL) - .put("fire", MapColor.FIRE) - .put("ice", MapColor.ICE) - .put("metal", MapColor.METAL) - .put("plant", MapColor.PLANT) - .put("snow", MapColor.SNOW) - .put("clay", MapColor.CLAY) - .put("dirt", MapColor.DIRT) - .put("stone", MapColor.STONE) - .put("water", MapColor.WATER) - .put("wood", MapColor.WOOD) - .put("quartz", MapColor.QUARTZ) - .put("color_orange", MapColor.COLOR_ORANGE) - .put("color_magenta", MapColor.COLOR_MAGENTA) - .put("color_light_blue", MapColor.COLOR_LIGHT_BLUE) - .put("color_yellow", MapColor.COLOR_YELLOW) - .put("color_light_green", MapColor.COLOR_LIGHT_GREEN) - .put("color_pink", MapColor.COLOR_PINK) - .put("color_gray", MapColor.COLOR_GRAY) - .put("color_light_gray", MapColor.COLOR_LIGHT_GRAY) - .put("color_cyan", MapColor.COLOR_CYAN) - .put("color_purple", MapColor.COLOR_PURPLE) - .put("color_blue", MapColor.COLOR_BLUE) - .put("color_brown", MapColor.COLOR_BROWN) - .put("color_green", MapColor.COLOR_GREEN) - .put("color_red", MapColor.COLOR_RED) - .put("color_black", MapColor.COLOR_BLACK) - .put("gold", MapColor.GOLD) - .put("diamond", MapColor.DIAMOND) - .put("lapis", MapColor.LAPIS) - .put("emerald", MapColor.EMERALD) - .put("podzol", MapColor.PODZOL) - .put("nether", MapColor.NETHER) - .put("terracotta_white", MapColor.TERRACOTTA_WHITE) - .put("terracotta_orange", MapColor.TERRACOTTA_ORANGE) - .put("terracotta_magenta", MapColor.TERRACOTTA_MAGENTA) - .put("terracotta_light_blue", MapColor.TERRACOTTA_LIGHT_BLUE) - .put("terracotta_yellow", MapColor.TERRACOTTA_YELLOW) - .put("terracotta_light_green", MapColor.TERRACOTTA_LIGHT_GREEN) - .put("terracotta_pink", MapColor.TERRACOTTA_PINK) - .put("terracotta_gray", MapColor.TERRACOTTA_GRAY) - .put("terracotta_light_gray", MapColor.TERRACOTTA_LIGHT_GRAY) - .put("terracotta_cyan", MapColor.TERRACOTTA_CYAN) - .put("terracotta_purple", MapColor.TERRACOTTA_PURPLE) - .put("terracotta_blue", MapColor.TERRACOTTA_BLUE) - .put("terracotta_brown", MapColor.TERRACOTTA_BROWN) - .put("terracotta_green", MapColor.TERRACOTTA_GREEN) - .put("terracotta_red", MapColor.TERRACOTTA_RED) - .put("terracotta_black", MapColor.TERRACOTTA_BLACK) - .put("crimson_nylium", MapColor.CRIMSON_NYLIUM) - .put("crimson_stem", MapColor.CRIMSON_STEM) - .put("crimson_hyphae", MapColor.CRIMSON_HYPHAE) - .put("warped_nylium", MapColor.WARPED_NYLIUM) - .put("warped_stem", MapColor.WARPED_STEM) - .put("warped_hyphae", MapColor.WARPED_HYPHAE) - .put("warped_wart_block", MapColor.WARPED_WART_BLOCK) - .put("deepslate", MapColor.DEEPSLATE) - .put("raw_iron", MapColor.RAW_IRON) - .put("glow_lichen", MapColor.GLOW_LICHEN) - .build(); + public static final Map COLORS = ImmutableMap.builder() + .put("none", MapColor.NONE) + .put("grass", MapColor.GRASS) + .put("sand", MapColor.SAND) + .put("wool", MapColor.WOOL) + .put("fire", MapColor.FIRE) + .put("ice", MapColor.ICE) + .put("metal", MapColor.METAL) + .put("plant", MapColor.PLANT) + .put("snow", MapColor.SNOW) + .put("clay", MapColor.CLAY) + .put("dirt", MapColor.DIRT) + .put("stone", MapColor.STONE) + .put("water", MapColor.WATER) + .put("wood", MapColor.WOOD) + .put("quartz", MapColor.QUARTZ) + .put("color_orange", MapColor.COLOR_ORANGE) + .put("color_magenta", MapColor.COLOR_MAGENTA) + .put("color_light_blue", MapColor.COLOR_LIGHT_BLUE) + .put("color_yellow", MapColor.COLOR_YELLOW) + .put("color_light_green", MapColor.COLOR_LIGHT_GREEN) + .put("color_pink", MapColor.COLOR_PINK) + .put("color_gray", MapColor.COLOR_GRAY) + .put("color_light_gray", MapColor.COLOR_LIGHT_GRAY) + .put("color_cyan", MapColor.COLOR_CYAN) + .put("color_purple", MapColor.COLOR_PURPLE) + .put("color_blue", MapColor.COLOR_BLUE) + .put("color_brown", MapColor.COLOR_BROWN) + .put("color_green", MapColor.COLOR_GREEN) + .put("color_red", MapColor.COLOR_RED) + .put("color_black", MapColor.COLOR_BLACK) + .put("gold", MapColor.GOLD) + .put("diamond", MapColor.DIAMOND) + .put("lapis", MapColor.LAPIS) + .put("emerald", MapColor.EMERALD) + .put("podzol", MapColor.PODZOL) + .put("nether", MapColor.NETHER) + .put("terracotta_white", MapColor.TERRACOTTA_WHITE) + .put("terracotta_orange", MapColor.TERRACOTTA_ORANGE) + .put("terracotta_magenta", MapColor.TERRACOTTA_MAGENTA) + .put("terracotta_light_blue", MapColor.TERRACOTTA_LIGHT_BLUE) + .put("terracotta_yellow", MapColor.TERRACOTTA_YELLOW) + .put("terracotta_light_green", MapColor.TERRACOTTA_LIGHT_GREEN) + .put("terracotta_pink", MapColor.TERRACOTTA_PINK) + .put("terracotta_gray", MapColor.TERRACOTTA_GRAY) + .put("terracotta_light_gray", MapColor.TERRACOTTA_LIGHT_GRAY) + .put("terracotta_cyan", MapColor.TERRACOTTA_CYAN) + .put("terracotta_purple", MapColor.TERRACOTTA_PURPLE) + .put("terracotta_blue", MapColor.TERRACOTTA_BLUE) + .put("terracotta_brown", MapColor.TERRACOTTA_BROWN) + .put("terracotta_green", MapColor.TERRACOTTA_GREEN) + .put("terracotta_red", MapColor.TERRACOTTA_RED) + .put("terracotta_black", MapColor.TERRACOTTA_BLACK) + .put("crimson_nylium", MapColor.CRIMSON_NYLIUM) + .put("crimson_stem", MapColor.CRIMSON_STEM) + .put("crimson_hyphae", MapColor.CRIMSON_HYPHAE) + .put("warped_nylium", MapColor.WARPED_NYLIUM) + .put("warped_stem", MapColor.WARPED_STEM) + .put("warped_hyphae", MapColor.WARPED_HYPHAE) + .put("warped_wart_block", MapColor.WARPED_WART_BLOCK) + .put("deepslate", MapColor.DEEPSLATE) + .put("raw_iron", MapColor.RAW_IRON) + .put("glow_lichen", MapColor.GLOW_LICHEN) + .build(); - private MapColorNames() { - } + private MapColorNames() { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinBlock.java index af03be30..3f271432 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinBlock.java @@ -22,53 +22,53 @@ public class NeurotoxinBlock extends BaseEntityBlock { - public NeurotoxinBlock(Properties settings) { - super(settings); - } + public NeurotoxinBlock(Properties settings) { + super(settings); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return Shapes.empty(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return Shapes.empty(); + } - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - if (state.is(this)) { - if (random.nextInt(10) == 0) { - world.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); - } - } - } + @Override + @SuppressWarnings("deprecation") + public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { + if (state.is(this)) { + if (random.nextInt(10) == 0) { + world.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); + } + } + } - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } - @NotNull - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @NotNull + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - @Override - @SuppressWarnings("deprecation") - public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { - if (!level.isClientSide) { - entity.hurt(level.damageSources().drown(), 1); - } - } + @Override + @SuppressWarnings("deprecation") + public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { + if (!level.isClientSide) { + entity.hurt(level.damageSources().drown(), 1); + } + } - @Override - public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new NeurotoxinBlockEntity(pos, state); - } + @Override + public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new NeurotoxinBlockEntity(pos, state); + } - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return createTickerHelper(type, PortalCubedBlocks.NEUROTOXIN_BLOCK_ENTITY, NeurotoxinBlockEntity::tick); - } + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PortalCubedBlocks.NEUROTOXIN_BLOCK_ENTITY, NeurotoxinBlockEntity::tick); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinEmitterBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinEmitterBlock.java index fe52b582..bd3a48ba 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinEmitterBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/NeurotoxinEmitterBlock.java @@ -26,74 +26,74 @@ public class NeurotoxinEmitterBlock extends BaseEntityBlock { - protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); + protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - public NeurotoxinEmitterBlock(Properties settings) { - super(settings); - } + public NeurotoxinEmitterBlock(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(BlockStateProperties.FACING, BlockStateProperties.POWERED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(BlockStateProperties.FACING, BlockStateProperties.POWERED); + } - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return PortalCubedBlocks.NEUROTOXIN_EMITTER.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()).setValue(BlockStateProperties.POWERED, false); - } + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return PortalCubedBlocks.NEUROTOXIN_EMITTER.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()).setValue(BlockStateProperties.POWERED, false); + } - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - if (!world.isClientSide) { - ((NeurotoxinEmitterBlockEntity) Objects.requireNonNull(world.getBlockEntity(pos))).spookyUpdateObstructor(pos); - } - } + @Override + public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { + if (!world.isClientSide) { + ((NeurotoxinEmitterBlockEntity) Objects.requireNonNull(world.getBlockEntity(pos))).spookyUpdateObstructor(pos); + } + } - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); - } + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); + } - @Override - public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new NeurotoxinEmitterBlockEntity(pos, state); - } + @Override + public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new NeurotoxinEmitterBlockEntity(pos, state); + } - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return createTickerHelper(type, PortalCubedBlocks.NEUROTOXIN_EMITTER_ENTITY, NeurotoxinEmitterBlockEntity::tick); - } + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PortalCubedBlocks.NEUROTOXIN_EMITTER_ENTITY, NeurotoxinEmitterBlockEntity::tick); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/OldApBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/OldApBlock.java index f65eab16..277ab325 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/OldApBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/OldApBlock.java @@ -6,16 +6,16 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class OldApBlock extends Block { - public OldApBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.defaultBlockState()); - } + public OldApBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.defaultBlockState()); + } - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - return stateFrom.getBlock() instanceof OldApBlock; - } + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { + return stateFrom.getBlock() instanceof OldApBlock; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/OldApDirectionalBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/OldApDirectionalBlock.java index 0229777d..4837140a 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/OldApDirectionalBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/OldApDirectionalBlock.java @@ -10,25 +10,25 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class OldApDirectionalBlock extends OldApBlock { - public OldApDirectionalBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.defaultBlockState()); - } + public OldApDirectionalBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.defaultBlockState()); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(BlockStateProperties.HORIZONTAL_FACING); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(BlockStateProperties.HORIZONTAL_FACING); + } - @Override - public @Nullable BlockState getStateForPlacement(BlockPlaceContext ctx) { - return this.defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_FACING, ctx.getHorizontalDirection().getOpposite()); - } + @Override + public @Nullable BlockState getStateForPlacement(BlockPlaceContext ctx) { + return this.defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_FACING, ctx.getHorizontalDirection().getOpposite()); + } - @Override - @ClientOnly - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - return stateFrom.getBlock() instanceof OldApBlock; - } + @Override + @ClientOnly + public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { + return stateFrom.getBlock() instanceof OldApBlock; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/OldApFloorButtonBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/OldApFloorButtonBlock.java index a47b18e7..af5b90d3 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/OldApFloorButtonBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/OldApFloorButtonBlock.java @@ -25,168 +25,168 @@ public class OldApFloorButtonBlock extends BaseEntityBlock { - public static final BooleanProperty ENABLE; + public static final BooleanProperty ENABLE; - protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); + protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape SHAPE_UP = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 18.0D, 15.0D); + protected static final VoxelShape SHAPE_UP = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 18.0D, 15.0D); - protected static final VoxelShape SHAPE_UP_2 = Block.box(-1.0D, 16.0D, -1.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_UP_2 = Block.box(-1.0D, 16.0D, -1.0D, 17.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_DOWN = Block.box(1.0D, -2.0D, 1.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_DOWN = Block.box(1.0D, -2.0D, 1.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_DOWN_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 0.0D, 17.0D); + protected static final VoxelShape SHAPE_DOWN_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 0.0D, 17.0D); - protected static final VoxelShape SHAPE_NORTH = Block.box(1.0D, 1.0D, -2.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_NORTH = Block.box(1.0D, 1.0D, -2.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_NORTH_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 17.0D, 0.0D); + protected static final VoxelShape SHAPE_NORTH_2 = Block.box(-1.0D, -1.0D, -1.0D, 17.0D, 17.0D, 0.0D); - protected static final VoxelShape SHAPE_SOUTH = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 18.0D); + protected static final VoxelShape SHAPE_SOUTH = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 18.0D); - protected static final VoxelShape SHAPE_SOUTH_2 = Block.box(-1.0D, -1.0D, 16.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_SOUTH_2 = Block.box(-1.0D, -1.0D, 16.0D, 17.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_WEST = Block.box(-2.0D, 1.0D, 1.0D, 15.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_WEST = Block.box(-2.0D, 1.0D, 1.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_WEST_2 = Block.box(-1.0D, -1.0D, -1.0D, 0.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_WEST_2 = Block.box(-1.0D, -1.0D, -1.0D, 0.0D, 17.0D, 17.0D); - protected static final VoxelShape SHAPE_EAST = Block.box(0.0D, 1.0D, 1.0D, 18.0D, 15.0D, 15.0D); + protected static final VoxelShape SHAPE_EAST = Block.box(0.0D, 1.0D, 1.0D, 18.0D, 15.0D, 15.0D); - protected static final VoxelShape SHAPE_EAST_2 = Block.box(16.0D, -1.0D, -1.0D, 17.0D, 17.0D, 17.0D); + protected static final VoxelShape SHAPE_EAST_2 = Block.box(16.0D, -1.0D, -1.0D, 17.0D, 17.0D, 17.0D); - public OldApFloorButtonBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any().setValue(ENABLE, false)); - } + public OldApFloorButtonBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any().setValue(ENABLE, false)); + } - static { - ENABLE = BlockStateProperties.ENABLED; - } + static { + ENABLE = BlockStateProperties.ENABLED; + } - @Override - @SuppressWarnings("deprecation") - public boolean isSignalSource(BlockState state) { - return state.getValue(BlockStateProperties.ENABLED); - } + @Override + @SuppressWarnings("deprecation") + public boolean isSignalSource(BlockState state) { + return state.getValue(BlockStateProperties.ENABLED); + } - @Override - @SuppressWarnings("deprecation") - public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - if (state.getValue(BlockStateProperties.ENABLED)) { - return 15; - } - return 0; - } + @Override + @SuppressWarnings("deprecation") + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + if (state.getValue(BlockStateProperties.ENABLED)) { + return 15; + } + return 0; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(BlockStateProperties.FACING); + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction facing = state.getValue(BlockStateProperties.FACING); - VoxelShape voxelShape = Shapes.empty(); + VoxelShape voxelShape = Shapes.empty(); - if (facing == Direction.UP) - voxelShape = Shapes.or(voxelShape, SHAPE_UP); - if (facing == Direction.DOWN) - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); - if (facing == Direction.NORTH) - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); - if (facing == Direction.SOUTH) - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); - if (facing == Direction.EAST) - voxelShape = Shapes.or(voxelShape, SHAPE_EAST); - if (facing == Direction.WEST) - voxelShape = Shapes.or(voxelShape, SHAPE_WEST); + if (facing == Direction.UP) + voxelShape = Shapes.or(voxelShape, SHAPE_UP); + if (facing == Direction.DOWN) + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); + if (facing == Direction.NORTH) + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); + if (facing == Direction.SOUTH) + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); + if (facing == Direction.EAST) + voxelShape = Shapes.or(voxelShape, SHAPE_EAST); + if (facing == Direction.WEST) + voxelShape = Shapes.or(voxelShape, SHAPE_WEST); - voxelShape = Shapes.or(voxelShape, SHAPE); - return voxelShape; - } + voxelShape = Shapes.or(voxelShape, SHAPE); + return voxelShape; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(BlockStateProperties.FACING); + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction facing = state.getValue(BlockStateProperties.FACING); - VoxelShape voxelShape = Shapes.empty(); + VoxelShape voxelShape = Shapes.empty(); - if (facing == Direction.UP) { - voxelShape = Shapes.or(voxelShape, SHAPE_UP); - voxelShape = Shapes.or(voxelShape, SHAPE_UP_2); - } - if (facing == Direction.DOWN) { - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); - voxelShape = Shapes.or(voxelShape, SHAPE_DOWN_2); - } - if (facing == Direction.NORTH) { - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); - voxelShape = Shapes.or(voxelShape, SHAPE_NORTH_2); - } - if (facing == Direction.SOUTH) { - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); - voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH_2); - } - if (facing == Direction.EAST) { - voxelShape = Shapes.or(voxelShape, SHAPE_EAST); - voxelShape = Shapes.or(voxelShape, SHAPE_EAST_2); - } - if (facing == Direction.WEST) { - voxelShape = Shapes.or(voxelShape, SHAPE_WEST); - voxelShape = Shapes.or(voxelShape, SHAPE_WEST_2); - } - - voxelShape = Shapes.or(voxelShape, SHAPE); - - return voxelShape; - } - - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { - return 1.0F; - } - - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } - - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - - - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(BlockStateProperties.FACING, BlockStateProperties.ENABLED); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return PortalCubedBlocks.OLD_AP_FLOOR_BUTTON.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); - } - - @Override - public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new OldApFloorButtonBlockEntity(pos, state); - } - - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return createTickerHelper(type, PortalCubedBlocks.OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY, OldApFloorButtonBlockEntity::tick1); - } + if (facing == Direction.UP) { + voxelShape = Shapes.or(voxelShape, SHAPE_UP); + voxelShape = Shapes.or(voxelShape, SHAPE_UP_2); + } + if (facing == Direction.DOWN) { + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN); + voxelShape = Shapes.or(voxelShape, SHAPE_DOWN_2); + } + if (facing == Direction.NORTH) { + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH); + voxelShape = Shapes.or(voxelShape, SHAPE_NORTH_2); + } + if (facing == Direction.SOUTH) { + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH); + voxelShape = Shapes.or(voxelShape, SHAPE_SOUTH_2); + } + if (facing == Direction.EAST) { + voxelShape = Shapes.or(voxelShape, SHAPE_EAST); + voxelShape = Shapes.or(voxelShape, SHAPE_EAST_2); + } + if (facing == Direction.WEST) { + voxelShape = Shapes.or(voxelShape, SHAPE_WEST); + voxelShape = Shapes.or(voxelShape, SHAPE_WEST_2); + } + + voxelShape = Shapes.or(voxelShape, SHAPE); + + return voxelShape; + } + + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { + return 1.0F; + } + + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } + + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } + + + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(BlockStateProperties.FACING, BlockStateProperties.ENABLED); + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return PortalCubedBlocks.OLD_AP_FLOOR_BUTTON.defaultBlockState().setValue(BlockStateProperties.FACING, ctx.getNearestLookingDirection().getOpposite()); + } + + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(BlockStateProperties.FACING, rotation.rotate(state.getValue(BlockStateProperties.FACING))); + } + + @Override + public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new OldApFloorButtonBlockEntity(pos, state); + } + + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PortalCubedBlocks.OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY, OldApFloorButtonBlockEntity::tick1); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/OldApTallButton.java b/src/main/java/com/fusionflux/portalcubed/blocks/OldApTallButton.java index 376cf8e3..7fd4dff5 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/OldApTallButton.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/OldApTallButton.java @@ -4,12 +4,12 @@ import net.minecraft.sounds.SoundEvent; public class OldApTallButton extends TallButtonVariant { - public OldApTallButton(Properties settings) { - super(settings); - } + public OldApTallButton(Properties settings) { + super(settings); + } - @Override - public SoundEvent getClickSound(boolean powered) { - return powered ? PortalCubedSounds.OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT : PortalCubedSounds.OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT; - } + @Override + public SoundEvent getClickSound(boolean powered) { + return powered ? PortalCubedSounds.OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT : PortalCubedSounds.OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/PortalBlocksLoader.java b/src/main/java/com/fusionflux/portalcubed/blocks/PortalBlocksLoader.java index 11ebe924..a708dc5e 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/PortalBlocksLoader.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/PortalBlocksLoader.java @@ -37,148 +37,148 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public final class PortalBlocksLoader { - private static final Map> BLOCK_TYPES = - ImmutableMap.>builder() - .put("default", Block::new) - .put("provided", settings -> null) - .put("pillar", RotatedPillarBlock::new) - .put("directional", DirectionalBlock::new) - .put("old_ap", OldApBlock::new) - .put("old_ap_directional", OldApDirectionalBlock::new) - .put("facade", FacadeBlock::new) - .put("multiface", SimpleMultiSidedBlock::new) - .build(); - private static final Set ALLOWED_IN_PROVIDED = Set.of("render_layer"); - @ClientOnly - private static Map renderLayers; - private static final Map BLOCK_DATA = new LinkedHashMap<>(); + private static final Map> BLOCK_TYPES = + ImmutableMap.>builder() + .put("default", Block::new) + .put("provided", settings -> null) + .put("pillar", RotatedPillarBlock::new) + .put("directional", DirectionalBlock::new) + .put("old_ap", OldApBlock::new) + .put("old_ap_directional", OldApDirectionalBlock::new) + .put("facade", FacadeBlock::new) + .put("multiface", SimpleMultiSidedBlock::new) + .build(); + private static final Set ALLOWED_IN_PROVIDED = Set.of("render_layer"); + @ClientOnly + private static Map renderLayers; + private static final Map BLOCK_DATA = new LinkedHashMap<>(); - static { - if (MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT) { - clinitClient(); - } - } + static { + if (MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT) { + clinitClient(); + } + } - private PortalBlocksLoader() { - } + private PortalBlocksLoader() { + } - @ClientOnly - private static void clinitClient() { - renderLayers = ImmutableMap.builder() - .put("solid", RenderType.solid()) - .put("cutout_mipped", RenderType.cutoutMipped()) - .put("cutout", RenderType.cutout()) - .put("translucent", RenderType.translucent()) - .put("tripwire", RenderType.tripwire()) - .build(); - } + @ClientOnly + private static void clinitClient() { + renderLayers = ImmutableMap.builder() + .put("solid", RenderType.solid()) + .put("cutout_mipped", RenderType.cutoutMipped()) + .put("cutout", RenderType.cutout()) + .put("translucent", RenderType.translucent()) + .put("tripwire", RenderType.tripwire()) + .build(); + } - public static void init(ModContainer mod) { - try (Reader reader = Files.newBufferedReader(mod.getPath("portal_blocks.json"), StandardCharsets.UTF_8)) { - load(GsonHelper.parse(reader)); - } catch (IOException e) { - PortalCubed.LOGGER.error("Failed to load block data", e); - } - } + public static void init(ModContainer mod) { + try (Reader reader = Files.newBufferedReader(mod.getPath("portal_blocks.json"), StandardCharsets.UTF_8)) { + load(GsonHelper.parse(reader)); + } catch (IOException e) { + PortalCubed.LOGGER.error("Failed to load block data", e); + } + } - public static void initCommon() { - BLOCK_DATA.forEach((key, value) -> { - if (value.block == null) return; - final ResourceLocation id = id(key); - Registry.register(BuiltInRegistries.BLOCK, id, value.block); - Registry.register(BuiltInRegistries.ITEM, id, new BlockItem(value.block, new Item.Properties())); - }); - } + public static void initCommon() { + BLOCK_DATA.forEach((key, value) -> { + if (value.block == null) return; + final ResourceLocation id = id(key); + Registry.register(BuiltInRegistries.BLOCK, id, value.block); + Registry.register(BuiltInRegistries.ITEM, id, new BlockItem(value.block, new Item.Properties())); + }); + } - @ClientOnly - public static void initClient() { - BLOCK_DATA.forEach((key, value) -> { - final ResourceLocation id = id(key); - if (value.renderLayer != null) { - final RenderType renderLayer = renderLayers.get(value.renderLayer); - if (renderLayer == null) { - throw new IllegalArgumentException("Unknown render_layer " + value.renderLayer); - } - BlockRenderLayerMap.put( - renderLayer, - BuiltInRegistries.BLOCK.getOptional(id) - .orElseThrow(() -> new IllegalArgumentException("Unknown block in portal_blocks.json: " + id)) - ); - } - }); - } + @ClientOnly + public static void initClient() { + BLOCK_DATA.forEach((key, value) -> { + final ResourceLocation id = id(key); + if (value.renderLayer != null) { + final RenderType renderLayer = renderLayers.get(value.renderLayer); + if (renderLayer == null) { + throw new IllegalArgumentException("Unknown render_layer " + value.renderLayer); + } + BlockRenderLayerMap.put( + renderLayer, + BuiltInRegistries.BLOCK.getOptional(id) + .orElseThrow(() -> new IllegalArgumentException("Unknown block in portal_blocks.json: " + id)) + ); + } + }); + } - private static void load(JsonObject json) { - for (final var entry : json.entrySet()) { - BLOCK_DATA.put(entry.getKey(), parseBlock(entry.getValue().getAsJsonObject(), entry.getKey())); - } - } + private static void load(JsonObject json) { + for (final var entry : json.entrySet()) { + BLOCK_DATA.put(entry.getKey(), parseBlock(entry.getValue().getAsJsonObject(), entry.getKey())); + } + } - private static BlockData parseBlock(JsonObject json, String name) { - final var type = BLOCK_TYPES.get(GsonHelper.getAsString(json, "type", "default")); - if (type == null) { - throw new IllegalArgumentException("Unknown type " + json.get("type")); - } - json.remove("type"); - final QuiltBlockSettings settings = json.has("inherit") - ? BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(GsonHelper.getAsString(json, "inherit"))) - .map(QuiltBlockSettings::copyOf) - .orElseThrow(() -> new IllegalArgumentException("Unknown block " + json.get("inherit"))) - : PortalCubedBlocks.settings() - .strength(3.5f, 3.5f) - .requiresTool(); - json.remove("inherit"); - String renderLayer = null; - for (final var entry : json.entrySet()) { - final JsonElement value = entry.getValue(); - switch (entry.getKey()) { - case "hardness" -> settings.destroyTime(GsonHelper.convertToFloat(value, "hardness")); - case "blast_resistance" -> settings.explosionResistance(GsonHelper.convertToFloat(value, "blast_resistance")); - case "opaque" -> settings.opaque(GsonHelper.convertToBoolean(value, "opaque")); - case "jump_velocity_multiplier" -> settings.jumpFactor(GsonHelper.convertToFloat(value, "jump_velocity_multiplier")); - case "slipperiness" -> settings.friction(GsonHelper.convertToFloat(value, "slipperiness")); - case "sounds" -> settings.sound(parseBlockSounds(value)); - case "map_color" -> settings.mapColor( - Optional.ofNullable(MapColorNames.COLORS.get(GsonHelper.convertToString(value, "map_color"))) - .orElseThrow(() -> new IllegalArgumentException("Unknown map_color " + value)) - ); - case "replaceable" -> settings.replaceable(GsonHelper.convertToBoolean(value, "replaceable")); - case "render_layer" -> renderLayer = GsonHelper.convertToString(value, "render_layer"); - default -> throw new IllegalArgumentException("Unknown Portal Block field " + entry.getKey()); - } - } + private static BlockData parseBlock(JsonObject json, String name) { + final var type = BLOCK_TYPES.get(GsonHelper.getAsString(json, "type", "default")); + if (type == null) { + throw new IllegalArgumentException("Unknown type " + json.get("type")); + } + json.remove("type"); + final QuiltBlockSettings settings = json.has("inherit") + ? BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(GsonHelper.getAsString(json, "inherit"))) + .map(QuiltBlockSettings::copyOf) + .orElseThrow(() -> new IllegalArgumentException("Unknown block " + json.get("inherit"))) + : PortalCubedBlocks.settings() + .strength(3.5f, 3.5f) + .requiresTool(); + json.remove("inherit"); + String renderLayer = null; + for (final var entry : json.entrySet()) { + final JsonElement value = entry.getValue(); + switch (entry.getKey()) { + case "hardness" -> settings.destroyTime(GsonHelper.convertToFloat(value, "hardness")); + case "blast_resistance" -> settings.explosionResistance(GsonHelper.convertToFloat(value, "blast_resistance")); + case "opaque" -> settings.opaque(GsonHelper.convertToBoolean(value, "opaque")); + case "jump_velocity_multiplier" -> settings.jumpFactor(GsonHelper.convertToFloat(value, "jump_velocity_multiplier")); + case "slipperiness" -> settings.friction(GsonHelper.convertToFloat(value, "slipperiness")); + case "sounds" -> settings.sound(parseBlockSounds(value)); + case "map_color" -> settings.mapColor( + Optional.ofNullable(MapColorNames.COLORS.get(GsonHelper.convertToString(value, "map_color"))) + .orElseThrow(() -> new IllegalArgumentException("Unknown map_color " + value)) + ); + case "replaceable" -> settings.replaceable(GsonHelper.convertToBoolean(value, "replaceable")); + case "render_layer" -> renderLayer = GsonHelper.convertToString(value, "render_layer"); + default -> throw new IllegalArgumentException("Unknown Portal Block field " + entry.getKey()); + } + } - final Block result = type.apply(settings); - if (result == null) { - final Set disallowedProperties = Sets.difference(json.keySet(), ALLOWED_IN_PROVIDED); - if (!disallowedProperties.isEmpty()) { - throw new IllegalArgumentException( - "The following properties aren't allowed in \"provided\" block " + name + - ": " + String.join(", ", disallowedProperties) - ); - } - } - return new BlockData(result, renderLayer); - } + final Block result = type.apply(settings); + if (result == null) { + final Set disallowedProperties = Sets.difference(json.keySet(), ALLOWED_IN_PROVIDED); + if (!disallowedProperties.isEmpty()) { + throw new IllegalArgumentException( + "The following properties aren't allowed in \"provided\" block " + name + + ": " + String.join(", ", disallowedProperties) + ); + } + } + return new BlockData(result, renderLayer); + } - private static SoundType parseBlockSounds(JsonElement sounds) { - if (sounds.isJsonPrimitive()) { - return BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(GsonHelper.convertToString(sounds, "sounds"))) - .map(b -> b.getSoundType(b.defaultBlockState())) - .orElseThrow(() -> new IllegalArgumentException("Unknown block " + sounds)); - } - final JsonObject object = GsonHelper.convertToJsonObject(sounds, "sounds"); - return new SoundType( - GsonHelper.getAsFloat(object, "volume", 1f), - GsonHelper.getAsFloat(object, "pitch", 1f), - SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "break"))), - SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "step"))), - SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "place"))), - SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "hit"))), - SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "fall"))) - ); - } + private static SoundType parseBlockSounds(JsonElement sounds) { + if (sounds.isJsonPrimitive()) { + return BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(GsonHelper.convertToString(sounds, "sounds"))) + .map(b -> b.getSoundType(b.defaultBlockState())) + .orElseThrow(() -> new IllegalArgumentException("Unknown block " + sounds)); + } + final JsonObject object = GsonHelper.convertToJsonObject(sounds, "sounds"); + return new SoundType( + GsonHelper.getAsFloat(object, "volume", 1f), + GsonHelper.getAsFloat(object, "pitch", 1f), + SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "break"))), + SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "step"))), + SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "place"))), + SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "hit"))), + SoundEvent.createVariableRangeEvent(new ResourceLocation(GsonHelper.getAsString(object, "fall"))) + ); + } - private record BlockData(@Nullable Block block, @Nullable String renderLayer) { - } + private record BlockData(@Nullable Block block, @Nullable String renderLayer) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/PortalCubedBlocks.java b/src/main/java/com/fusionflux/portalcubed/blocks/PortalCubedBlocks.java index 97e70085..3dce85b0 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/PortalCubedBlocks.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/PortalCubedBlocks.java @@ -29,241 +29,241 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedBlocks { - public static final Item BASE_GEL = new Item(new QuiltItemSettings().fireResistant()); - public static final PropulsionGel PROPULSION_GEL = new PropulsionGel(settings().replaceable(false).randomTicks().destroyTime(0f).noOcclusion().noCollission().sound(new SoundType(1, -1, SoundEvents.HONEY_BLOCK_BREAK, SoundEvents.HONEY_BLOCK_STEP, SoundEvents.HONEY_BLOCK_PLACE, SoundEvents.HONEY_BLOCK_HIT, SoundEvents.HONEY_BLOCK_FALL)).mapColor(MapColor.COLOR_ORANGE).pushReaction(PushReaction.DESTROY)); - public static final RepulsionGel REPULSION_GEL = new RepulsionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_LIGHT_BLUE)); - public static final AdhesionGel ADHESION_GEL = new AdhesionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_PURPLE)); - public static final BaseGel CONVERSION_GEL = new BaseGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.METAL)); - public static final BaseGel REFLECTION_GEL = new ReflectionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_LIGHT_GRAY)); - - public static final HardLightBridgeEmitterBlock HLB_EMITTER_BLOCK = new HardLightBridgeEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.BLOCK)); - public static final HardLightBridgeBlock HLB_BLOCK = new HardLightBridgeBlock(settings().destroyTime(999999f).noOcclusion().explosionResistance(9999999999f).mapColor(MapColor.DIAMOND).randomTicks().pushReaction(PushReaction.DESTROY)); - - public static final AutoPortalBlock AUTO_PORTAL_BLOCK = new AutoPortalBlock( - settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.DESTROY) - ); - - // TODO: Due to remapping weirdness, QuiltMaterialBuilder couldn't be used properly here. However, the whole material system is redone in 1.20, and neurotoxin is broken anyway, so this is just a temporary patch. - public static final NeurotoxinBlock NEUROTOXIN_BLOCK = new NeurotoxinBlock(settings().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); - public static final NeurotoxinEmitterBlock NEUROTOXIN_EMITTER = new NeurotoxinEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().noCollission().sound(SoundType.STONE)); - public static final ExcursionFunnelEmitterBlock EXCURSION_FUNNEL_EMITTER = new ExcursionFunnelEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.BLOCK)); + public static final Item BASE_GEL = new Item(new QuiltItemSettings().fireResistant()); + public static final PropulsionGel PROPULSION_GEL = new PropulsionGel(settings().replaceable(false).randomTicks().destroyTime(0f).noOcclusion().noCollission().sound(new SoundType(1, -1, SoundEvents.HONEY_BLOCK_BREAK, SoundEvents.HONEY_BLOCK_STEP, SoundEvents.HONEY_BLOCK_PLACE, SoundEvents.HONEY_BLOCK_HIT, SoundEvents.HONEY_BLOCK_FALL)).mapColor(MapColor.COLOR_ORANGE).pushReaction(PushReaction.DESTROY)); + public static final RepulsionGel REPULSION_GEL = new RepulsionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_LIGHT_BLUE)); + public static final AdhesionGel ADHESION_GEL = new AdhesionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_PURPLE)); + public static final BaseGel CONVERSION_GEL = new BaseGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.METAL)); + public static final BaseGel REFLECTION_GEL = new ReflectionGel(QuiltBlockSettings.copyOf(PROPULSION_GEL).mapColor(MapColor.COLOR_LIGHT_GRAY)); + + public static final HardLightBridgeEmitterBlock HLB_EMITTER_BLOCK = new HardLightBridgeEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.BLOCK)); + public static final HardLightBridgeBlock HLB_BLOCK = new HardLightBridgeBlock(settings().destroyTime(999999f).noOcclusion().explosionResistance(9999999999f).mapColor(MapColor.DIAMOND).randomTicks().pushReaction(PushReaction.DESTROY)); + + public static final AutoPortalBlock AUTO_PORTAL_BLOCK = new AutoPortalBlock( + settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.DESTROY) + ); + + // TODO: Due to remapping weirdness, QuiltMaterialBuilder couldn't be used properly here. However, the whole material system is redone in 1.20, and neurotoxin is broken anyway, so this is just a temporary patch. + public static final NeurotoxinBlock NEUROTOXIN_BLOCK = new NeurotoxinBlock(settings().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); + public static final NeurotoxinEmitterBlock NEUROTOXIN_EMITTER = new NeurotoxinEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().noCollission().sound(SoundType.STONE)); + public static final ExcursionFunnelEmitterBlock EXCURSION_FUNNEL_EMITTER = new ExcursionFunnelEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE).pushReaction(PushReaction.BLOCK)); - public static final TallButton TALL_BUTTON = new TallButton(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops()); - public static final OldApTallButton OLD_AP_PEDESTAL_BUTTON = new OldApTallButton(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops()); + public static final TallButton TALL_BUTTON = new TallButton(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops()); + public static final OldApTallButton OLD_AP_PEDESTAL_BUTTON = new OldApTallButton(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops()); - public static final SlidingDoorBlock PORTAL2DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); - public static final SlidingDoorBlock OCTOPUS_DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); - public static final SlidingDoorBlock OLD_AP_DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); - public static final SlidingDoorBlock PORTAL1DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); - - public static final BlockEntityType AUTO_PORTAL_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(AutoPortalBlockEntity::new, AUTO_PORTAL_BLOCK).build(); - - public static final Block FAITH_PLATE = new FaithPlateBlock(settings().destroyTime(999999f).explosionResistance(9999999999f).sound(new SoundType(1, 1, SoundEvents.STONE_BREAK, SoundEvents.STONE_STEP, SoundEvents.STONE_PLACE, SoundEvents.STONE_HIT, SoundEvents.STONE_FALL)), PortalCubedBlocks::getFaithPlateBlockEntity); - public static final Block BETA_FAITH_PLATE = new FaithPlateBlock(QuiltBlockSettings.copyOf(FAITH_PLATE), PortalCubedBlocks::getBetaFaithPlateBlockEntity); - public static final BlockEntityType FAITH_PLATE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(FaithPlateBlockEntity::new, FAITH_PLATE).build(); - public static final BlockEntityType BETA_FAITH_PLATE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(BetaFaithPlateBlockEntity::new, BETA_FAITH_PLATE).build(); - - public static final Block FAITH_PLATE_TARGET = new FaithPlateTargetBlock(settings().destroyTime(0).noOcclusion().noCollission().mapColor(MapColor.COLOR_CYAN)); - - public static final BlockEntityType NEUROTOXIN_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(NeurotoxinBlockEntity::new, NEUROTOXIN_BLOCK).build(); - public static final BlockEntityType NEUROTOXIN_EMITTER_ENTITY = QuiltBlockEntityTypeBuilder.create(NeurotoxinEmitterBlockEntity::new, NEUROTOXIN_EMITTER).build(); - public static final BlockEntityType EXCURSION_FUNNEL_EMITTER_ENTITY = QuiltBlockEntityTypeBuilder.create(ExcursionFunnelEmitterBlockEntity::new, EXCURSION_FUNNEL_EMITTER).build(); - - public static final PowerBlock POWER_BLOCK = new PowerBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); - - public static final Block VELOCITY_HELPER = new VelocityHelperBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); - public static final BlockEntityType VELOCITY_HELPER_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(VelocityHelperBlockEntity::new, VELOCITY_HELPER).build(); - - public static final Block CATAPULT = new CatapultBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); - public static final BlockEntityType CATAPULT_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(CatapultBlockEntity::new, CATAPULT).build(); - - public static final FizzlerBlock FIZZLER = new FizzlerBlock(settings().noCollission().strength(-1, 3600000).noOcclusion().noCollission().pushReaction(PushReaction.BLOCK)); - public static final FizzlerEmitter FIZZLER_EMITTER = new FizzlerEmitter(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE), FIZZLER); - public static final FizzlerBlock PORTAL_1_FIZZLER = new FizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter PORTAL_1_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), PORTAL_1_FIZZLER); - public static final FizzlerBlock OLD_APERTURE_FIZZLER = new FizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter OLD_APERTURE_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), OLD_APERTURE_FIZZLER); - public static final DeathFizzlerBlock DEATH_FIZZLER = new DeathFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter DEATH_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), DEATH_FIZZLER); - public static final LaserFizzlerBlock LASER_FIZZLER = new LaserFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter LASER_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), LASER_FIZZLER); - public static final DeathFizzlerBlock OLD_APERTURE_DEATH_FIZZLER = new DeathFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter OLD_APERTURE_DEATH_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), OLD_APERTURE_DEATH_FIZZLER); - public static final MatterInquisitionField MATTER_INQUISITION_FIELD = new MatterInquisitionField(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter MATTER_INQUISITION_FIELD_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), MATTER_INQUISITION_FIELD); - public static final PhysicsRepulsionField PHYSICS_REPULSION_FIELD = new PhysicsRepulsionField(QuiltBlockSettings.copyOf(FIZZLER)); - public static final FizzlerEmitter PHYSICS_REPULSION_FIELD_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), PHYSICS_REPULSION_FIELD); + public static final SlidingDoorBlock PORTAL2DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); + public static final SlidingDoorBlock OCTOPUS_DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); + public static final SlidingDoorBlock OLD_AP_DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); + public static final SlidingDoorBlock PORTAL1DOOR = new SlidingDoorBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().pushReaction(PushReaction.DESTROY)); + + public static final BlockEntityType AUTO_PORTAL_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(AutoPortalBlockEntity::new, AUTO_PORTAL_BLOCK).build(); + + public static final Block FAITH_PLATE = new FaithPlateBlock(settings().destroyTime(999999f).explosionResistance(9999999999f).sound(new SoundType(1, 1, SoundEvents.STONE_BREAK, SoundEvents.STONE_STEP, SoundEvents.STONE_PLACE, SoundEvents.STONE_HIT, SoundEvents.STONE_FALL)), PortalCubedBlocks::getFaithPlateBlockEntity); + public static final Block BETA_FAITH_PLATE = new FaithPlateBlock(QuiltBlockSettings.copyOf(FAITH_PLATE), PortalCubedBlocks::getBetaFaithPlateBlockEntity); + public static final BlockEntityType FAITH_PLATE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(FaithPlateBlockEntity::new, FAITH_PLATE).build(); + public static final BlockEntityType BETA_FAITH_PLATE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(BetaFaithPlateBlockEntity::new, BETA_FAITH_PLATE).build(); + + public static final Block FAITH_PLATE_TARGET = new FaithPlateTargetBlock(settings().destroyTime(0).noOcclusion().noCollission().mapColor(MapColor.COLOR_CYAN)); + + public static final BlockEntityType NEUROTOXIN_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(NeurotoxinBlockEntity::new, NEUROTOXIN_BLOCK).build(); + public static final BlockEntityType NEUROTOXIN_EMITTER_ENTITY = QuiltBlockEntityTypeBuilder.create(NeurotoxinEmitterBlockEntity::new, NEUROTOXIN_EMITTER).build(); + public static final BlockEntityType EXCURSION_FUNNEL_EMITTER_ENTITY = QuiltBlockEntityTypeBuilder.create(ExcursionFunnelEmitterBlockEntity::new, EXCURSION_FUNNEL_EMITTER).build(); + + public static final PowerBlock POWER_BLOCK = new PowerBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); + + public static final Block VELOCITY_HELPER = new VelocityHelperBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); + public static final BlockEntityType VELOCITY_HELPER_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(VelocityHelperBlockEntity::new, VELOCITY_HELPER).build(); + + public static final Block CATAPULT = new CatapultBlock(settings().strength(-1.0F, 3600000.8F).noLootTable().noOcclusion().noCollission().replaceable().mapColor(MapColor.NONE)); + public static final BlockEntityType CATAPULT_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(CatapultBlockEntity::new, CATAPULT).build(); + + public static final FizzlerBlock FIZZLER = new FizzlerBlock(settings().noCollission().strength(-1, 3600000).noOcclusion().noCollission().pushReaction(PushReaction.BLOCK)); + public static final FizzlerEmitter FIZZLER_EMITTER = new FizzlerEmitter(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE), FIZZLER); + public static final FizzlerBlock PORTAL_1_FIZZLER = new FizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter PORTAL_1_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), PORTAL_1_FIZZLER); + public static final FizzlerBlock OLD_APERTURE_FIZZLER = new FizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter OLD_APERTURE_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), OLD_APERTURE_FIZZLER); + public static final DeathFizzlerBlock DEATH_FIZZLER = new DeathFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter DEATH_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), DEATH_FIZZLER); + public static final LaserFizzlerBlock LASER_FIZZLER = new LaserFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter LASER_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), LASER_FIZZLER); + public static final DeathFizzlerBlock OLD_APERTURE_DEATH_FIZZLER = new DeathFizzlerBlock(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter OLD_APERTURE_DEATH_FIZZLER_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), OLD_APERTURE_DEATH_FIZZLER); + public static final MatterInquisitionField MATTER_INQUISITION_FIELD = new MatterInquisitionField(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter MATTER_INQUISITION_FIELD_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), MATTER_INQUISITION_FIELD); + public static final PhysicsRepulsionField PHYSICS_REPULSION_FIELD = new PhysicsRepulsionField(QuiltBlockSettings.copyOf(FIZZLER)); + public static final FizzlerEmitter PHYSICS_REPULSION_FIELD_EMITTER = new FizzlerEmitter(QuiltBlockSettings.copyOf(FIZZLER_EMITTER), PHYSICS_REPULSION_FIELD); - public static final LaserEmitterBlock LASER_EMITTER = new LaserEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); - public static final BlockEntityType LASER_EMITTER_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(LaserEmitterBlockEntity::new, LASER_EMITTER).build(); + public static final LaserEmitterBlock LASER_EMITTER = new LaserEmitterBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); + public static final BlockEntityType LASER_EMITTER_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(LaserEmitterBlockEntity::new, LASER_EMITTER).build(); - public static final LaserCatcherBlock LASER_CATCHER = new LaserCatcherBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); - public static final LaserRelayBlock LASER_RELAY = new LaserRelayBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); - public static final BlockEntityType LASER_NODE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(LaserNodeBlockEntity::new, LASER_CATCHER, LASER_RELAY).build(); + public static final LaserCatcherBlock LASER_CATCHER = new LaserCatcherBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); + public static final LaserRelayBlock LASER_RELAY = new LaserRelayBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().noOcclusion().sound(SoundType.STONE)); + public static final BlockEntityType LASER_NODE_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(LaserNodeBlockEntity::new, LASER_CATCHER, LASER_RELAY).build(); - public static final FloorButtonBlock FLOOR_BUTTON = new FloorButtonBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); - public static final BlockEntityType FLOOR_BUTTON_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(FloorButtonBlockEntity::new, FLOOR_BUTTON).build(); + public static final FloorButtonBlock FLOOR_BUTTON = new FloorButtonBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); + public static final BlockEntityType FLOOR_BUTTON_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(FloorButtonBlockEntity::new, FLOOR_BUTTON).build(); - public static final OldApFloorButtonBlock OLD_AP_FLOOR_BUTTON = new OldApFloorButtonBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); - public static final BlockEntityType OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(OldApFloorButtonBlockEntity::new, OLD_AP_FLOOR_BUTTON).build(); + public static final OldApFloorButtonBlock OLD_AP_FLOOR_BUTTON = new OldApFloorButtonBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); + public static final BlockEntityType OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(OldApFloorButtonBlockEntity::new, OLD_AP_FLOOR_BUTTON).build(); - public static final RocketTurretBlock ROCKET_TURRET = new RocketTurretBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); - public static final BlockEntityType ROCKET_TURRET_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(RocketTurretBlockEntity::new, ROCKET_TURRET).build(); + public static final RocketTurretBlock ROCKET_TURRET = new RocketTurretBlock(settings().strength(3.5f, 3.5f).requiresCorrectToolForDrops().sound(SoundType.STONE)); + public static final BlockEntityType ROCKET_TURRET_BLOCK_ENTITY = QuiltBlockEntityTypeBuilder.create(RocketTurretBlockEntity::new, ROCKET_TURRET).build(); - public static final TagKey BULLET_HOLE_CONCRETE = TagKey.create(Registries.BLOCK, id("bullet_hole_concrete")); - public static final TagKey BULLET_HOLE_GLASS = TagKey.create(Registries.BLOCK, id("bullet_hole_glass")); - public static final TagKey BULLET_HOLE_METAL = TagKey.create(Registries.BLOCK, id("bullet_hole_metal")); - public static final TagKey CANT_PLACE_PORTAL_ON = TagKey.create(Registries.BLOCK, id("cant_place_portal_on")); - public static final TagKey PORTALABLE_IN_ADVENTURE = TagKey.create(Registries.BLOCK, id("portalable_in_adventure")); - public static final TagKey PORTAL_NONSOLID = TagKey.create(Registries.BLOCK, id("portal_nonsolid")); - public static final TagKey PORTAL_SOLID = TagKey.create(Registries.BLOCK, id("portal_solid")); - public static final TagKey PORTALABLE_GELS = TagKey.create(Registries.BLOCK, id("portalable_gels")); - public static final TagKey REFLECTIVE = TagKey.create(Registries.BLOCK, id("reflective")); + public static final TagKey BULLET_HOLE_CONCRETE = TagKey.create(Registries.BLOCK, id("bullet_hole_concrete")); + public static final TagKey BULLET_HOLE_GLASS = TagKey.create(Registries.BLOCK, id("bullet_hole_glass")); + public static final TagKey BULLET_HOLE_METAL = TagKey.create(Registries.BLOCK, id("bullet_hole_metal")); + public static final TagKey CANT_PLACE_PORTAL_ON = TagKey.create(Registries.BLOCK, id("cant_place_portal_on")); + public static final TagKey PORTALABLE_IN_ADVENTURE = TagKey.create(Registries.BLOCK, id("portalable_in_adventure")); + public static final TagKey PORTAL_NONSOLID = TagKey.create(Registries.BLOCK, id("portal_nonsolid")); + public static final TagKey PORTAL_SOLID = TagKey.create(Registries.BLOCK, id("portal_solid")); + public static final TagKey PORTALABLE_GELS = TagKey.create(Registries.BLOCK, id("portalable_gels")); + public static final TagKey REFLECTIVE = TagKey.create(Registries.BLOCK, id("reflective")); - public static void registerBlocks() { - Registry.register(BuiltInRegistries.ITEM, id("base_gel"), BASE_GEL); + public static void registerBlocks() { + Registry.register(BuiltInRegistries.ITEM, id("base_gel"), BASE_GEL); - Registry.register(BuiltInRegistries.BLOCK, id("propulsion_gel"), PROPULSION_GEL); - Registry.register(BuiltInRegistries.ITEM, id("propulsion_gel"), new GelBlobItem(PROPULSION_GEL, PortalCubedEntities.PROPULSION_GEL_BLOB, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("propulsion_gel"), PROPULSION_GEL); + Registry.register(BuiltInRegistries.ITEM, id("propulsion_gel"), new GelBlobItem(PROPULSION_GEL, PortalCubedEntities.PROPULSION_GEL_BLOB, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("repulsion_gel"), REPULSION_GEL); - Registry.register(BuiltInRegistries.ITEM, id("repulsion_gel"), new GelBlobItem(REPULSION_GEL, PortalCubedEntities.REPULSION_GEL_BLOB, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("repulsion_gel"), REPULSION_GEL); + Registry.register(BuiltInRegistries.ITEM, id("repulsion_gel"), new GelBlobItem(REPULSION_GEL, PortalCubedEntities.REPULSION_GEL_BLOB, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("adhesion_gel"), ADHESION_GEL); - Registry.register(BuiltInRegistries.ITEM, id("adhesion_gel"), new GelBlobItem(ADHESION_GEL, PortalCubedEntities.ADHESION_GEL_BLOB, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("adhesion_gel"), ADHESION_GEL); + Registry.register(BuiltInRegistries.ITEM, id("adhesion_gel"), new GelBlobItem(ADHESION_GEL, PortalCubedEntities.ADHESION_GEL_BLOB, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("conversion_gel"), CONVERSION_GEL); - Registry.register(BuiltInRegistries.ITEM, id("conversion_gel"), new GelBlobItem(CONVERSION_GEL, PortalCubedEntities.CONVERSION_GEL_BLOB, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("conversion_gel"), CONVERSION_GEL); + Registry.register(BuiltInRegistries.ITEM, id("conversion_gel"), new GelBlobItem(CONVERSION_GEL, PortalCubedEntities.CONVERSION_GEL_BLOB, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("reflection_gel"), REFLECTION_GEL); - Registry.register(BuiltInRegistries.ITEM, id("reflection_gel"), new GelBlobItem(REFLECTION_GEL, PortalCubedEntities.REFLECTION_GEL_BLOB, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("reflection_gel"), REFLECTION_GEL); + Registry.register(BuiltInRegistries.ITEM, id("reflection_gel"), new GelBlobItem(REFLECTION_GEL, PortalCubedEntities.REFLECTION_GEL_BLOB, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("portal_2_door"), PORTAL2DOOR); - Registry.register(BuiltInRegistries.ITEM, id("portal_2_door"), new BlockItem(PORTAL2DOOR, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("portal_2_door"), PORTAL2DOOR); + Registry.register(BuiltInRegistries.ITEM, id("portal_2_door"), new BlockItem(PORTAL2DOOR, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("octopus_door"), OCTOPUS_DOOR); - Registry.register(BuiltInRegistries.ITEM, id("octopus_door"), new BlockItem(OCTOPUS_DOOR, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("octopus_door"), OCTOPUS_DOOR); + Registry.register(BuiltInRegistries.ITEM, id("octopus_door"), new BlockItem(OCTOPUS_DOOR, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("old_ap_door"), OLD_AP_DOOR); - Registry.register(BuiltInRegistries.ITEM, id("old_ap_door"), new BlockItem(OLD_AP_DOOR, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("old_ap_door"), OLD_AP_DOOR); + Registry.register(BuiltInRegistries.ITEM, id("old_ap_door"), new BlockItem(OLD_AP_DOOR, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("portal_1_door"), PORTAL1DOOR); - Registry.register(BuiltInRegistries.ITEM, id("portal_1_door"), new BlockItem(PORTAL1DOOR, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("portal_1_door"), PORTAL1DOOR); + Registry.register(BuiltInRegistries.ITEM, id("portal_1_door"), new BlockItem(PORTAL1DOOR, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("light_bridge_emitter"), HLB_EMITTER_BLOCK); - Registry.register(BuiltInRegistries.ITEM, id("light_bridge_emitter"), new BlockItem(HLB_EMITTER_BLOCK, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("light_bridge"), HLB_BLOCK); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("neurotoxin_entity"), NEUROTOXIN_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("neurotoxin"), NEUROTOXIN_BLOCK); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("neurotoxin_emitter_entity"), NEUROTOXIN_EMITTER_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("neurotoxin_emitter"), NEUROTOXIN_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("neurotoxin_emitter"), new BlockItem(NEUROTOXIN_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("light_bridge_emitter"), HLB_EMITTER_BLOCK); + Registry.register(BuiltInRegistries.ITEM, id("light_bridge_emitter"), new BlockItem(HLB_EMITTER_BLOCK, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("light_bridge"), HLB_BLOCK); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("neurotoxin_entity"), NEUROTOXIN_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("neurotoxin"), NEUROTOXIN_BLOCK); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("neurotoxin_emitter_entity"), NEUROTOXIN_EMITTER_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("neurotoxin_emitter"), NEUROTOXIN_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("neurotoxin_emitter"), new BlockItem(NEUROTOXIN_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("auto_portal_entity"), AUTO_PORTAL_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("auto_portal"), AUTO_PORTAL_BLOCK); - Registry.register(BuiltInRegistries.ITEM, id("auto_portal"), new BlockItem(AUTO_PORTAL_BLOCK, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("auto_portal_entity"), AUTO_PORTAL_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("auto_portal"), AUTO_PORTAL_BLOCK); + Registry.register(BuiltInRegistries.ITEM, id("auto_portal"), new BlockItem(AUTO_PORTAL_BLOCK, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("excursion_funnel_emitter_entity"), EXCURSION_FUNNEL_EMITTER_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("excursion_funnel_emitter"), EXCURSION_FUNNEL_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("excursion_funnel_emitter"), new ExcursionFunnelEmitterBlockItem(EXCURSION_FUNNEL_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("excursion_funnel_emitter_entity"), EXCURSION_FUNNEL_EMITTER_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("excursion_funnel_emitter"), EXCURSION_FUNNEL_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("excursion_funnel_emitter"), new ExcursionFunnelEmitterBlockItem(EXCURSION_FUNNEL_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("faith_plate"), FAITH_PLATE_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("beta_faith_plate"), BETA_FAITH_PLATE_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("faith_plate"), FAITH_PLATE_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("beta_faith_plate"), BETA_FAITH_PLATE_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("faith_plate"), FAITH_PLATE); - Registry.register(BuiltInRegistries.ITEM, id("faith_plate"), new BlockItem(FAITH_PLATE, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("faith_plate"), FAITH_PLATE); + Registry.register(BuiltInRegistries.ITEM, id("faith_plate"), new BlockItem(FAITH_PLATE, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("beta_faith_plate"), BETA_FAITH_PLATE); - Registry.register(BuiltInRegistries.ITEM, id("beta_faith_plate"), new BlockItem(BETA_FAITH_PLATE, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("beta_faith_plate"), BETA_FAITH_PLATE); + Registry.register(BuiltInRegistries.ITEM, id("beta_faith_plate"), new BlockItem(BETA_FAITH_PLATE, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("faith_plate_target"), FAITH_PLATE_TARGET); - Registry.register(BuiltInRegistries.ITEM, id("faith_plate_target"), new BlockItem(FAITH_PLATE_TARGET, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("faith_plate_target"), FAITH_PLATE_TARGET); + Registry.register(BuiltInRegistries.ITEM, id("faith_plate_target"), new BlockItem(FAITH_PLATE_TARGET, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("laser_emitter_entity"), LASER_EMITTER_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("laser_emitter"), LASER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("laser_emitter"), new BlockItem(LASER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("laser_emitter_entity"), LASER_EMITTER_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("laser_emitter"), LASER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("laser_emitter"), new BlockItem(LASER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("laser_catcher"), LASER_CATCHER); - Registry.register(BuiltInRegistries.ITEM, id("laser_catcher"), new BlockItem(LASER_CATCHER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("laser_catcher"), LASER_CATCHER); + Registry.register(BuiltInRegistries.ITEM, id("laser_catcher"), new BlockItem(LASER_CATCHER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("laser_relay"), LASER_RELAY); - Registry.register(BuiltInRegistries.ITEM, id("laser_relay"), new BlockItem(LASER_RELAY, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("laser_relay"), LASER_RELAY); + Registry.register(BuiltInRegistries.ITEM, id("laser_relay"), new BlockItem(LASER_RELAY, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("laser_node"), LASER_NODE_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("laser_node"), LASER_NODE_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("floor_button_block_entity"), FLOOR_BUTTON_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("floor_button"), FLOOR_BUTTON); - Registry.register(BuiltInRegistries.ITEM, id("floor_button"), new BlockItem(FLOOR_BUTTON, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("floor_button_block_entity"), FLOOR_BUTTON_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("floor_button"), FLOOR_BUTTON); + Registry.register(BuiltInRegistries.ITEM, id("floor_button"), new BlockItem(FLOOR_BUTTON, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("old_ap_floor_button_block_entity"), OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("old_ap_floor_button"), OLD_AP_FLOOR_BUTTON); - Registry.register(BuiltInRegistries.ITEM, id("old_ap_floor_button"), new BlockItem(OLD_AP_FLOOR_BUTTON, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("old_ap_floor_button_block_entity"), OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("old_ap_floor_button"), OLD_AP_FLOOR_BUTTON); + Registry.register(BuiltInRegistries.ITEM, id("old_ap_floor_button"), new BlockItem(OLD_AP_FLOOR_BUTTON, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("rocket_turret"), ROCKET_TURRET_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("rocket_turret"), ROCKET_TURRET); - Registry.register(BuiltInRegistries.ITEM, id("rocket_turret"), new BlockItem(ROCKET_TURRET, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("rocket_turret"), ROCKET_TURRET_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("rocket_turret"), ROCKET_TURRET); + Registry.register(BuiltInRegistries.ITEM, id("rocket_turret"), new BlockItem(ROCKET_TURRET, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("power_block"), POWER_BLOCK); - Registry.register(BuiltInRegistries.ITEM, id("power_block"), new BlockItem(POWER_BLOCK, new Item.Properties().rarity(Rarity.EPIC))); + Registry.register(BuiltInRegistries.BLOCK, id("power_block"), POWER_BLOCK); + Registry.register(BuiltInRegistries.ITEM, id("power_block"), new BlockItem(POWER_BLOCK, new Item.Properties().rarity(Rarity.EPIC))); - Registry.register(BuiltInRegistries.BLOCK, id("velocity_helper"), VELOCITY_HELPER); - Registry.register(BuiltInRegistries.ITEM, id("velocity_helper"), new BlockItem(VELOCITY_HELPER, new Item.Properties().rarity(Rarity.EPIC))); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("velocity_helper"), VELOCITY_HELPER_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("velocity_helper"), VELOCITY_HELPER); + Registry.register(BuiltInRegistries.ITEM, id("velocity_helper"), new BlockItem(VELOCITY_HELPER, new Item.Properties().rarity(Rarity.EPIC))); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("velocity_helper"), VELOCITY_HELPER_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("catapult"), CATAPULT); - Registry.register(BuiltInRegistries.ITEM, id("catapult"), new BlockItem(CATAPULT, new Item.Properties().rarity(Rarity.EPIC))); - Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("catapult"), CATAPULT_BLOCK_ENTITY); + Registry.register(BuiltInRegistries.BLOCK, id("catapult"), CATAPULT); + Registry.register(BuiltInRegistries.ITEM, id("catapult"), new BlockItem(CATAPULT, new Item.Properties().rarity(Rarity.EPIC))); + Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id("catapult"), CATAPULT_BLOCK_ENTITY); - Registry.register(BuiltInRegistries.BLOCK, id("fizzler"), FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("fizzler_emitter"), FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("fizzler_emitter"), new BlockItem(FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("fizzler"), FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("fizzler_emitter"), FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("fizzler_emitter"), new BlockItem(FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("portal_1_fizzler"), PORTAL_1_FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("portal_1_fizzler_emitter"), PORTAL_1_FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("portal_1_fizzler_emitter"), new BlockItem(PORTAL_1_FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("portal_1_fizzler"), PORTAL_1_FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("portal_1_fizzler_emitter"), PORTAL_1_FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("portal_1_fizzler_emitter"), new BlockItem(PORTAL_1_FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_fizzler"), OLD_APERTURE_FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_fizzler_emitter"), OLD_APERTURE_FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("old_aperture_fizzler_emitter"), new BlockItem(OLD_APERTURE_FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_fizzler"), OLD_APERTURE_FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_fizzler_emitter"), OLD_APERTURE_FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("old_aperture_fizzler_emitter"), new BlockItem(OLD_APERTURE_FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("laser_fizzler"), LASER_FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("laser_fizzler_emitter"), LASER_FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("laser_fizzler_emitter"), new BlockItem(LASER_FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("laser_fizzler"), LASER_FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("laser_fizzler_emitter"), LASER_FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("laser_fizzler_emitter"), new BlockItem(LASER_FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("death_fizzler"), DEATH_FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("death_fizzler_emitter"), DEATH_FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("death_fizzler_emitter"), new BlockItem(DEATH_FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("death_fizzler"), DEATH_FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("death_fizzler_emitter"), DEATH_FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("death_fizzler_emitter"), new BlockItem(DEATH_FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_death_fizzler"), OLD_APERTURE_DEATH_FIZZLER); - Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_death_fizzler_emitter"), OLD_APERTURE_DEATH_FIZZLER_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("old_aperture_death_fizzler_emitter"), new BlockItem(OLD_APERTURE_DEATH_FIZZLER_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_death_fizzler"), OLD_APERTURE_DEATH_FIZZLER); + Registry.register(BuiltInRegistries.BLOCK, id("old_aperture_death_fizzler_emitter"), OLD_APERTURE_DEATH_FIZZLER_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("old_aperture_death_fizzler_emitter"), new BlockItem(OLD_APERTURE_DEATH_FIZZLER_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("matter_inquisition_field"), MATTER_INQUISITION_FIELD); - Registry.register(BuiltInRegistries.BLOCK, id("matter_inquisition_field_emitter"), MATTER_INQUISITION_FIELD_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("matter_inquisition_field_emitter"), new BlockItem(MATTER_INQUISITION_FIELD_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("matter_inquisition_field"), MATTER_INQUISITION_FIELD); + Registry.register(BuiltInRegistries.BLOCK, id("matter_inquisition_field_emitter"), MATTER_INQUISITION_FIELD_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("matter_inquisition_field_emitter"), new BlockItem(MATTER_INQUISITION_FIELD_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("physics_repulsion_field"), PHYSICS_REPULSION_FIELD); - Registry.register(BuiltInRegistries.BLOCK, id("physics_repulsion_field_emitter"), PHYSICS_REPULSION_FIELD_EMITTER); - Registry.register(BuiltInRegistries.ITEM, id("physics_repulsion_field_emitter"), new BlockItem(PHYSICS_REPULSION_FIELD_EMITTER, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("physics_repulsion_field"), PHYSICS_REPULSION_FIELD); + Registry.register(BuiltInRegistries.BLOCK, id("physics_repulsion_field_emitter"), PHYSICS_REPULSION_FIELD_EMITTER); + Registry.register(BuiltInRegistries.ITEM, id("physics_repulsion_field_emitter"), new BlockItem(PHYSICS_REPULSION_FIELD_EMITTER, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("pedestal_button"), TALL_BUTTON); - Registry.register(BuiltInRegistries.ITEM, id("pedestal_button"), new BlockItem(TALL_BUTTON, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("pedestal_button"), TALL_BUTTON); + Registry.register(BuiltInRegistries.ITEM, id("pedestal_button"), new BlockItem(TALL_BUTTON, new Item.Properties())); - Registry.register(BuiltInRegistries.BLOCK, id("old_ap_pedestal_button"), OLD_AP_PEDESTAL_BUTTON); - Registry.register(BuiltInRegistries.ITEM, id("old_ap_pedestal_button"), new BlockItem(OLD_AP_PEDESTAL_BUTTON, new Item.Properties())); + Registry.register(BuiltInRegistries.BLOCK, id("old_ap_pedestal_button"), OLD_AP_PEDESTAL_BUTTON); + Registry.register(BuiltInRegistries.ITEM, id("old_ap_pedestal_button"), new BlockItem(OLD_AP_PEDESTAL_BUTTON, new Item.Properties())); - PortalBlocksLoader.initCommon(); - } + PortalBlocksLoader.initCommon(); + } - private static BlockEntityType getFaithPlateBlockEntity() { - return FAITH_PLATE_BLOCK_ENTITY; - } + private static BlockEntityType getFaithPlateBlockEntity() { + return FAITH_PLATE_BLOCK_ENTITY; + } - private static BlockEntityType getBetaFaithPlateBlockEntity() { - return BETA_FAITH_PLATE_BLOCK_ENTITY; - } + private static BlockEntityType getBetaFaithPlateBlockEntity() { + return BETA_FAITH_PLATE_BLOCK_ENTITY; + } - public static QuiltBlockSettings settings() { - return QuiltBlockSettings.copyOf(BlockBehaviour.Properties.of()); - } + public static QuiltBlockSettings settings() { + return QuiltBlockSettings.copyOf(BlockBehaviour.Properties.of()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/PortalMoveListeningBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/PortalMoveListeningBlock.java index 1cc57324..8679e153 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/PortalMoveListeningBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/PortalMoveListeningBlock.java @@ -7,7 +7,7 @@ import net.minecraft.world.level.block.state.BlockState; public interface PortalMoveListeningBlock { - void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal); + void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal); - void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal); + void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal); } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/PowerBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/PowerBlock.java index 755184b6..08b5a424 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/PowerBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/PowerBlock.java @@ -19,62 +19,62 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class PowerBlock extends SpecialHiddenBlock { - public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; + public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; - public static final VoxelShape SHAPE = box(2, 2, 2, 14, 14, 14); + public static final VoxelShape SHAPE = box(2, 2, 2, 14, 14, 14); - public PowerBlock(Properties settings) { - super(settings); - registerDefaultState(defaultBlockState().setValue(LEVEL, 15)); - } + public PowerBlock(Properties settings) { + super(settings); + registerDefaultState(defaultBlockState().setValue(LEVEL, 15)); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - super.createBlockStateDefinition(builder); - builder.add(LEVEL); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + super.createBlockStateDefinition(builder); + builder.add(LEVEL); + } - @Override - protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } + @Override + protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!world.isClientSide) { - world.setBlock(pos, state.cycle(LEVEL), Block.UPDATE_ALL); - return InteractionResult.SUCCESS; - } - return InteractionResult.CONSUME; - } + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!world.isClientSide) { + world.setBlock(pos, state.cycle(LEVEL), Block.UPDATE_ALL); + return InteractionResult.SUCCESS; + } + return InteractionResult.CONSUME; + } - @Override - public ItemStack getCloneItemStack(BlockGetter world, BlockPos pos, BlockState state) { - final ItemStack stack = super.getCloneItemStack(world, pos, state); - if (state.getValue(LEVEL) != 15) { - final CompoundTag compound = new CompoundTag(); - compound.putString(LEVEL.getName(), Integer.toString(state.getValue(LEVEL))); - stack.addTagElement("BlockStateTag", compound); - } - return stack; - } + @Override + public ItemStack getCloneItemStack(BlockGetter world, BlockPos pos, BlockState state) { + final ItemStack stack = super.getCloneItemStack(world, pos, state); + if (state.getValue(LEVEL) != 15) { + final CompoundTag compound = new CompoundTag(); + compound.putString(LEVEL.getName(), Integer.toString(state.getValue(LEVEL))); + stack.addTagElement("BlockStateTag", compound); + } + return stack; + } - @Override - @SuppressWarnings("deprecation") - public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - return state.getValue(LEVEL); - } + @Override + @SuppressWarnings("deprecation") + public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + return state.getValue(LEVEL); + } - @Override - @SuppressWarnings("deprecation") - public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - return state.getValue(LEVEL); - } + @Override + @SuppressWarnings("deprecation") + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + return state.getValue(LEVEL); + } - @Override - @SuppressWarnings("deprecation") - public boolean isSignalSource(BlockState state) { - return state.getValue(LEVEL) > 0; - } + @Override + @SuppressWarnings("deprecation") + public boolean isSignalSource(BlockState state) { + return state.getValue(LEVEL) > 0; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/PropulsionGel.java b/src/main/java/com/fusionflux/portalcubed/blocks/PropulsionGel.java index 8d285054..29b6dd30 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/PropulsionGel.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/PropulsionGel.java @@ -11,37 +11,37 @@ import net.minecraft.world.level.block.state.BlockState; public class PropulsionGel extends BaseGel { - private final BlockCollisionLimiter limiter = new BlockCollisionLimiter(); + private final BlockCollisionLimiter limiter = new BlockCollisionLimiter(); - public PropulsionGel(Properties settings) { - super(settings); - } + public PropulsionGel(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { - this.addCollisionEffects(world, entity); - } + @Override + @SuppressWarnings("deprecation") + public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { + this.addCollisionEffects(world, entity); + } - private void addCollisionEffects(Level level, Entity entity) { - if (entity.getType().equals(EntityType.BOAT)) { - entity.hurt(level.damageSources().magic(), 200); - } else { - if (entity.onGround()) { - if (!entity.isShiftKeyDown()) { - if (limiter.check(level, entity)) { - if (Math.abs(entity.getDeltaMovement().x) < 2 && Math.abs(entity.getDeltaMovement().z) < 2) { - entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.7, 1.0D, 1.7)); - } else if (Math.abs(entity.getDeltaMovement().x) > 2 && Math.abs(entity.getDeltaMovement().z) > 2) { - entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.01, 1.0D, 1.01)); - } - if (((EntityExt) entity).getMaxFallSpeed() == 0) { - level.playSound(null, entity.position().x(), entity.position().y(), entity.position().z(), PortalCubedSounds.GEL_RUN_EVENT, SoundSource.NEUTRAL, .3F, 1F); - } - ((EntityExt) entity).setMaxFallSpeed(10); - } - } - } - } - } + private void addCollisionEffects(Level level, Entity entity) { + if (entity.getType().equals(EntityType.BOAT)) { + entity.hurt(level.damageSources().magic(), 200); + } else { + if (entity.onGround()) { + if (!entity.isShiftKeyDown()) { + if (limiter.check(level, entity)) { + if (Math.abs(entity.getDeltaMovement().x) < 2 && Math.abs(entity.getDeltaMovement().z) < 2) { + entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.7, 1.0D, 1.7)); + } else if (Math.abs(entity.getDeltaMovement().x) > 2 && Math.abs(entity.getDeltaMovement().z) > 2) { + entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.01, 1.0D, 1.01)); + } + if (((EntityExt) entity).getMaxFallSpeed() == 0) { + level.playSound(null, entity.position().x(), entity.position().y(), entity.position().z(), PortalCubedSounds.GEL_RUN_EVENT, SoundSource.NEUTRAL, .3F, 1F); + } + ((EntityExt) entity).setMaxFallSpeed(10); + } + } + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/ReflectionGel.java b/src/main/java/com/fusionflux/portalcubed/blocks/ReflectionGel.java index e9064927..11812fca 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/ReflectionGel.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/ReflectionGel.java @@ -7,13 +7,13 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class ReflectionGel extends BaseGel { - public ReflectionGel(Properties settings) { - super(settings); - } + public ReflectionGel(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getVisualShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return getShape(state, world, pos, context); - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getVisualShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return getShape(state, world, pos, context); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/RepulsionGel.java b/src/main/java/com/fusionflux/portalcubed/blocks/RepulsionGel.java index 7f9a40ac..0ef0ee89 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/RepulsionGel.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/RepulsionGel.java @@ -15,194 +15,194 @@ public class RepulsionGel extends BaseGel { - public RepulsionGel(Properties settings) { - super(settings); - } - - @Override - @SuppressWarnings("deprecation") - public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { - this.addCollisionEffects(world, entity, pos); - } - - public Vec3 getDirections(BlockState state) { - Vec3 result = Vec3.ZERO; - - if (state.getValue(BlockStateProperties.NORTH)) { - result = result.subtract(0, 0, 1); - } - if (state.getValue(BlockStateProperties.SOUTH)) { - result = result.add(0, 0, 1); - } - - if (state.getValue(BlockStateProperties.SOUTH) && state.getValue(BlockStateProperties.NORTH)) { - result = result.add(0, 0, 2); - } - - if (state.getValue(BlockStateProperties.EAST)) { - result = result.add(1, 0, 0); - } - if (state.getValue(BlockStateProperties.WEST)) { - result = result.subtract(1, 0, 0); - } - - if (state.getValue(BlockStateProperties.EAST) && state.getValue(BlockStateProperties.WEST)) { - result = result.add(2, 0, 0); - } - - if (state.getValue(BlockStateProperties.UP)) { - result = result.add(0, 1, 0); - } - if (state.getValue(BlockStateProperties.DOWN)) { - result = result.subtract(0, 1, 0); - } - - if (state.getValue(BlockStateProperties.UP) && state.getValue(BlockStateProperties.DOWN)) { - result = result.add(0, 2, 0); - } - - return result; - } - - private void addCollisionEffects(Level world, Entity entity, BlockPos pos) { - Vec3 vec3dLast = ((EntityExt) entity).getLastVel(); - Vec3 vec3d = new Vec3(Math.max(entity.getDeltaMovement().x(), vec3dLast.x()), Math.max(entity.getDeltaMovement().y(), vec3dLast.y()), Math.max(entity.getDeltaMovement().z(), vec3dLast.z())); - BlockState state = world.getBlockState(pos); - - Vec3 direction = getDirections(state); - Vec3 rotatedPos = entity.position(); - direction = RotationUtil.vecWorldToPlayer(direction, GravityChangerAPI.getGravityDirection(entity)); - rotatedPos = RotationUtil.vecWorldToPlayer(rotatedPos, GravityChangerAPI.getGravityDirection(entity)); - - if (!entity.isSuppressingBounce()) { - final boolean jumping = entity instanceof LivingEntityAccessor living && living.isJumping(); - if (entity.verticalCollision || jumping) { - final boolean speedGel = Math.abs(vec3d.x()) + Math.abs(vec3d.z()) > 0.6; - if ((direction.y == -1 || Math.abs(direction.y) == 2) && (vec3dLast.y() < 0 || speedGel || jumping)) { - double fall = ((EntityExt) entity).getMaxFallHeight(); - if (fall != rotatedPos.y || speedGel) { - - fall = fall - rotatedPos.y; - if (fall < 5) { - fall = 5; - } - double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; - entity.setOnGround(false); - entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); - ((EntityExt) entity).setMaxFallHeight(rotatedPos.y); - PortalCubed.playBounceSound(entity); - if (entity instanceof Player && world.isClientSide && (jumping || speedGel)) { - PortalCubed.playBounceSoundRemotely(); - } - } - } - if (direction.y == 1 || Math.abs(direction.y) == 2 && vec3dLast.y() > 0) { - entity.setDeltaMovement(vec3d.x, -vec3dLast.y, vec3d.z); - PortalCubed.playBounceSound(entity); - } - } - - double defaultVelocity = Math.sqrt(2 * .08 * .25); - if (entity.horizontalCollision) { - if (direction.z == -1 || Math.abs(direction.z) == 2 && vec3dLast.z() < 0) { - if (Math.abs(vec3dLast.z) < defaultVelocity) { - entity.setDeltaMovement(vec3d.x, vec3d.y, defaultVelocity); - } else { - entity.setDeltaMovement(vec3d.x, vec3d.y, -vec3dLast.z); - } - if (Math.abs(vec3dLast.z) > .1) { - if (vec3dLast.y() != 0) { - double fall = ((EntityExt)entity).getMaxFallHeight(); - if (fall != rotatedPos.y) { - - fall = fall - rotatedPos.y; - if (fall < 1.5) { - fall = 1.5; - } - - double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; - entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); - ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); - } - } - } - - PortalCubed.playBounceSound(entity); - } - if (direction.z == 1 || Math.abs(direction.z) == 2 && vec3dLast.z() > 0) { - if (Math.abs(vec3dLast.z) < defaultVelocity) { - entity.setDeltaMovement(vec3d.x, vec3d.y, -defaultVelocity); - } else { - entity.setDeltaMovement(vec3d.x, vec3d.y, -vec3dLast.z); - } - if (Math.abs(vec3dLast.z) > .1 && vec3dLast.y() != 0) { - double fall = ((EntityExt)entity).getMaxFallHeight(); - if (fall != rotatedPos.y) { - - fall = fall - rotatedPos.y; - if (fall < 1.5) { - fall = 1.5; - } - double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; - entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); - ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); - } - } - PortalCubed.playBounceSound(entity); - } - if (direction.x == 1 || Math.abs(direction.x) == 2 && vec3dLast.x() > 0) { - - if (Math.abs(vec3dLast.x) < defaultVelocity) { - entity.setDeltaMovement(-defaultVelocity, vec3d.y, vec3d.z); - } else { - entity.setDeltaMovement(-vec3dLast.x, vec3d.y, vec3d.z); - } - if (Math.abs(vec3dLast.x) > .1 && vec3dLast.y() != 0) { - double fall = ((EntityExt)entity).getMaxFallHeight(); - if (fall != rotatedPos.y) { - - fall = fall - rotatedPos.y; - if (fall < 1.5) { - fall = 1.5; - } - double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; - entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); - ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); - } - } - PortalCubed.playBounceSound(entity); - } - if (direction.x == -1 || Math.abs(direction.x) == 2 && vec3dLast.x() < 0) { - if (Math.abs(vec3dLast.x) < defaultVelocity) { - entity.setDeltaMovement(defaultVelocity, vec3d.y, vec3d.z); - } else { - entity.setDeltaMovement(-vec3dLast.x, vec3d.y, vec3d.z); - } - if (Math.abs(vec3dLast.x) > .1 && vec3dLast.y() != 0) { - double fall = ((EntityExt)entity).getMaxFallHeight(); - if (fall != rotatedPos.y) { - - fall = fall - rotatedPos.y; - if (fall < 1.5) { - fall = 1.5; - } - double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; - entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); - ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); - } - } - PortalCubed.playBounceSound(entity); - } - } - } - } - - @Override - public void fallOn(Level level, BlockState state, BlockPos pos, Entity entity, float fallDistance) { - if (entity.isSuppressingBounce()) { - super.fallOn(level, state, pos, entity, fallDistance); - } else { - entity.causeFallDamage(fallDistance, 0.0F, level.damageSources().fall()); - } - } + public RepulsionGel(Properties settings) { + super(settings); + } + + @Override + @SuppressWarnings("deprecation") + public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { + this.addCollisionEffects(world, entity, pos); + } + + public Vec3 getDirections(BlockState state) { + Vec3 result = Vec3.ZERO; + + if (state.getValue(BlockStateProperties.NORTH)) { + result = result.subtract(0, 0, 1); + } + if (state.getValue(BlockStateProperties.SOUTH)) { + result = result.add(0, 0, 1); + } + + if (state.getValue(BlockStateProperties.SOUTH) && state.getValue(BlockStateProperties.NORTH)) { + result = result.add(0, 0, 2); + } + + if (state.getValue(BlockStateProperties.EAST)) { + result = result.add(1, 0, 0); + } + if (state.getValue(BlockStateProperties.WEST)) { + result = result.subtract(1, 0, 0); + } + + if (state.getValue(BlockStateProperties.EAST) && state.getValue(BlockStateProperties.WEST)) { + result = result.add(2, 0, 0); + } + + if (state.getValue(BlockStateProperties.UP)) { + result = result.add(0, 1, 0); + } + if (state.getValue(BlockStateProperties.DOWN)) { + result = result.subtract(0, 1, 0); + } + + if (state.getValue(BlockStateProperties.UP) && state.getValue(BlockStateProperties.DOWN)) { + result = result.add(0, 2, 0); + } + + return result; + } + + private void addCollisionEffects(Level world, Entity entity, BlockPos pos) { + Vec3 vec3dLast = ((EntityExt) entity).getLastVel(); + Vec3 vec3d = new Vec3(Math.max(entity.getDeltaMovement().x(), vec3dLast.x()), Math.max(entity.getDeltaMovement().y(), vec3dLast.y()), Math.max(entity.getDeltaMovement().z(), vec3dLast.z())); + BlockState state = world.getBlockState(pos); + + Vec3 direction = getDirections(state); + Vec3 rotatedPos = entity.position(); + direction = RotationUtil.vecWorldToPlayer(direction, GravityChangerAPI.getGravityDirection(entity)); + rotatedPos = RotationUtil.vecWorldToPlayer(rotatedPos, GravityChangerAPI.getGravityDirection(entity)); + + if (!entity.isSuppressingBounce()) { + final boolean jumping = entity instanceof LivingEntityAccessor living && living.isJumping(); + if (entity.verticalCollision || jumping) { + final boolean speedGel = Math.abs(vec3d.x()) + Math.abs(vec3d.z()) > 0.6; + if ((direction.y == -1 || Math.abs(direction.y) == 2) && (vec3dLast.y() < 0 || speedGel || jumping)) { + double fall = ((EntityExt) entity).getMaxFallHeight(); + if (fall != rotatedPos.y || speedGel) { + + fall = fall - rotatedPos.y; + if (fall < 5) { + fall = 5; + } + double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; + entity.setOnGround(false); + entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); + ((EntityExt) entity).setMaxFallHeight(rotatedPos.y); + PortalCubed.playBounceSound(entity); + if (entity instanceof Player && world.isClientSide && (jumping || speedGel)) { + PortalCubed.playBounceSoundRemotely(); + } + } + } + if (direction.y == 1 || Math.abs(direction.y) == 2 && vec3dLast.y() > 0) { + entity.setDeltaMovement(vec3d.x, -vec3dLast.y, vec3d.z); + PortalCubed.playBounceSound(entity); + } + } + + double defaultVelocity = Math.sqrt(2 * .08 * .25); + if (entity.horizontalCollision) { + if (direction.z == -1 || Math.abs(direction.z) == 2 && vec3dLast.z() < 0) { + if (Math.abs(vec3dLast.z) < defaultVelocity) { + entity.setDeltaMovement(vec3d.x, vec3d.y, defaultVelocity); + } else { + entity.setDeltaMovement(vec3d.x, vec3d.y, -vec3dLast.z); + } + if (Math.abs(vec3dLast.z) > .1) { + if (vec3dLast.y() != 0) { + double fall = ((EntityExt)entity).getMaxFallHeight(); + if (fall != rotatedPos.y) { + + fall = fall - rotatedPos.y; + if (fall < 1.5) { + fall = 1.5; + } + + double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; + entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); + ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); + } + } + } + + PortalCubed.playBounceSound(entity); + } + if (direction.z == 1 || Math.abs(direction.z) == 2 && vec3dLast.z() > 0) { + if (Math.abs(vec3dLast.z) < defaultVelocity) { + entity.setDeltaMovement(vec3d.x, vec3d.y, -defaultVelocity); + } else { + entity.setDeltaMovement(vec3d.x, vec3d.y, -vec3dLast.z); + } + if (Math.abs(vec3dLast.z) > .1 && vec3dLast.y() != 0) { + double fall = ((EntityExt)entity).getMaxFallHeight(); + if (fall != rotatedPos.y) { + + fall = fall - rotatedPos.y; + if (fall < 1.5) { + fall = 1.5; + } + double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; + entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); + ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); + } + } + PortalCubed.playBounceSound(entity); + } + if (direction.x == 1 || Math.abs(direction.x) == 2 && vec3dLast.x() > 0) { + + if (Math.abs(vec3dLast.x) < defaultVelocity) { + entity.setDeltaMovement(-defaultVelocity, vec3d.y, vec3d.z); + } else { + entity.setDeltaMovement(-vec3dLast.x, vec3d.y, vec3d.z); + } + if (Math.abs(vec3dLast.x) > .1 && vec3dLast.y() != 0) { + double fall = ((EntityExt)entity).getMaxFallHeight(); + if (fall != rotatedPos.y) { + + fall = fall - rotatedPos.y; + if (fall < 1.5) { + fall = 1.5; + } + double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; + entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); + ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); + } + } + PortalCubed.playBounceSound(entity); + } + if (direction.x == -1 || Math.abs(direction.x) == 2 && vec3dLast.x() < 0) { + if (Math.abs(vec3dLast.x) < defaultVelocity) { + entity.setDeltaMovement(defaultVelocity, vec3d.y, vec3d.z); + } else { + entity.setDeltaMovement(-vec3dLast.x, vec3d.y, vec3d.z); + } + if (Math.abs(vec3dLast.x) > .1 && vec3dLast.y() != 0) { + double fall = ((EntityExt)entity).getMaxFallHeight(); + if (fall != rotatedPos.y) { + + fall = fall - rotatedPos.y; + if (fall < 1.5) { + fall = 1.5; + } + double velocity = Math.sqrt(2 * .08 * (fall)) + .0402; + entity.setDeltaMovement(vec3d.x, velocity, vec3d.z); + ((EntityExt)entity).setMaxFallHeight(rotatedPos.y); + } + } + PortalCubed.playBounceSound(entity); + } + } + } + } + + @Override + public void fallOn(Level level, BlockState state, BlockPos pos, Entity entity, float fallDistance) { + if (entity.isSuppressingBounce()) { + super.fallOn(level, state, pos, entity, fallDistance); + } else { + entity.causeFallDamage(fallDistance, 0.0F, level.damageSources().fall()); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/RocketTurretBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/RocketTurretBlock.java index 65d13d94..f2162524 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/RocketTurretBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/RocketTurretBlock.java @@ -21,76 +21,76 @@ import org.jetbrains.annotations.Nullable; public class RocketTurretBlock extends BaseEntityBlock { - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - public static final VoxelShape BASE_SHAPE = Shapes.or( - box(0, 0, 0, 16, 17, 16), - box(1.97, 16.97, 1.97, 14.03, 18.03, 14.03) - ); - public static final VoxelShape POWERED_SHAPE = Shapes.or( - BASE_SHAPE, - box(4, 16, 4, 12, 33, 12) - ); - public static final VoxelShape POWERED_COLLISION_SHAPE = Shapes.or( - BASE_SHAPE, - box(4, 16, 4, 12, 32, 12) - ); + public static final VoxelShape BASE_SHAPE = Shapes.or( + box(0, 0, 0, 16, 17, 16), + box(1.97, 16.97, 1.97, 14.03, 18.03, 14.03) + ); + public static final VoxelShape POWERED_SHAPE = Shapes.or( + BASE_SHAPE, + box(4, 16, 4, 12, 33, 12) + ); + public static final VoxelShape POWERED_COLLISION_SHAPE = Shapes.or( + BASE_SHAPE, + box(4, 16, 4, 12, 32, 12) + ); - public RocketTurretBlock(Properties settings) { - super(settings); - registerDefaultState( - getStateDefinition().any() - .setValue(POWERED, false) - ); - } + public RocketTurretBlock(Properties settings) { + super(settings); + registerDefaultState( + getStateDefinition().any() + .setValue(POWERED, false) + ); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(POWERED); + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return state.getValue(POWERED) ? POWERED_SHAPE : BASE_SHAPE; - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return state.getValue(POWERED) ? POWERED_SHAPE : BASE_SHAPE; + } - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return state.getValue(POWERED) ? POWERED_COLLISION_SHAPE : BASE_SHAPE; - } + @Override + @SuppressWarnings("deprecation") + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return state.getValue(POWERED) ? POWERED_COLLISION_SHAPE : BASE_SHAPE; + } - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } + @Override + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new RocketTurretBlockEntity(pos, state); - } + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new RocketTurretBlockEntity(pos, state); + } - @Nullable - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - return defaultBlockState().setValue(POWERED, ctx.getLevel().hasNeighborSignal(ctx.getClickedPos())); - } + @Nullable + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + return defaultBlockState().setValue(POWERED, ctx.getLevel().hasNeighborSignal(ctx.getClickedPos())); + } - @Override - @SuppressWarnings("deprecation") - public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { - final boolean powered = world.hasNeighborSignal(pos); - if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { - world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); - } - } + @Override + @SuppressWarnings("deprecation") + public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { + final boolean powered = world.hasNeighborSignal(pos); + if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { + world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); + } + } - @Nullable - @Override - public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { - return type == PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY - ? (world1, pos, state1, entity) -> ((RocketTurretBlockEntity)entity).tick(world1, pos, state1) - : null; - } + @Nullable + @Override + public BlockEntityTicker getTicker(Level world, BlockState state, BlockEntityType type) { + return type == PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY + ? (world1, pos, state1, entity) -> ((RocketTurretBlockEntity)entity).tick(world1, pos, state1) + : null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/SimpleLoggedBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/SimpleLoggedBlock.java index 9ac98e75..96a16ebd 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/SimpleLoggedBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/SimpleLoggedBlock.java @@ -18,45 +18,45 @@ import java.util.Optional; public interface SimpleLoggedBlock extends BucketPickupEx, LiquidBlockContainer { - @Override - default boolean canPlaceLiquid(BlockGetter level, BlockPos pos, BlockState state, Fluid fluid) { - final Fluid existingFluid = state.getValue(PortalCubedProperties.LOGGING).fluid; - return existingFluid == Fluids.EMPTY || fluid == existingFluid; - } + @Override + default boolean canPlaceLiquid(BlockGetter level, BlockPos pos, BlockState state, Fluid fluid) { + final Fluid existingFluid = state.getValue(PortalCubedProperties.LOGGING).fluid; + return existingFluid == Fluids.EMPTY || fluid == existingFluid; + } - @Override - default boolean placeLiquid(LevelAccessor level, BlockPos pos, BlockState state, FluidState fluidState) { - if (state.getValue(PortalCubedProperties.LOGGING) != FluidType.EMPTY) { - return false; - } - if (!level.isClientSide()) { - final FluidType fluidType = FluidType.getByFluid(fluidState.getType()); - if (fluidType == null) { - return false; - } - level.setBlock(pos, state.setValue(PortalCubedProperties.LOGGING, fluidType), Block.UPDATE_ALL); - level.scheduleTick(pos, fluidState.getType(), fluidState.getType().getTickDelay(level)); - } - return true; - } + @Override + default boolean placeLiquid(LevelAccessor level, BlockPos pos, BlockState state, FluidState fluidState) { + if (state.getValue(PortalCubedProperties.LOGGING) != FluidType.EMPTY) { + return false; + } + if (!level.isClientSide()) { + final FluidType fluidType = FluidType.getByFluid(fluidState.getType()); + if (fluidType == null) { + return false; + } + level.setBlock(pos, state.setValue(PortalCubedProperties.LOGGING, fluidType), Block.UPDATE_ALL); + level.scheduleTick(pos, fluidState.getType(), fluidState.getType().getTickDelay(level)); + } + return true; + } - @NotNull - @Override - default ItemStack pickupBlock(LevelAccessor level, BlockPos pos, BlockState state) { - final Fluid fluid = state.getValue(PortalCubedProperties.LOGGING).fluid; - if (fluid == Fluids.EMPTY) { - return ItemStack.EMPTY; - } - level.setBlock(pos, state.setValue(PortalCubedProperties.LOGGING, FluidType.EMPTY), Block.UPDATE_ALL); - if (!state.canSurvive(level, pos)) { - level.destroyBlock(pos, true); - } - return new ItemStack(fluid.getBucket()); - } + @NotNull + @Override + default ItemStack pickupBlock(LevelAccessor level, BlockPos pos, BlockState state) { + final Fluid fluid = state.getValue(PortalCubedProperties.LOGGING).fluid; + if (fluid == Fluids.EMPTY) { + return ItemStack.EMPTY; + } + level.setBlock(pos, state.setValue(PortalCubedProperties.LOGGING, FluidType.EMPTY), Block.UPDATE_ALL); + if (!state.canSurvive(level, pos)) { + level.destroyBlock(pos, true); + } + return new ItemStack(fluid.getBucket()); + } - @NotNull - @Override - default Optional getPickupSound(BlockState state) { - return state.getValue(PortalCubedProperties.LOGGING).fluid.getPickupSound(); - } + @NotNull + @Override + default Optional getPickupSound(BlockState state) { + return state.getValue(PortalCubedProperties.LOGGING).fluid.getPickupSound(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/SimpleMultiSidedBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/SimpleMultiSidedBlock.java index fede2a62..866d866a 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/SimpleMultiSidedBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/SimpleMultiSidedBlock.java @@ -7,18 +7,18 @@ import org.jetbrains.annotations.NotNull; public class SimpleMultiSidedBlock extends MultifaceBlock { - public SimpleMultiSidedBlock(Properties settings) { - super(settings); - } + public SimpleMultiSidedBlock(Properties settings) { + super(settings); + } - @NotNull - @Override - public MultifaceSpreader getSpreader() { - return new MultifaceSpreader(this); - } + @NotNull + @Override + public MultifaceSpreader getSpreader() { + return new MultifaceSpreader(this); + } - @Override - public boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) { - return useContext.getItemInHand().is(asItem()) ? super.canBeReplaced(state, useContext) : state.canBeReplaced(); - } + @Override + public boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) { + return useContext.getItemInHand().is(asItem()) ? super.canBeReplaced(state, useContext) : state.canBeReplaced(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/SlidingDoorBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/SlidingDoorBlock.java index 2cd47fec..16f9b819 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/SlidingDoorBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/SlidingDoorBlock.java @@ -29,218 +29,218 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class SlidingDoorBlock extends Block { - public static final DirectionProperty FACING; - public static final BooleanProperty OPEN; - public static final EnumProperty HINGE; - public static final BooleanProperty POWERED; - public static final EnumProperty HALF; - protected static final VoxelShape NORTH_SHAPE; - protected static final VoxelShape SOUTH_SHAPE; - protected static final VoxelShape EAST_SHAPE; - protected static final VoxelShape WEST_SHAPE; - protected static final VoxelShape WEST_NORTH_SHAPE; - protected static final VoxelShape WEST_SOUTH_SHAPE; - protected static final VoxelShape EAST_NORTH_SHAPE; - protected static final VoxelShape EAST_SOUTH_SHAPE; - protected static final VoxelShape NORTH_WEST_SHAPE; - protected static final VoxelShape SOUTH_WEST_SHAPE; - protected static final VoxelShape NORTH_EAST_SHAPE; - protected static final VoxelShape SOUTH_EAST_SHAPE; - - static { - FACING = HorizontalDirectionalBlock.FACING; - OPEN = BlockStateProperties.OPEN; - HINGE = BlockStateProperties.DOOR_HINGE; - POWERED = BlockStateProperties.POWERED; - HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; - NORTH_SHAPE = Block.box(0.0D, 0.0D, 1.0D, 16.0D, 16.0D, 5.0D); - NORTH_EAST_SHAPE = Block.box(13.0D, 0.0D, 1.0D, 16.0D, 16.0D, 5.0D); - NORTH_WEST_SHAPE = Block.box(0.0D, 0.0D, 1.0D, 3.0D, 16.0D, 5.0D); - SOUTH_SHAPE = Block.box(0.0D, 0.0D, 11.0D, 16.0D, 16.0D, 15.0D); - SOUTH_EAST_SHAPE = Block.box(13.0D, 0.0D, 11.0D, 16.0D, 16.0D, 15.0D); - SOUTH_WEST_SHAPE = Block.box(0.0D, 0.0D, 11.0D, 3.0D, 16.0D, 15.0D); - EAST_SHAPE = Block.box(11.0D, 0.0D, 0.0D, 15.0D, 16.0D, 16.0D); - EAST_SOUTH_SHAPE = Block.box(11.0D, 0.0D, 13.0D, 15.0D, 16.0D, 16.0D); - EAST_NORTH_SHAPE = Block.box(11.0D, 0.0D, 0.0D, 15.0D, 16.0D, 3.0D); - WEST_SHAPE = Block.box(1.0D, 0.0D, 0.0D, 5.0D, 16.0D, 16.0D); - WEST_NORTH_SHAPE = Block.box(1.0D, 0.0D, 0.0D, 5.0D, 16.0D, 3.0D); - WEST_SOUTH_SHAPE = Block.box(1.0D, 0.0D, 13.0D, 5.0D, 16.0D, 16.0D); - } - - protected SlidingDoorBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(OPEN, false).setValue(HINGE, DoorHingeSide.LEFT).setValue(POWERED, false).setValue(HALF, DoubleBlockHalf.LOWER)); - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); - boolean bl = !(Boolean) state.getValue(OPEN); - boolean bl2 = state.getValue(HINGE) == DoorHingeSide.RIGHT; - return switch (direction) { - default -> bl ? WEST_SHAPE : (bl2 ? WEST_SOUTH_SHAPE : WEST_NORTH_SHAPE); - case SOUTH -> bl ? NORTH_SHAPE : (bl2 ? NORTH_WEST_SHAPE : NORTH_EAST_SHAPE); - case WEST -> bl ? EAST_SHAPE : (bl2 ? EAST_NORTH_SHAPE : EAST_SOUTH_SHAPE); - case NORTH -> bl ? SOUTH_SHAPE : (bl2 ? SOUTH_EAST_SHAPE : SOUTH_WEST_SHAPE); - }; - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape(BlockState state, Direction direction, BlockState newState, LevelAccessor world, BlockPos pos, BlockPos posFrom) { - DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); - if (direction.getAxis() == Direction.Axis.Y && doubleBlockHalf == DoubleBlockHalf.LOWER == (direction == Direction.UP)) { - return newState.is(this) && newState.getValue(HALF) != doubleBlockHalf ? state.setValue(FACING, newState.getValue(FACING)).setValue(OPEN, newState.getValue(OPEN)).setValue(HINGE, newState.getValue(HINGE)).setValue(POWERED, newState.getValue(POWERED)) : Blocks.AIR.defaultBlockState(); - } else { - return doubleBlockHalf == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, direction, newState, world, pos, posFrom); - } - } - - @Override - @SuppressWarnings("deprecation") - public boolean isPathfindable(BlockState state, BlockGetter world, BlockPos pos, PathComputationType type) { - return switch (type) { - case LAND, AIR -> state.getValue(OPEN); - case WATER -> false; - }; - } - - @Override - @Nullable - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - BlockPos blockPos = ctx.getClickedPos(); - if (blockPos.getY() < 255 && ctx.getLevel().getBlockState(blockPos.above()).canBeReplaced(ctx)) { - Level world = ctx.getLevel(); - boolean bl = world.hasNeighborSignal(blockPos) || world.hasNeighborSignal(blockPos.above()); - return this.defaultBlockState().setValue(FACING, ctx.getHorizontalDirection()).setValue(HINGE, this.getHinge(ctx)).setValue(POWERED, bl).setValue(OPEN, bl).setValue(HALF, DoubleBlockHalf.LOWER); - } else { - return null; - } - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - world.setBlock(pos.above(), state.setValue(HALF, DoubleBlockHalf.UPPER), 3); - } - - private DoorHingeSide getHinge(BlockPlaceContext ctx) { - BlockGetter blockView = ctx.getLevel(); - BlockPos blockPos = ctx.getClickedPos(); - Direction direction = ctx.getHorizontalDirection(); - BlockPos blockPos2 = blockPos.above(); - Direction direction2 = direction.getCounterClockWise(); - BlockPos blockPos3 = blockPos.relative(direction2); - BlockState blockState = blockView.getBlockState(blockPos3); - BlockPos blockPos4 = blockPos2.relative(direction2); - BlockState blockState2 = blockView.getBlockState(blockPos4); - Direction direction3 = direction.getClockWise(); - BlockPos blockPos5 = blockPos.relative(direction3); - BlockState blockState3 = blockView.getBlockState(blockPos5); - BlockPos blockPos6 = blockPos2.relative(direction3); - BlockState blockState4 = blockView.getBlockState(blockPos6); - int i = (blockState.isCollisionShapeFullBlock(blockView, blockPos3) ? -1 : 0) + (blockState2.isCollisionShapeFullBlock(blockView, blockPos4) ? -1 : 0) + (blockState3.isCollisionShapeFullBlock(blockView, blockPos5) ? 1 : 0) + (blockState4.isCollisionShapeFullBlock(blockView, blockPos6) ? 1 : 0); - boolean bl = blockState.is(this) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER; - boolean bl2 = blockState3.is(this) && blockState3.getValue(HALF) == DoubleBlockHalf.LOWER; - if ((!bl || bl2) && i <= 0) { - if ((!bl2 || bl) && i == 0) { - int j = direction.getStepX(); - int k = direction.getStepZ(); - Vec3 vec3d = ctx.getClickLocation(); - double d = vec3d.x - (double) blockPos.getX(); - double e = vec3d.z - (double) blockPos.getZ(); - return (j >= 0 || !(e < 0.5D)) && (j <= 0 || !(e > 0.5D)) && (k >= 0 || !(d > 0.5D)) && (k <= 0 || !(d < 0.5D)) ? DoorHingeSide.LEFT : DoorHingeSide.RIGHT; - } else { - return DoorHingeSide.LEFT; - } - } else { - return DoorHingeSide.RIGHT; - } - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - return InteractionResult.PASS; - } - - @Override - @SuppressWarnings("deprecation") - public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { - boolean bl = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN)); - if (block != this && bl != state.getValue(POWERED)) { - if (bl != state.getValue(OPEN)) { - this.playOpenCloseSound(world, pos, bl); - } - - world.setBlock(pos, state.setValue(POWERED, bl).setValue(OPEN, bl), 2); - } - - } - - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - BlockPos blockPos = pos.below(); - BlockState blockState = world.getBlockState(blockPos); - return state.getValue(HALF) == DoubleBlockHalf.LOWER ? blockState.isFaceSturdy(world, blockPos, Direction.UP) : blockState.is(this); - } - - private void playOpenCloseSound(Level world, BlockPos pos, boolean open) { - world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), open ? SoundEvents.PISTON_EXTEND : SoundEvents.PISTON_CONTRACT, SoundSource.MASTER, .3F, 2F); - } - - @Override - public void playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { - if (!world.isClientSide && player.isCreative()) { - onBreakInCreative(world, pos, state, player); - } - - super.playerWillDestroy(world, pos, state, player); - } - - public static void onBreakInCreative(Level world, BlockPos pos, BlockState state, Player player) { - DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); - if (doubleBlockHalf == DoubleBlockHalf.UPPER) { - BlockPos blockPos = pos.below(); - BlockState blockState = world.getBlockState(blockPos); - if (blockState.is(state.getBlock()) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER) { - BlockState blockState2 = blockState.hasProperty(BlockStateProperties.WATERLOGGED) && blockState.getValue(BlockStateProperties.WATERLOGGED) - ? Blocks.WATER.defaultBlockState() - : Blocks.AIR.defaultBlockState(); - world.setBlock(blockPos, blockState2, Block.UPDATE_ALL | Block.UPDATE_SUPPRESS_DROPS); - world.levelEvent(player, LevelEvent.PARTICLES_DESTROY_BLOCK, blockPos, Block.getId(blockState)); - } - } - - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState mirror(BlockState state, Mirror mirror) { - return mirror == Mirror.NONE ? state : state.rotate(mirror.getRotation(state.getValue(FACING))).cycle(HINGE); - } - - @Override - @ClientOnly - @SuppressWarnings("deprecation") - public long getSeed(BlockState state, BlockPos pos) { - return Mth.getSeed(pos.getX(), pos.below(state.getValue(HALF) == DoubleBlockHalf.LOWER ? 0 : 1).getY(), pos.getZ()); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF, FACING, OPEN, HINGE, POWERED); - } + public static final DirectionProperty FACING; + public static final BooleanProperty OPEN; + public static final EnumProperty HINGE; + public static final BooleanProperty POWERED; + public static final EnumProperty HALF; + protected static final VoxelShape NORTH_SHAPE; + protected static final VoxelShape SOUTH_SHAPE; + protected static final VoxelShape EAST_SHAPE; + protected static final VoxelShape WEST_SHAPE; + protected static final VoxelShape WEST_NORTH_SHAPE; + protected static final VoxelShape WEST_SOUTH_SHAPE; + protected static final VoxelShape EAST_NORTH_SHAPE; + protected static final VoxelShape EAST_SOUTH_SHAPE; + protected static final VoxelShape NORTH_WEST_SHAPE; + protected static final VoxelShape SOUTH_WEST_SHAPE; + protected static final VoxelShape NORTH_EAST_SHAPE; + protected static final VoxelShape SOUTH_EAST_SHAPE; + + static { + FACING = HorizontalDirectionalBlock.FACING; + OPEN = BlockStateProperties.OPEN; + HINGE = BlockStateProperties.DOOR_HINGE; + POWERED = BlockStateProperties.POWERED; + HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; + NORTH_SHAPE = Block.box(0.0D, 0.0D, 1.0D, 16.0D, 16.0D, 5.0D); + NORTH_EAST_SHAPE = Block.box(13.0D, 0.0D, 1.0D, 16.0D, 16.0D, 5.0D); + NORTH_WEST_SHAPE = Block.box(0.0D, 0.0D, 1.0D, 3.0D, 16.0D, 5.0D); + SOUTH_SHAPE = Block.box(0.0D, 0.0D, 11.0D, 16.0D, 16.0D, 15.0D); + SOUTH_EAST_SHAPE = Block.box(13.0D, 0.0D, 11.0D, 16.0D, 16.0D, 15.0D); + SOUTH_WEST_SHAPE = Block.box(0.0D, 0.0D, 11.0D, 3.0D, 16.0D, 15.0D); + EAST_SHAPE = Block.box(11.0D, 0.0D, 0.0D, 15.0D, 16.0D, 16.0D); + EAST_SOUTH_SHAPE = Block.box(11.0D, 0.0D, 13.0D, 15.0D, 16.0D, 16.0D); + EAST_NORTH_SHAPE = Block.box(11.0D, 0.0D, 0.0D, 15.0D, 16.0D, 3.0D); + WEST_SHAPE = Block.box(1.0D, 0.0D, 0.0D, 5.0D, 16.0D, 16.0D); + WEST_NORTH_SHAPE = Block.box(1.0D, 0.0D, 0.0D, 5.0D, 16.0D, 3.0D); + WEST_SOUTH_SHAPE = Block.box(1.0D, 0.0D, 13.0D, 5.0D, 16.0D, 16.0D); + } + + protected SlidingDoorBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(OPEN, false).setValue(HINGE, DoorHingeSide.LEFT).setValue(POWERED, false).setValue(HALF, DoubleBlockHalf.LOWER)); + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction direction = state.getValue(FACING); + boolean bl = !(Boolean) state.getValue(OPEN); + boolean bl2 = state.getValue(HINGE) == DoorHingeSide.RIGHT; + return switch (direction) { + default -> bl ? WEST_SHAPE : (bl2 ? WEST_SOUTH_SHAPE : WEST_NORTH_SHAPE); + case SOUTH -> bl ? NORTH_SHAPE : (bl2 ? NORTH_WEST_SHAPE : NORTH_EAST_SHAPE); + case WEST -> bl ? EAST_SHAPE : (bl2 ? EAST_NORTH_SHAPE : EAST_SOUTH_SHAPE); + case NORTH -> bl ? SOUTH_SHAPE : (bl2 ? SOUTH_EAST_SHAPE : SOUTH_WEST_SHAPE); + }; + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState updateShape(BlockState state, Direction direction, BlockState newState, LevelAccessor world, BlockPos pos, BlockPos posFrom) { + DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); + if (direction.getAxis() == Direction.Axis.Y && doubleBlockHalf == DoubleBlockHalf.LOWER == (direction == Direction.UP)) { + return newState.is(this) && newState.getValue(HALF) != doubleBlockHalf ? state.setValue(FACING, newState.getValue(FACING)).setValue(OPEN, newState.getValue(OPEN)).setValue(HINGE, newState.getValue(HINGE)).setValue(POWERED, newState.getValue(POWERED)) : Blocks.AIR.defaultBlockState(); + } else { + return doubleBlockHalf == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, direction, newState, world, pos, posFrom); + } + } + + @Override + @SuppressWarnings("deprecation") + public boolean isPathfindable(BlockState state, BlockGetter world, BlockPos pos, PathComputationType type) { + return switch (type) { + case LAND, AIR -> state.getValue(OPEN); + case WATER -> false; + }; + } + + @Override + @Nullable + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + BlockPos blockPos = ctx.getClickedPos(); + if (blockPos.getY() < 255 && ctx.getLevel().getBlockState(blockPos.above()).canBeReplaced(ctx)) { + Level world = ctx.getLevel(); + boolean bl = world.hasNeighborSignal(blockPos) || world.hasNeighborSignal(blockPos.above()); + return this.defaultBlockState().setValue(FACING, ctx.getHorizontalDirection()).setValue(HINGE, this.getHinge(ctx)).setValue(POWERED, bl).setValue(OPEN, bl).setValue(HALF, DoubleBlockHalf.LOWER); + } else { + return null; + } + } + + @Override + public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { + world.setBlock(pos.above(), state.setValue(HALF, DoubleBlockHalf.UPPER), 3); + } + + private DoorHingeSide getHinge(BlockPlaceContext ctx) { + BlockGetter blockView = ctx.getLevel(); + BlockPos blockPos = ctx.getClickedPos(); + Direction direction = ctx.getHorizontalDirection(); + BlockPos blockPos2 = blockPos.above(); + Direction direction2 = direction.getCounterClockWise(); + BlockPos blockPos3 = blockPos.relative(direction2); + BlockState blockState = blockView.getBlockState(blockPos3); + BlockPos blockPos4 = blockPos2.relative(direction2); + BlockState blockState2 = blockView.getBlockState(blockPos4); + Direction direction3 = direction.getClockWise(); + BlockPos blockPos5 = blockPos.relative(direction3); + BlockState blockState3 = blockView.getBlockState(blockPos5); + BlockPos blockPos6 = blockPos2.relative(direction3); + BlockState blockState4 = blockView.getBlockState(blockPos6); + int i = (blockState.isCollisionShapeFullBlock(blockView, blockPos3) ? -1 : 0) + (blockState2.isCollisionShapeFullBlock(blockView, blockPos4) ? -1 : 0) + (blockState3.isCollisionShapeFullBlock(blockView, blockPos5) ? 1 : 0) + (blockState4.isCollisionShapeFullBlock(blockView, blockPos6) ? 1 : 0); + boolean bl = blockState.is(this) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER; + boolean bl2 = blockState3.is(this) && blockState3.getValue(HALF) == DoubleBlockHalf.LOWER; + if ((!bl || bl2) && i <= 0) { + if ((!bl2 || bl) && i == 0) { + int j = direction.getStepX(); + int k = direction.getStepZ(); + Vec3 vec3d = ctx.getClickLocation(); + double d = vec3d.x - (double) blockPos.getX(); + double e = vec3d.z - (double) blockPos.getZ(); + return (j >= 0 || !(e < 0.5D)) && (j <= 0 || !(e > 0.5D)) && (k >= 0 || !(d > 0.5D)) && (k <= 0 || !(d < 0.5D)) ? DoorHingeSide.LEFT : DoorHingeSide.RIGHT; + } else { + return DoorHingeSide.LEFT; + } + } else { + return DoorHingeSide.RIGHT; + } + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + return InteractionResult.PASS; + } + + @Override + @SuppressWarnings("deprecation") + public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { + boolean bl = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN)); + if (block != this && bl != state.getValue(POWERED)) { + if (bl != state.getValue(OPEN)) { + this.playOpenCloseSound(world, pos, bl); + } + + world.setBlock(pos, state.setValue(POWERED, bl).setValue(OPEN, bl), 2); + } + + } + + @Override + @SuppressWarnings("deprecation") + public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { + BlockPos blockPos = pos.below(); + BlockState blockState = world.getBlockState(blockPos); + return state.getValue(HALF) == DoubleBlockHalf.LOWER ? blockState.isFaceSturdy(world, blockPos, Direction.UP) : blockState.is(this); + } + + private void playOpenCloseSound(Level world, BlockPos pos, boolean open) { + world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), open ? SoundEvents.PISTON_EXTEND : SoundEvents.PISTON_CONTRACT, SoundSource.MASTER, .3F, 2F); + } + + @Override + public void playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { + if (!world.isClientSide && player.isCreative()) { + onBreakInCreative(world, pos, state, player); + } + + super.playerWillDestroy(world, pos, state, player); + } + + public static void onBreakInCreative(Level world, BlockPos pos, BlockState state, Player player) { + DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); + if (doubleBlockHalf == DoubleBlockHalf.UPPER) { + BlockPos blockPos = pos.below(); + BlockState blockState = world.getBlockState(blockPos); + if (blockState.is(state.getBlock()) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER) { + BlockState blockState2 = blockState.hasProperty(BlockStateProperties.WATERLOGGED) && blockState.getValue(BlockStateProperties.WATERLOGGED) + ? Blocks.WATER.defaultBlockState() + : Blocks.AIR.defaultBlockState(); + world.setBlock(blockPos, blockState2, Block.UPDATE_ALL | Block.UPDATE_SUPPRESS_DROPS); + world.levelEvent(player, LevelEvent.PARTICLES_DESTROY_BLOCK, blockPos, Block.getId(blockState)); + } + } + + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState mirror(BlockState state, Mirror mirror) { + return mirror == Mirror.NONE ? state : state.rotate(mirror.getRotation(state.getValue(FACING))).cycle(HINGE); + } + + @Override + @ClientOnly + @SuppressWarnings("deprecation") + public long getSeed(BlockState state, BlockPos pos) { + return Mth.getSeed(pos.getX(), pos.below(state.getValue(HALF) == DoubleBlockHalf.LOWER ? 0 : 1).getY(), pos.getZ()); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(HALF, FACING, OPEN, HINGE, POWERED); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlock.java index 450f1ac8..c1fee682 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlock.java @@ -29,82 +29,82 @@ import org.quiltmc.loader.api.minecraft.MinecraftQuiltLoader; public abstract class SpecialHiddenBlock extends Block implements SimpleLoggedBlock { - public static final EnumProperty LOGGING = PortalCubedProperties.LOGGING; + public static final EnumProperty LOGGING = PortalCubedProperties.LOGGING; - public SpecialHiddenBlock(Properties settings) { - super(settings); - registerDefaultState( - getStateDefinition().any() - .setValue(LOGGING, FluidType.EMPTY) - ); - } + public SpecialHiddenBlock(Properties settings) { + super(settings); + registerDefaultState( + getStateDefinition().any() + .setValue(LOGGING, FluidType.EMPTY) + ); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(LOGGING); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(LOGGING); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public final VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return isHolding(context, asItem()) || isHolding(context, PortalCubedItems.HAMMER) - ? getVisibleOutlineShape(state, world, pos, context) : Shapes.empty(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public final VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return isHolding(context, asItem()) || isHolding(context, PortalCubedItems.HAMMER) + ? getVisibleOutlineShape(state, world, pos, context) : Shapes.empty(); + } - protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return Shapes.block(); - } + protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return Shapes.block(); + } - private static boolean isHolding(CollisionContext context, Item item) { - return context.isHoldingItem(item) || - (context instanceof EntityCollisionContext entityContext && - entityContext.getEntity() instanceof LivingEntity living && - living.isHolding(item) - ); - } + private static boolean isHolding(CollisionContext context, Item item) { + return context.isHoldingItem(item) || + (context instanceof EntityCollisionContext entityContext && + entityContext.getEntity() instanceof LivingEntity living && + living.isHolding(item) + ); + } - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { - return true; - } + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter world, BlockPos pos) { + return true; + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public RenderShape getRenderShape(BlockState state) { - return MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT - ? overrideRenderTypeClient() : RenderShape.INVISIBLE; - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public RenderShape getRenderShape(BlockState state) { + return MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT + ? overrideRenderTypeClient() : RenderShape.INVISIBLE; + } - @ClientOnly - private RenderShape overrideRenderTypeClient() { - return PortalCubedClient.hiddenBlocksVisible() ? RenderShape.MODEL : RenderShape.INVISIBLE; - } + @ClientOnly + private RenderShape overrideRenderTypeClient() { + return PortalCubedClient.hiddenBlocksVisible() ? RenderShape.MODEL : RenderShape.INVISIBLE; + } - @Override - @SuppressWarnings("deprecation") - public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { - return 1f; - } + @Override + @SuppressWarnings("deprecation") + public float getShadeBrightness(BlockState state, BlockGetter world, BlockPos pos) { + return 1f; + } - @NotNull - @SuppressWarnings("deprecation") - @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { - final Fluid fluid = state.getValue(LOGGING).fluid; - if (fluid != Fluids.EMPTY) { - world.scheduleTick(pos, fluid, fluid.getTickDelay(world)); - } + @NotNull + @SuppressWarnings("deprecation") + @Override + public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { + final Fluid fluid = state.getValue(LOGGING).fluid; + if (fluid != Fluids.EMPTY) { + world.scheduleTick(pos, fluid, fluid.getTickDelay(world)); + } - return super.updateShape(state, direction, neighborState, world, pos, neighborPos); - } + return super.updateShape(state, direction, neighborState, world, pos, neighborPos); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public FluidState getFluidState(BlockState state) { - final Fluid fluid = state.getValue(LOGGING).fluid; - return fluid instanceof FlowingFluid flowing ? flowing.getSource(false) : fluid.defaultFluidState(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public FluidState getFluidState(BlockState state) { + final Fluid fluid = state.getValue(LOGGING).fluid; + return fluid instanceof FlowingFluid flowing ? flowing.getSource(false) : fluid.defaultFluidState(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlockWithEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlockWithEntity.java index 72c74acf..cfa4995b 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlockWithEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/SpecialHiddenBlockWithEntity.java @@ -11,34 +11,34 @@ import org.jetbrains.annotations.Nullable; public abstract class SpecialHiddenBlockWithEntity extends SpecialHiddenBlock implements EntityBlock { - public SpecialHiddenBlockWithEntity(Properties settings) { - super(settings); - } + public SpecialHiddenBlockWithEntity(Properties settings) { + super(settings); + } - @Override - @SuppressWarnings("deprecation") - public boolean triggerEvent(BlockState state, Level world, BlockPos pos, int type, int data) { - super.triggerEvent(state, world, pos, type, data); - BlockEntity blockEntity = world.getBlockEntity(pos); - return blockEntity != null && blockEntity.triggerEvent(type, data); - } + @Override + @SuppressWarnings("deprecation") + public boolean triggerEvent(BlockState state, Level world, BlockPos pos, int type, int data) { + super.triggerEvent(state, world, pos, type, data); + BlockEntity blockEntity = world.getBlockEntity(pos); + return blockEntity != null && blockEntity.triggerEvent(type, data); + } - @Nullable - @Override - @SuppressWarnings("deprecation") - public MenuProvider getMenuProvider(BlockState state, Level world, BlockPos pos) { - BlockEntity blockEntity = world.getBlockEntity(pos); - return blockEntity instanceof MenuProvider ? (MenuProvider)blockEntity : null; - } + @Nullable + @Override + @SuppressWarnings("deprecation") + public MenuProvider getMenuProvider(BlockState state, Level world, BlockPos pos) { + BlockEntity blockEntity = world.getBlockEntity(pos); + return blockEntity instanceof MenuProvider ? (MenuProvider)blockEntity : null; + } - /** - * {@return the ticker if the given type and expected type are the same, or {@code null} if they are different} - */ - @Nullable - @SuppressWarnings("unchecked") - protected static BlockEntityTicker checkType( - BlockEntityType givenType, BlockEntityType expectedType, BlockEntityTicker ticker - ) { - return expectedType == givenType ? (BlockEntityTicker)ticker : null; - } + /** + * {@return the ticker if the given type and expected type are the same, or {@code null} if they are different} + */ + @Nullable + @SuppressWarnings("unchecked") + protected static BlockEntityTicker checkType( + BlockEntityType givenType, BlockEntityType expectedType, BlockEntityTicker ticker + ) { + return expectedType == givenType ? (BlockEntityTicker)ticker : null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/TallButton.java b/src/main/java/com/fusionflux/portalcubed/blocks/TallButton.java index 62425398..f00b3dc6 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/TallButton.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/TallButton.java @@ -4,12 +4,12 @@ import net.minecraft.sounds.SoundEvent; public class TallButton extends TallButtonVariant { - public TallButton(Properties settings) { - super(settings); - } + public TallButton(Properties settings) { + super(settings); + } - @Override - public SoundEvent getClickSound(boolean powered) { - return powered ? PortalCubedSounds.PEDESTAL_BUTTON_PRESS_EVENT : PortalCubedSounds.PEDESTAL_BUTTON_RELEASE_EVENT; - } + @Override + public SoundEvent getClickSound(boolean powered) { + return powered ? PortalCubedSounds.PEDESTAL_BUTTON_PRESS_EVENT : PortalCubedSounds.PEDESTAL_BUTTON_RELEASE_EVENT; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/TallButtonVariant.java b/src/main/java/com/fusionflux/portalcubed/blocks/TallButtonVariant.java index 3540fad9..6fc99587 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/TallButtonVariant.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/TallButtonVariant.java @@ -31,166 +31,166 @@ import java.util.Map; public abstract class TallButtonVariant extends FaceAttachedHorizontalDirectionalBlock { - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - public static final BooleanProperty OFFSET = BooleanProperty.create("offset"); - - private static final VoxelShape[] CEILING_X_SHAPE = createShapePair(5.5, -4, 5.5, 10.5, 16, 10.5); - private static final VoxelShape[] CEILING_Z_SHAPE = createShapePair(5.5, -4, 5.5, 10.5, 16, 10.5); - private static final VoxelShape[] FLOOR_X_SHAPE = createShapePair(5.5, 0, 5.5, 10.5, 20, 10.5); - private static final VoxelShape[] FLOOR_Z_SHAPE = createShapePair(5.5, 0, 5.5, 10.5, 20, 10.5); - private static final VoxelShape[] NORTH_SHAPE = createShapePair(5.5, 5.5, -4, 10.5, 10.5, 16); - private static final VoxelShape[] SOUTH_SHAPE = createShapePair(5.5, 5.5, 0, 10.5, 10.5, 20); - private static final VoxelShape[] WEST_SHAPE = createShapePair(-4, 5.5, 5.5, 16, 10.5, 10.5); - private static final VoxelShape[] EAST_SHAPE = createShapePair(0, 5.5, 5.5, 20, 10.5, 10.5); - - protected static final Map SHAPE_CACHE = new HashMap<>(); - - protected TallButtonVariant(Properties settings) { - super(settings); - registerDefaultState( - stateDefinition.any() - .setValue(FACING, Direction.NORTH) - .setValue(POWERED, false) - .setValue(FACE, AttachFace.WALL) - .setValue(OFFSET, false) - ); - } - - private int getPressTicks() { - return 30; - } - - private static VoxelShape[] createShapePair(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - return new VoxelShape[] { - box(minX, minY, minZ, maxX, maxY, maxZ), - box( - maybeShrink(minX), maybeShrink(minY), maybeShrink(minZ), - maybeShrink(maxX), maybeShrink(maxY), maybeShrink(maxZ) - ) - }; - } - - private static double maybeShrink(double v) { - return v == 20 ? 18 : v == -4 ? -2 : v; - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - final VoxelShape[] baseShape = getBaseShape(state); - VoxelShape shape = SHAPE_CACHE.get(state); - if (shape == null) { - if (state.getValue(OFFSET)) { - final Vec3 offsetDir = Vec3.atLowerCornerOf(getOffsetDir(state).getNormal()).scale(0.25); - shape = baseShape[1].move(offsetDir.x, offsetDir.y, offsetDir.z); - } else { - shape = baseShape[0]; - } - SHAPE_CACHE.put(state, shape); - } - return shape; - } - - private VoxelShape[] getBaseShape(BlockState state) { - Direction direction = state.getValue(FACING); - return switch (state.getValue(FACE)) { - case FLOOR -> direction.getAxis() == Direction.Axis.X ? FLOOR_X_SHAPE : FLOOR_Z_SHAPE; - case WALL -> switch (direction) { - case EAST -> EAST_SHAPE; - case WEST -> WEST_SHAPE; - case SOUTH -> SOUTH_SHAPE; - case NORTH -> NORTH_SHAPE; - default -> throw new AssertionError(); - }; - case CEILING -> direction.getAxis() == Direction.Axis.X ? CEILING_X_SHAPE : CEILING_Z_SHAPE; - }; - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { - world.setBlockAndUpdate(pos, state.cycle(OFFSET)); - return InteractionResult.sidedSuccess(world.isClientSide); - } - if (state.getValue(POWERED)) { - return InteractionResult.PASS; - } else { - this.powerOn(state, world, pos); - this.playClickSound(player, world, pos, true); - return InteractionResult.sidedSuccess(world.isClientSide); - } - } - - public void powerOn(BlockState state, Level world, BlockPos pos) { - world.setBlock(pos, state.setValue(POWERED, true), 3); - this.updateNeighbors(state, world, pos); - world.scheduleTick(pos, this, this.getPressTicks()); - } - - protected void playClickSound(@Nullable Player player, LevelAccessor world, BlockPos pos, boolean powered) { - world.playSound(powered ? player : null, pos, this.getClickSound(powered), SoundSource.BLOCKS, 0.8f, 1f); - } - - public abstract SoundEvent getClickSound(boolean powered); - - @Override - @SuppressWarnings("deprecation") - public void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean moved) { - if (!moved && !state.is(newState.getBlock())) { - if (state.getValue(POWERED)) { - this.updateNeighbors(state, world, pos); - } - - super.onRemove(state, world, pos, newState, false); - } - } - - @Override - @SuppressWarnings("deprecation") - public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - return state.getValue(POWERED) ? 15 : 0; - } - - @Override - @SuppressWarnings("deprecation") - public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { - return state.getValue(POWERED) && getConnectedDirection(state) == direction ? 15 : 0; - } - - @Override - @SuppressWarnings("deprecation") - public boolean isSignalSource(BlockState state) { - return true; - } - - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED)) { - world.setBlock(pos, state.setValue(POWERED, false), 3); - this.updateNeighbors(state, world, pos); - this.playClickSound(null, world, pos, false); - } - } - - private void updateNeighbors(BlockState state, Level world, BlockPos pos) { - world.updateNeighborsAt(pos, this); - world.updateNeighborsAt(pos.relative(getConnectedDirection(state).getOpposite()), this); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED, FACE, OFFSET); - } - - public static Direction getOffsetDir(BlockState state) { - if (state.getValue(FACE) == AttachFace.WALL) { - return Direction.UP; - } - return state.getValue(FACING); - } + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final BooleanProperty OFFSET = BooleanProperty.create("offset"); + + private static final VoxelShape[] CEILING_X_SHAPE = createShapePair(5.5, -4, 5.5, 10.5, 16, 10.5); + private static final VoxelShape[] CEILING_Z_SHAPE = createShapePair(5.5, -4, 5.5, 10.5, 16, 10.5); + private static final VoxelShape[] FLOOR_X_SHAPE = createShapePair(5.5, 0, 5.5, 10.5, 20, 10.5); + private static final VoxelShape[] FLOOR_Z_SHAPE = createShapePair(5.5, 0, 5.5, 10.5, 20, 10.5); + private static final VoxelShape[] NORTH_SHAPE = createShapePair(5.5, 5.5, -4, 10.5, 10.5, 16); + private static final VoxelShape[] SOUTH_SHAPE = createShapePair(5.5, 5.5, 0, 10.5, 10.5, 20); + private static final VoxelShape[] WEST_SHAPE = createShapePair(-4, 5.5, 5.5, 16, 10.5, 10.5); + private static final VoxelShape[] EAST_SHAPE = createShapePair(0, 5.5, 5.5, 20, 10.5, 10.5); + + protected static final Map SHAPE_CACHE = new HashMap<>(); + + protected TallButtonVariant(Properties settings) { + super(settings); + registerDefaultState( + stateDefinition.any() + .setValue(FACING, Direction.NORTH) + .setValue(POWERED, false) + .setValue(FACE, AttachFace.WALL) + .setValue(OFFSET, false) + ); + } + + private int getPressTicks() { + return 30; + } + + private static VoxelShape[] createShapePair(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + return new VoxelShape[] { + box(minX, minY, minZ, maxX, maxY, maxZ), + box( + maybeShrink(minX), maybeShrink(minY), maybeShrink(minZ), + maybeShrink(maxX), maybeShrink(maxY), maybeShrink(maxZ) + ) + }; + } + + private static double maybeShrink(double v) { + return v == 20 ? 18 : v == -4 ? -2 : v; + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + final VoxelShape[] baseShape = getBaseShape(state); + VoxelShape shape = SHAPE_CACHE.get(state); + if (shape == null) { + if (state.getValue(OFFSET)) { + final Vec3 offsetDir = Vec3.atLowerCornerOf(getOffsetDir(state).getNormal()).scale(0.25); + shape = baseShape[1].move(offsetDir.x, offsetDir.y, offsetDir.z); + } else { + shape = baseShape[0]; + } + SHAPE_CACHE.put(state, shape); + } + return shape; + } + + private VoxelShape[] getBaseShape(BlockState state) { + Direction direction = state.getValue(FACING); + return switch (state.getValue(FACE)) { + case FLOOR -> direction.getAxis() == Direction.Axis.X ? FLOOR_X_SHAPE : FLOOR_Z_SHAPE; + case WALL -> switch (direction) { + case EAST -> EAST_SHAPE; + case WEST -> WEST_SHAPE; + case SOUTH -> SOUTH_SHAPE; + case NORTH -> NORTH_SHAPE; + default -> throw new AssertionError(); + }; + case CEILING -> direction.getAxis() == Direction.Axis.X ? CEILING_X_SHAPE : CEILING_Z_SHAPE; + }; + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { + world.setBlockAndUpdate(pos, state.cycle(OFFSET)); + return InteractionResult.sidedSuccess(world.isClientSide); + } + if (state.getValue(POWERED)) { + return InteractionResult.PASS; + } else { + this.powerOn(state, world, pos); + this.playClickSound(player, world, pos, true); + return InteractionResult.sidedSuccess(world.isClientSide); + } + } + + public void powerOn(BlockState state, Level world, BlockPos pos) { + world.setBlock(pos, state.setValue(POWERED, true), 3); + this.updateNeighbors(state, world, pos); + world.scheduleTick(pos, this, this.getPressTicks()); + } + + protected void playClickSound(@Nullable Player player, LevelAccessor world, BlockPos pos, boolean powered) { + world.playSound(powered ? player : null, pos, this.getClickSound(powered), SoundSource.BLOCKS, 0.8f, 1f); + } + + public abstract SoundEvent getClickSound(boolean powered); + + @Override + @SuppressWarnings("deprecation") + public void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean moved) { + if (!moved && !state.is(newState.getBlock())) { + if (state.getValue(POWERED)) { + this.updateNeighbors(state, world, pos); + } + + super.onRemove(state, world, pos, newState, false); + } + } + + @Override + @SuppressWarnings("deprecation") + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + return state.getValue(POWERED) ? 15 : 0; + } + + @Override + @SuppressWarnings("deprecation") + public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { + return state.getValue(POWERED) && getConnectedDirection(state) == direction ? 15 : 0; + } + + @Override + @SuppressWarnings("deprecation") + public boolean isSignalSource(BlockState state) { + return true; + } + + @Override + @SuppressWarnings("deprecation") + public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { + if (state.getValue(POWERED)) { + world.setBlock(pos, state.setValue(POWERED, false), 3); + this.updateNeighbors(state, world, pos); + this.playClickSound(null, world, pos, false); + } + } + + private void updateNeighbors(BlockState state, Level world, BlockPos pos) { + world.updateNeighborsAt(pos, this); + world.updateNeighborsAt(pos.relative(getConnectedDirection(state).getOpposite()), this); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, POWERED, FACE, OFFSET); + } + + public static Direction getOffsetDir(BlockState state) { + if (state.getValue(FACE) == AttachFace.WALL) { + return Direction.UP; + } + return state.getValue(FACING); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/VelocityHelperBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/VelocityHelperBlock.java index 7147acc0..f930752e 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/VelocityHelperBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/VelocityHelperBlock.java @@ -32,89 +32,89 @@ import java.util.function.Consumer; public class VelocityHelperBlock extends SpecialHiddenBlockWithEntity implements BlockCollisionTrigger { - public static final int CONFIG_DEST = 0; - public static final int CONFIG_OTHER = 1; + public static final int CONFIG_DEST = 0; + public static final int CONFIG_OTHER = 1; - public static final VoxelShape SHAPE = box(4, 4, 4, 12, 12, 12); + public static final VoxelShape SHAPE = box(4, 4, 4, 12, 12, 12); - public VelocityHelperBlock(Properties settings) { - super(settings); - } + public VelocityHelperBlock(Properties settings) { + super(settings); + } - @Nullable - @Override - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new VelocityHelperBlockEntity(pos, state); - } + @Nullable + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new VelocityHelperBlockEntity(pos, state); + } - @Override - protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPE; - } + @Override + protected VoxelShape getVisibleOutlineShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPE; + } - @Override - public VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return Shapes.block(); - } + @Override + public VoxelShape getTriggerShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return Shapes.block(); + } - @Override - public void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { - if (entity instanceof EntityExt ext) { - world.getBlockEntity(pos, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY) - .ifPresent(ext::collidedWithVelocityHelper); - } - } + @Override + public void onEntityEnter(BlockState state, Level world, BlockPos pos, Entity entity) { + if (entity instanceof EntityExt ext) { + world.getBlockEntity(pos, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY) + .ifPresent(ext::collidedWithVelocityHelper); + } + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.isCreative()) return InteractionResult.PASS; - final ItemStack stack = player.getItemInHand(hand); - if (stack.is(PortalCubedItems.WRENCHES)) { - final VelocityHelperBlockEntity entity = world.getBlockEntity(pos, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).orElse(null); - if (entity != null) { - if (!world.isClientSide) { - return InteractionResult.PASS; - } - if (PortalCubedClient.velocityHelperDragStart == null) { - if (entity.getDestination() == null) { - PortalCubedClient.velocityHelperDragStart = pos; - } else { - sendLinkPacket(pos, null); - } - } else if (PortalCubedClient.velocityHelperDragStart.equals(pos)) { - PortalCubedClient.velocityHelperDragStart = null; - } else { - sendLinkPacket(PortalCubedClient.velocityHelperDragStart, pos); - PortalCubedClient.velocityHelperDragStart = null; - } - return InteractionResult.SUCCESS; - } - } else { - if (!world.isClientSide) { - final MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); + @NotNull + @Override + @SuppressWarnings("deprecation") + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.isCreative()) return InteractionResult.PASS; + final ItemStack stack = player.getItemInHand(hand); + if (stack.is(PortalCubedItems.WRENCHES)) { + final VelocityHelperBlockEntity entity = world.getBlockEntity(pos, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).orElse(null); + if (entity != null) { + if (!world.isClientSide) { + return InteractionResult.PASS; + } + if (PortalCubedClient.velocityHelperDragStart == null) { + if (entity.getDestination() == null) { + PortalCubedClient.velocityHelperDragStart = pos; + } else { + sendLinkPacket(pos, null); + } + } else if (PortalCubedClient.velocityHelperDragStart.equals(pos)) { + PortalCubedClient.velocityHelperDragStart = null; + } else { + sendLinkPacket(PortalCubedClient.velocityHelperDragStart, pos); + PortalCubedClient.velocityHelperDragStart = null; + } + return InteractionResult.SUCCESS; + } + } else { + if (!world.isClientSide) { + final MenuProvider screenHandlerFactory = state.getMenuProvider(world, pos); - if (screenHandlerFactory != null) { - player.openMenu(screenHandlerFactory); - } - } - return InteractionResult.SUCCESS; - } - return InteractionResult.PASS; - } + if (screenHandlerFactory != null) { + player.openMenu(screenHandlerFactory); + } + } + return InteractionResult.SUCCESS; + } + return InteractionResult.PASS; + } - @ClientOnly - private static void sendLinkPacket(BlockPos origin, @Nullable BlockPos dest) { - sendConfigurePacket(origin, CONFIG_DEST, buf -> buf.writeOptional(Optional.ofNullable(dest), FriendlyByteBuf::writeBlockPos)); - } + @ClientOnly + private static void sendLinkPacket(BlockPos origin, @Nullable BlockPos dest) { + sendConfigurePacket(origin, CONFIG_DEST, buf -> buf.writeOptional(Optional.ofNullable(dest), FriendlyByteBuf::writeBlockPos)); + } - @ClientOnly - public static void sendConfigurePacket(BlockPos origin, int mode, Consumer writer) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBlockPos(origin); - buf.writeByte(mode); - writer.accept(buf); - ClientPlayNetworking.send(PortalCubedServerPackets.VELOCITY_HELPER_CONFIGURE, buf); - } + @ClientOnly + public static void sendConfigurePacket(BlockPos origin, int mode, Consumer writer) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBlockPos(origin); + buf.writeByte(mode); + writer.accept(buf); + ClientPlayNetworking.send(PortalCubedServerPackets.VELOCITY_HELPER_CONFIGURE, buf); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/AutoPortalBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/AutoPortalBlockEntity.java index fda7f7ae..0ab8fda8 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/AutoPortalBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/AutoPortalBlockEntity.java @@ -9,31 +9,31 @@ import net.minecraft.world.level.block.state.BlockState; public class AutoPortalBlockEntity extends BlockEntity { - private int color = 0x1d86db; + private int color = 0x1d86db; - public AutoPortalBlockEntity(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { - super(blockEntityType, blockPos, blockState); - } + public AutoPortalBlockEntity(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { + super(blockEntityType, blockPos, blockState); + } - public AutoPortalBlockEntity(BlockPos blockPos, BlockState blockState) { - this(PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY, blockPos, blockState); - } + public AutoPortalBlockEntity(BlockPos blockPos, BlockState blockState) { + this(PortalCubedBlocks.AUTO_PORTAL_BLOCK_ENTITY, blockPos, blockState); + } - public int getColor() { - return color; - } + public int getColor() { + return color; + } - public void setColor(int color) { - this.color = color; - } + public void setColor(int color) { + this.color = color; + } - @Override - public void load(CompoundTag nbt) { - color = nbt.contains("Color", Tag.TAG_INT) ? nbt.getInt("Color") : 0x1d86db; - } + @Override + public void load(CompoundTag nbt) { + color = nbt.contains("Color", Tag.TAG_INT) ? nbt.getInt("Color") : 0x1d86db; + } - @Override - protected void saveAdditional(CompoundTag nbt) { - nbt.putInt("Color", color); - } + @Override + protected void saveAdditional(CompoundTag nbt) { + nbt.putInt("Color", color); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/BetaFaithPlateBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/BetaFaithPlateBlockEntity.java index 6ac30773..ed23f88c 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/BetaFaithPlateBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/BetaFaithPlateBlockEntity.java @@ -5,7 +5,7 @@ import net.minecraft.world.level.block.state.BlockState; public class BetaFaithPlateBlockEntity extends FaithPlateBlockEntity { - public BetaFaithPlateBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.BETA_FAITH_PLATE_BLOCK_ENTITY, pos, state); - } + public BetaFaithPlateBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.BETA_FAITH_PLATE_BLOCK_ENTITY, pos, state); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/CatapultBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/CatapultBlockEntity.java index 1d21b8e0..dcb6872c 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/CatapultBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/CatapultBlockEntity.java @@ -26,118 +26,118 @@ import org.jetbrains.annotations.Nullable; public class CatapultBlockEntity extends BlockEntity implements ExtendedScreenHandlerFactory, NbtSyncable { - private double destX; - private double destY; - private double destZ; - private double angle = 45; - - public CatapultBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { - super(type, pos, state); - destX = pos.getX() + 0.5; - destY = pos.getY(); - destZ = pos.getZ() + 0.5; - } - - public CatapultBlockEntity(BlockPos pos, BlockState state) { - this(PortalCubedBlocks.CATAPULT_BLOCK_ENTITY, pos, state); - } - - @Override - public void load(CompoundTag nbt) { - destX = nbt.getDouble("DestX"); - destY = nbt.getDouble("DestY"); - destZ = nbt.getDouble("DestZ"); - angle = nbt.contains("Angle") ? nbt.getDouble("Angle") : 45; - } - - @Override - protected void saveAdditional(CompoundTag nbt) { - nbt.putDouble("DestX", destX); - nbt.putDouble("DestY", destY); - nbt.putDouble("DestZ", destZ); - nbt.putDouble("Angle", angle); - } - - @Override - public void syncNbt(CompoundTag nbt, ServerPlayer player) throws CommandRuntimeException { - destX = getDouble(nbt, player, "DestX", destX); - destY = getDouble(nbt, player, "DestY", destY); - destZ = getDouble(nbt, player, "DestZ", destZ); - angle = getDouble(nbt, player, "Angle", angle); - updateListeners(); - } - - private static double getDouble(CompoundTag nbt, ServerPlayer player, String key, double defaultValue) throws CommandRuntimeException { - if (!nbt.contains(key, Tag.TAG_DOUBLE)) { - return defaultValue; - } - final double value = nbt.getDouble(key); - if (!Double.isFinite(value)) { - throw new CommandRuntimeException(Component.translatable("portalcubed.catapult.invalidDouble", value)); - } - return value; - } - - public void updateListeners() { - setChanged(); - assert level != null; - level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); - } - - @NotNull - @Override - public CompoundTag getUpdateTag() { - return saveWithoutMetadata(); - } - - @Nullable - @Override - public Packet getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this); - } - - @NotNull - @Override - public Component getDisplayName() { - return Component.translatable(getBlockState().getBlock().getDescriptionId()); - } - - @Nullable - @Override - public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { - return null; // TODO: Implement GUI - } - - @Override - public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { - buf.writeBlockPos(worldPosition); - } - - private double getRelX(double startX) { - return destX - startX - 0.5; - } - - private double getRelZ(double startZ) { - return destZ - startZ - 0.5; - } - - public double getRelH(double startX, double startZ) { - return Math.sqrt(Mth.square(getRelX(startX)) + Mth.square(getRelZ(startZ))); - } - - public double getRelY(double startY) { - return destY - startY; - } - - public double getAngle() { - return angle; - } - - public Vec3 getLaunchDir(double startX, double startZ) { - final double a = Math.toRadians(angle); - return new Vec3(getRelX(startX), 0, getRelZ(startZ)) - .normalize() - .scale(Math.cos(a)) - .add(0, Math.sin(a), 0); - } + private double destX; + private double destY; + private double destZ; + private double angle = 45; + + public CatapultBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + destX = pos.getX() + 0.5; + destY = pos.getY(); + destZ = pos.getZ() + 0.5; + } + + public CatapultBlockEntity(BlockPos pos, BlockState state) { + this(PortalCubedBlocks.CATAPULT_BLOCK_ENTITY, pos, state); + } + + @Override + public void load(CompoundTag nbt) { + destX = nbt.getDouble("DestX"); + destY = nbt.getDouble("DestY"); + destZ = nbt.getDouble("DestZ"); + angle = nbt.contains("Angle") ? nbt.getDouble("Angle") : 45; + } + + @Override + protected void saveAdditional(CompoundTag nbt) { + nbt.putDouble("DestX", destX); + nbt.putDouble("DestY", destY); + nbt.putDouble("DestZ", destZ); + nbt.putDouble("Angle", angle); + } + + @Override + public void syncNbt(CompoundTag nbt, ServerPlayer player) throws CommandRuntimeException { + destX = getDouble(nbt, player, "DestX", destX); + destY = getDouble(nbt, player, "DestY", destY); + destZ = getDouble(nbt, player, "DestZ", destZ); + angle = getDouble(nbt, player, "Angle", angle); + updateListeners(); + } + + private static double getDouble(CompoundTag nbt, ServerPlayer player, String key, double defaultValue) throws CommandRuntimeException { + if (!nbt.contains(key, Tag.TAG_DOUBLE)) { + return defaultValue; + } + final double value = nbt.getDouble(key); + if (!Double.isFinite(value)) { + throw new CommandRuntimeException(Component.translatable("portalcubed.catapult.invalidDouble", value)); + } + return value; + } + + public void updateListeners() { + setChanged(); + assert level != null; + level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); + } + + @NotNull + @Override + public CompoundTag getUpdateTag() { + return saveWithoutMetadata(); + } + + @Nullable + @Override + public Packet getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } + + @NotNull + @Override + public Component getDisplayName() { + return Component.translatable(getBlockState().getBlock().getDescriptionId()); + } + + @Nullable + @Override + public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { + return null; // TODO: Implement GUI + } + + @Override + public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { + buf.writeBlockPos(worldPosition); + } + + private double getRelX(double startX) { + return destX - startX - 0.5; + } + + private double getRelZ(double startZ) { + return destZ - startZ - 0.5; + } + + public double getRelH(double startX, double startZ) { + return Math.sqrt(Mth.square(getRelX(startX)) + Mth.square(getRelZ(startZ))); + } + + public double getRelY(double startY) { + return destY - startY; + } + + public double getAngle() { + return angle; + } + + public Vec3 getLaunchDir(double startX, double startZ) { + final double a = Math.toRadians(angle); + return new Vec3(getRelX(startX), 0, getRelZ(startZ)) + .normalize() + .scale(Math.cos(a)) + .add(0, Math.sin(a), 0); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/EntityLikeBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/EntityLikeBlockEntity.java index cf8c3dc2..2c2ae0d3 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/EntityLikeBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/EntityLikeBlockEntity.java @@ -9,54 +9,54 @@ import net.minecraft.world.level.block.state.BlockState; public abstract class EntityLikeBlockEntity extends BlockEntity { - private int age; - public float prevYaw, prevPitch; - public float yaw, pitch; - - public EntityLikeBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { - super(type, pos, state); - } - - @Override - protected void saveAdditional(CompoundTag nbt) { - nbt.putFloat("Yaw", yaw); - nbt.putFloat("Pitch", pitch); - } - - @Override - public void load(CompoundTag nbt) { - yaw = nbt.getFloat("Yaw"); - pitch = nbt.getFloat("Pitch"); - } - - public void tick(Level world, BlockPos pos, BlockState state) { - age++; - prevYaw = yaw; - prevPitch = pitch; - } - - public int getAge() { - return age; - } - - public float getYaw() { - return yaw; - } - - public void setYaw(float yaw) { - this.yaw = Mth.wrapDegrees(yaw); - } - - public float getPitch() { - return pitch; - } - - public void setPitch(float pitch) { - this.pitch = Mth.wrapDegrees(pitch); - } - - @Override - public CompoundTag getUpdateTag() { - return saveWithoutMetadata(); - } + private int age; + public float prevYaw, prevPitch; + public float yaw, pitch; + + public EntityLikeBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + } + + @Override + protected void saveAdditional(CompoundTag nbt) { + nbt.putFloat("Yaw", yaw); + nbt.putFloat("Pitch", pitch); + } + + @Override + public void load(CompoundTag nbt) { + yaw = nbt.getFloat("Yaw"); + pitch = nbt.getFloat("Pitch"); + } + + public void tick(Level world, BlockPos pos, BlockState state) { + age++; + prevYaw = yaw; + prevPitch = pitch; + } + + public int getAge() { + return age; + } + + public float getYaw() { + return yaw; + } + + public void setYaw(float yaw) { + this.yaw = Mth.wrapDegrees(yaw); + } + + public float getPitch() { + return pitch; + } + + public void setPitch(float pitch) { + this.pitch = Mth.wrapDegrees(pitch); + } + + @Override + public CompoundTag getUpdateTag() { + return saveWithoutMetadata(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/ExcursionFunnelEmitterBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/ExcursionFunnelEmitterBlockEntity.java index d50692b2..f92a9dbc 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/ExcursionFunnelEmitterBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/ExcursionFunnelEmitterBlockEntity.java @@ -17,80 +17,80 @@ import net.minecraft.world.level.block.state.BlockState; public class ExcursionFunnelEmitterBlockEntity extends BlockEntity { - private ToggleMode toggleMode = ToggleMode.FORWARD; - private UUID funnelEntityId = null; - @Nullable - private Float maxLength = null; - - public ExcursionFunnelEmitterBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER_ENTITY, pos, state); - } - - public ToggleMode getToggleMode() { - return toggleMode; - } - - public void setToggleMode(ToggleMode mode) { - this.toggleMode = mode; - setChanged(); - } - - @Nullable - public UUID getFunnelEntityId() { - return funnelEntityId; - } - - public void setFunnelEntityId(UUID funnelEntityId) { - this.funnelEntityId = funnelEntityId; - setChanged(); - } - - public float getMaxLength() { - return maxLength == null ? EmittedEntity.DEFAULT_MAX_LENGTH : maxLength; - } - - @Override - public void saveAdditional(@NotNull CompoundTag tag) { - tag.putString("toggleMode", toggleMode.getSerializedName()); - if (funnelEntityId != null) - tag.putUUID("funnelEntityId", funnelEntityId); - if (maxLength != null) - tag.putFloat("maxLength", maxLength); - } - - @Override - public void load(@NotNull CompoundTag tag) { - this.toggleMode = NbtHelper.readEnum(tag, "toggleMode", toggleMode); - if (tag.contains("funnelEntityId", Tag.TAG_INT_ARRAY)) - this.funnelEntityId = tag.getUUID("funnelEntityId"); - if (tag.contains("maxLength", Tag.TAG_FLOAT)) - this.maxLength = tag.getFloat("maxLength"); - } - - public enum ToggleMode implements StringRepresentable { - FORWARD(Mode.FORWARD_OFF, Mode.FORWARD_ON), - REVERSE(Mode.REVERSED_OFF, Mode.REVERSED_ON), - SWITCH(Mode.FORWARD_ON, Mode.REVERSED_ON); - - public final Mode off, on; - - ToggleMode(Mode off, Mode on) { - this.off = off; - this.on = on; - } - - public ToggleMode next() { - return switch (this) { - case FORWARD -> REVERSE; - case REVERSE -> SWITCH; - case SWITCH -> FORWARD; - }; - } - - @Override - @NotNull - public String getSerializedName() { - return name(); - } - } + private ToggleMode toggleMode = ToggleMode.FORWARD; + private UUID funnelEntityId = null; + @Nullable + private Float maxLength = null; + + public ExcursionFunnelEmitterBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER_ENTITY, pos, state); + } + + public ToggleMode getToggleMode() { + return toggleMode; + } + + public void setToggleMode(ToggleMode mode) { + this.toggleMode = mode; + setChanged(); + } + + @Nullable + public UUID getFunnelEntityId() { + return funnelEntityId; + } + + public void setFunnelEntityId(UUID funnelEntityId) { + this.funnelEntityId = funnelEntityId; + setChanged(); + } + + public float getMaxLength() { + return maxLength == null ? EmittedEntity.DEFAULT_MAX_LENGTH : maxLength; + } + + @Override + public void saveAdditional(@NotNull CompoundTag tag) { + tag.putString("toggleMode", toggleMode.getSerializedName()); + if (funnelEntityId != null) + tag.putUUID("funnelEntityId", funnelEntityId); + if (maxLength != null) + tag.putFloat("maxLength", maxLength); + } + + @Override + public void load(@NotNull CompoundTag tag) { + this.toggleMode = NbtHelper.readEnum(tag, "toggleMode", toggleMode); + if (tag.contains("funnelEntityId", Tag.TAG_INT_ARRAY)) + this.funnelEntityId = tag.getUUID("funnelEntityId"); + if (tag.contains("maxLength", Tag.TAG_FLOAT)) + this.maxLength = tag.getFloat("maxLength"); + } + + public enum ToggleMode implements StringRepresentable { + FORWARD(Mode.FORWARD_OFF, Mode.FORWARD_ON), + REVERSE(Mode.REVERSED_OFF, Mode.REVERSED_ON), + SWITCH(Mode.FORWARD_ON, Mode.REVERSED_ON); + + public final Mode off, on; + + ToggleMode(Mode off, Mode on) { + this.off = off; + this.on = on; + } + + public ToggleMode next() { + return switch (this) { + case FORWARD -> REVERSE; + case REVERSE -> SWITCH; + case SWITCH -> FORWARD; + }; + } + + @Override + @NotNull + public String getSerializedName() { + return name(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FaithPlateBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FaithPlateBlockEntity.java index 9adf5f04..0996bfa0 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FaithPlateBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FaithPlateBlockEntity.java @@ -39,167 +39,167 @@ import java.util.List; public class FaithPlateBlockEntity extends EntityLikeBlockEntity implements ExtendedScreenHandlerFactory, ServerAnimatable { - private double velX = 0; - private double velY = 0; - private double velZ = 0; - - private double timer = 0; - public final AnimationState flingState = new AnimationState(); - - public FaithPlateBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { - super(type, pos, state); - } - - public FaithPlateBlockEntity(BlockPos pos, BlockState state) { - this(PortalCubedBlocks.FAITH_PLATE_BLOCK_ENTITY, pos, state); - } - - @Override - public void tick(Level world, BlockPos pos, BlockState state) { - super.tick(world, pos, state); - if (state.getValue(FaithPlateBlock.FACING).getAxis().isVertical()) { - final boolean isFlipped = state.getValue(FaithPlateBlock.FACING) == Direction.DOWN; - setYaw(directionToAngle(state.getValue(FaithPlateBlock.HORIFACING)) * (isFlipped ? -1 : 1)); - setPitch(isFlipped ? 180f : 0f); - } else { - setYaw(directionToAngle(state.getValue(FaithPlateBlock.FACING)) + 180f); - setPitch(90f); - } - - AABB checkBox = new AABB(pos).move( - state.getValue(FaithPlateBlock.FACING).getStepX(), - state.getValue(FaithPlateBlock.FACING).getStepY(), - state.getValue(FaithPlateBlock.FACING).getStepZ() - ); - - List list = world.getEntitiesOfClass(Entity.class, checkBox); - - final boolean launch = new Vec3(velX, velY, velZ).lengthSqr() > 1e-7; - for (Entity liver : list) { - if (timer <= 0) { - if (liver instanceof CorePhysicsEntity physEn && physEn.getHolderUUID().isPresent()) { - continue; - } - if (launch) { - final Vec3 force = new Vec3(velX, velY, velZ); - RayonIntegration.INSTANCE.setVelocity(liver, force); - if (liver instanceof ServerPlayer player) { - PortalCubedTriggers.FLING.trigger(player, worldPosition, force); - } - } - timer = 5; - if (!world.isClientSide) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBlockPos(pos); - buf.writeUtf("fling"); - //noinspection DataFlowIssue - world.getServer() - .getPlayerList() - .broadcast( - null, - pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, - 96, world.dimension(), - ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.SERVER_ANIMATE, buf) - ); - } - world.playSound( - null, - pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, - PortalCubedSounds.CATAPULT_LAUNCH_EVENT, SoundSource.BLOCKS, - .2f, 1f - ); - } - } - if (timer > 0) { - timer--; - } - } - - private static float directionToAngle(Direction dir) { - return switch (dir) { - case EAST -> 90f; - case SOUTH -> 180f; - case WEST -> -90f; - case NORTH -> 0f; - default -> throw new AssertionError("FaithPlateBlockEntity.directionToAngle called with non-horizontal direction " + dir); - }; - } - - public double getVelX() { - return velX; - } - - public void setVelX(double velX) { - this.velX = velX; - } - - public double getVelY() { - return velY; - } - - public void setVelY(double velY) { - this.velY = velY; - } - - public double getVelZ() { - return velZ; - } - - public void setVelZ(double velZ) { - this.velZ = velZ; - } - - @Override - public void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); - tag.putDouble("velX", velX); - tag.putDouble("velY", velY); - tag.putDouble("velZ", velZ); - } - - @Override - public void load(CompoundTag tag) { - super.load(tag); - velX = tag.getDouble("velX"); - velY = tag.getDouble("velY"); - velZ = tag.getDouble("velZ"); - } - - @Nullable - @Override - public Packet getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this); - } - - @Override - public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { - buf.writeBlockPos(this.worldPosition); - buf.writeDouble(velX); - buf.writeDouble(velY); - buf.writeDouble(velZ); - } - - @NotNull - @Override - public Component getDisplayName() { - return Component.empty(); - } - - @Nullable - @Override - public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { - return new FaithPlateScreenHandler(i); - } - - public void updateListeners() { - setChanged(); - assert level != null; - level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); - } - - @Override - @Nullable - public AnimationState getAnimation(String name) { - return name.equals("fling") ? flingState : null; - } + private double velX = 0; + private double velY = 0; + private double velZ = 0; + + private double timer = 0; + public final AnimationState flingState = new AnimationState(); + + public FaithPlateBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + } + + public FaithPlateBlockEntity(BlockPos pos, BlockState state) { + this(PortalCubedBlocks.FAITH_PLATE_BLOCK_ENTITY, pos, state); + } + + @Override + public void tick(Level world, BlockPos pos, BlockState state) { + super.tick(world, pos, state); + if (state.getValue(FaithPlateBlock.FACING).getAxis().isVertical()) { + final boolean isFlipped = state.getValue(FaithPlateBlock.FACING) == Direction.DOWN; + setYaw(directionToAngle(state.getValue(FaithPlateBlock.HORIFACING)) * (isFlipped ? -1 : 1)); + setPitch(isFlipped ? 180f : 0f); + } else { + setYaw(directionToAngle(state.getValue(FaithPlateBlock.FACING)) + 180f); + setPitch(90f); + } + + AABB checkBox = new AABB(pos).move( + state.getValue(FaithPlateBlock.FACING).getStepX(), + state.getValue(FaithPlateBlock.FACING).getStepY(), + state.getValue(FaithPlateBlock.FACING).getStepZ() + ); + + List list = world.getEntitiesOfClass(Entity.class, checkBox); + + final boolean launch = new Vec3(velX, velY, velZ).lengthSqr() > 1e-7; + for (Entity liver : list) { + if (timer <= 0) { + if (liver instanceof CorePhysicsEntity physEn && physEn.getHolderUUID().isPresent()) { + continue; + } + if (launch) { + final Vec3 force = new Vec3(velX, velY, velZ); + RayonIntegration.INSTANCE.setVelocity(liver, force); + if (liver instanceof ServerPlayer player) { + PortalCubedTriggers.FLING.trigger(player, worldPosition, force); + } + } + timer = 5; + if (!world.isClientSide) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBlockPos(pos); + buf.writeUtf("fling"); + //noinspection DataFlowIssue + world.getServer() + .getPlayerList() + .broadcast( + null, + pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, + 96, world.dimension(), + ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.SERVER_ANIMATE, buf) + ); + } + world.playSound( + null, + pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, + PortalCubedSounds.CATAPULT_LAUNCH_EVENT, SoundSource.BLOCKS, + .2f, 1f + ); + } + } + if (timer > 0) { + timer--; + } + } + + private static float directionToAngle(Direction dir) { + return switch (dir) { + case EAST -> 90f; + case SOUTH -> 180f; + case WEST -> -90f; + case NORTH -> 0f; + default -> throw new AssertionError("FaithPlateBlockEntity.directionToAngle called with non-horizontal direction " + dir); + }; + } + + public double getVelX() { + return velX; + } + + public void setVelX(double velX) { + this.velX = velX; + } + + public double getVelY() { + return velY; + } + + public void setVelY(double velY) { + this.velY = velY; + } + + public double getVelZ() { + return velZ; + } + + public void setVelZ(double velZ) { + this.velZ = velZ; + } + + @Override + public void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + tag.putDouble("velX", velX); + tag.putDouble("velY", velY); + tag.putDouble("velZ", velZ); + } + + @Override + public void load(CompoundTag tag) { + super.load(tag); + velX = tag.getDouble("velX"); + velY = tag.getDouble("velY"); + velZ = tag.getDouble("velZ"); + } + + @Nullable + @Override + public Packet getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } + + @Override + public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { + buf.writeBlockPos(this.worldPosition); + buf.writeDouble(velX); + buf.writeDouble(velY); + buf.writeDouble(velZ); + } + + @NotNull + @Override + public Component getDisplayName() { + return Component.empty(); + } + + @Nullable + @Override + public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { + return new FaithPlateScreenHandler(i); + } + + public void updateListeners() { + setChanged(); + assert level != null; + level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); + } + + @Override + @Nullable + public AnimationState getAnimation(String name) { + return name.equals("fling") ? flingState : null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FloorButtonBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FloorButtonBlockEntity.java index 1a8667da..b572520c 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FloorButtonBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/FloorButtonBlockEntity.java @@ -25,69 +25,69 @@ public class FloorButtonBlockEntity extends BlockEntity { - public FloorButtonBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.FLOOR_BUTTON_BLOCK_ENTITY, pos, state); - - } - - public static void tick1(Level world, BlockPos pos, BlockState state, FloorButtonBlockEntity blockEntity) { - if (!world.isClientSide) { - Direction storedDirec = blockEntity.getBlockState().getValue(BlockStateProperties.FACING); - Direction storedDirecOpp = storedDirec.getOpposite(); - BlockPos transPos = pos.relative(storedDirec); - - AABB portalCheckBox = new AABB(transPos); - - portalCheckBox = portalCheckBox.deflate(Math.abs(storedDirecOpp.getStepX()), Math.abs(storedDirecOpp.getStepY()), Math.abs(storedDirecOpp.getStepZ())).move(storedDirecOpp.getStepX() * .8125, storedDirecOpp.getStepY() * .8125, storedDirecOpp.getStepZ() * .8125); - List entities = world.getEntitiesOfClass(LivingEntity.class, portalCheckBox); - - boolean isPowered = false; - for (LivingEntity living : entities) { - if (living instanceof Player || living instanceof StorageCubeEntity || living instanceof Portal1CompanionCubeEntity || living instanceof Portal1StorageCubeEntity || living instanceof OldApCubeEntity) { - if (living instanceof CorePhysicsEntity physicsEntity) { - if (physicsEntity.fizzling()) { - physicsEntity.push(0, 0.015, 0); - } else { - isPowered = true; - if (living instanceof StorageCubeEntity cube) { - cube.setButtonTimer(1); - } - } - } else { - isPowered = true; - } - } - } - - if (state.getValue(BlockStateProperties.ENABLED) != isPowered) { - blockEntity.updateState(state, isPowered); - } - } - - - } - - public void updateState(BlockState state, boolean toggle) { - if (level != null) { - level.setBlock(worldPosition, state.setValue(BlockStateProperties.ENABLED, toggle), 3); - if (!level.isClientSide && state.getValue(BlockStateProperties.ENABLED) != toggle) { - level.playSound( - null, worldPosition, - toggle ? PortalCubedSounds.FLOOR_BUTTON_PRESS_EVENT : PortalCubedSounds.FLOOR_BUTTON_RELEASE_EVENT, - SoundSource.BLOCKS, 0.8f, 1f - ); - } - } - } - - @Override - public void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); - } - - @Override - public void load(CompoundTag tag) { - super.load(tag); - } + public FloorButtonBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.FLOOR_BUTTON_BLOCK_ENTITY, pos, state); + + } + + public static void tick1(Level world, BlockPos pos, BlockState state, FloorButtonBlockEntity blockEntity) { + if (!world.isClientSide) { + Direction storedDirec = blockEntity.getBlockState().getValue(BlockStateProperties.FACING); + Direction storedDirecOpp = storedDirec.getOpposite(); + BlockPos transPos = pos.relative(storedDirec); + + AABB portalCheckBox = new AABB(transPos); + + portalCheckBox = portalCheckBox.deflate(Math.abs(storedDirecOpp.getStepX()), Math.abs(storedDirecOpp.getStepY()), Math.abs(storedDirecOpp.getStepZ())).move(storedDirecOpp.getStepX() * .8125, storedDirecOpp.getStepY() * .8125, storedDirecOpp.getStepZ() * .8125); + List entities = world.getEntitiesOfClass(LivingEntity.class, portalCheckBox); + + boolean isPowered = false; + for (LivingEntity living : entities) { + if (living instanceof Player || living instanceof StorageCubeEntity || living instanceof Portal1CompanionCubeEntity || living instanceof Portal1StorageCubeEntity || living instanceof OldApCubeEntity) { + if (living instanceof CorePhysicsEntity physicsEntity) { + if (physicsEntity.fizzling()) { + physicsEntity.push(0, 0.015, 0); + } else { + isPowered = true; + if (living instanceof StorageCubeEntity cube) { + cube.setButtonTimer(1); + } + } + } else { + isPowered = true; + } + } + } + + if (state.getValue(BlockStateProperties.ENABLED) != isPowered) { + blockEntity.updateState(state, isPowered); + } + } + + + } + + public void updateState(BlockState state, boolean toggle) { + if (level != null) { + level.setBlock(worldPosition, state.setValue(BlockStateProperties.ENABLED, toggle), 3); + if (!level.isClientSide && state.getValue(BlockStateProperties.ENABLED) != toggle) { + level.playSound( + null, worldPosition, + toggle ? PortalCubedSounds.FLOOR_BUTTON_PRESS_EVENT : PortalCubedSounds.FLOOR_BUTTON_RELEASE_EVENT, + SoundSource.BLOCKS, 0.8f, 1f + ); + } + } + } + + @Override + public void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + } + + @Override + public void load(CompoundTag tag) { + super.load(tag); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserEmitterBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserEmitterBlockEntity.java index 54ab69e8..bea5f8cc 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserEmitterBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserEmitterBlockEntity.java @@ -49,276 +49,276 @@ import static com.fusionflux.portalcubed.mechanics.PortalCubedDamageSources.pcSources; public class LaserEmitterBlockEntity extends BlockEntity { - private record Target(@NotNull BlockPos pos, @Nullable Direction side) { - } + private record Target(@NotNull BlockPos pos, @Nullable Direction side) { + } - private final List multiSegments = new ArrayList<>(); - private final Set targets = new HashSet<>(); + private final List multiSegments = new ArrayList<>(); + private final Set targets = new HashSet<>(); - @ClientOnly - private SoundInstance musicInstance; + @ClientOnly + private SoundInstance musicInstance; - public LaserEmitterBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY, pos, state); - } + public LaserEmitterBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY, pos, state); + } - @Override - public void saveAdditional(@NotNull CompoundTag tag) { - final ListTag list = new ListTag(); - for (final Target target : targets) { - final CompoundTag targetNbt = new CompoundTag(); - targetNbt.putIntArray("Target", new int[] {target.pos.getX(), target.pos.getY(), target.pos.getZ()}); - if (target.side != null) { - targetNbt.putString("TargetSide", target.side.getName()); - } - list.add(targetNbt); - } - tag.put("Targets", list); - } + @Override + public void saveAdditional(@NotNull CompoundTag tag) { + final ListTag list = new ListTag(); + for (final Target target : targets) { + final CompoundTag targetNbt = new CompoundTag(); + targetNbt.putIntArray("Target", new int[] {target.pos.getX(), target.pos.getY(), target.pos.getZ()}); + if (target.side != null) { + targetNbt.putString("TargetSide", target.side.getName()); + } + list.add(targetNbt); + } + tag.put("Targets", list); + } - @Override - public void load(CompoundTag tag) { - targets.clear(); - for (final Tag elem : tag.getList("Targets", Tag.TAG_COMPOUND)) { - final CompoundTag targetNbt = (CompoundTag)elem; - final int[] targetA = targetNbt.getIntArray("Target"); - if (targetA.length >= 3) { - targets.add(new Target( - new BlockPos(targetA[0], targetA[1], targetA[2]), - Direction.byName(tag.getString("TargetSide")) - )); - } - } - } + @Override + public void load(CompoundTag tag) { + targets.clear(); + for (final Tag elem : tag.getList("Targets", Tag.TAG_COMPOUND)) { + final CompoundTag targetNbt = (CompoundTag)elem; + final int[] targetA = targetNbt.getIntArray("Target"); + if (targetA.length >= 3) { + targets.add(new Target( + new BlockPos(targetA[0], targetA[1], targetA[2]), + Direction.byName(tag.getString("TargetSide")) + )); + } + } + } - public void clearTargets() { - assert level != null; - if (!level.isClientSide) { - for (final Target target : targets) { - level.getBlockEntity(target.pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).ifPresent(LaserNodeBlockEntity::removeLaser); - } - targets.clear(); - } - } + public void clearTargets() { + assert level != null; + if (!level.isClientSide) { + for (final Target target : targets) { + level.getBlockEntity(target.pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).ifPresent(LaserNodeBlockEntity::removeLaser); + } + targets.clear(); + } + } - public void tick(Level level, BlockPos pos, BlockState state) { - if (!state.is(PortalCubedBlocks.LASER_EMITTER)) - return; - multiSegments.clear(); - if (!state.getValue(LaserEmitterBlock.POWERED)) { - clearTargets(); - return; - } - Vec3 direction = Vec3.atLowerCornerOf(state.getValue(LaserEmitterBlock.FACING).getNormal()); - Vec3 start = Vec3.atCenterOf(pos).add(direction.scale(0.5)); - double lengthRemaining = PortalCubedConfig.maxBridgeLength; - final Set alreadyHit = new HashSet<>(); - BlockState hitState; - do { - //noinspection DataFlowIssue - final AdvancedEntityRaycast.Result segments = AdvancedEntityRaycast.raycast( - level, - new ClipContext( - start, start.add(direction.scale(lengthRemaining)), - ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, null - ), - (level1, ctx) -> BlockGetter.traverseBlocks( - ctx.getFrom(), ctx.getTo(), ctx, - (ctx1, pos1) -> { - final BlockState block = level1.getBlockState(pos1); - final VoxelShape shape = block.is(PortalCubedBlocks.REFLECTIVE) - ? block.getShape(level1, pos1) - : ctx1.getBlockShape(block, level1, pos1); - return level1.clipWithInteractionOverride(ctx1.getFrom(), ctx1.getTo(), pos1, shape, block); - }, - ctx1 -> { - final Vec3 offset = ctx1.getFrom().subtract(ctx1.getTo()); - return BlockHitResult.miss( - ctx1.getTo(), - Direction.getNearest(offset.x, offset.y, offset.z), - BlockPos.containing(ctx1.getTo()) - ); - } - ), - PortalDirectionUtils.PORTAL_RAYCAST_TRANSFORM, - new AdvancedEntityRaycast.TransformInfo( - e -> e instanceof RedirectionCubeEntity && !alreadyHit.contains(e), - (context, blockHit, entityHit) -> { - final RedirectionCubeEntity entity = (RedirectionCubeEntity)entityHit.getEntity(); - alreadyHit.add(entity); - final double distance = context.getFrom().distanceTo(context.getTo()); - final Vec3 offset = entityHit.getLocation().subtract(context.getFrom()); - final RedirectionCubeEntity destination = entity.getConnection(); - alreadyHit.add(destination); - destination.markActive(); - final Vec3 newOffset = Vec3.directionFromRotation(destination.getXRot(), destination.getYRot()) - .scale(distance - offset.length()); - final Vec3 origin = destination.position().add(new Vec3(0, destination.getBbHeight() / 2, 0)); - return new AdvancedEntityRaycast.TransformResult( - entityHit.getLocation().add(offset.scale(0.25 / offset.length())), - AdvancedEntityRaycast.withStartEnd(context, origin, origin.add(newOffset)) - ); - } - ), - new AdvancedEntityRaycast.TransformInfo( - e -> e instanceof CorePhysicsEntity && !alreadyHit.contains(e), - (context, blockHit, entityHit) -> new AdvancedEntityRaycast.TransformResult(entityHit.getLocation(), null) - ) - ); - direction = segments.finalRay().relative().normalize(); - start = segments.finalRay().end(); - lengthRemaining -= segments.length(); - multiSegments.add(segments); - if (segments.finalHit().getType() == HitResult.Type.BLOCK) { - final BlockHitResult finalHit = (BlockHitResult)segments.finalHit(); - hitState = level.getBlockState(finalHit.getBlockPos()); - if (hitState.is(PortalCubedBlocks.REFLECTIVE)) { - final Direction.Axis axis = finalHit.getDirection().getAxis(); - direction = direction.with(axis, -direction.get(axis)); - } - } else { - hitState = null; - } - } while (hitState != null && (hitState.is(PortalCubedBlocks.LASER_RELAY) || hitState.is(PortalCubedBlocks.REFLECTIVE))); + public void tick(Level level, BlockPos pos, BlockState state) { + if (!state.is(PortalCubedBlocks.LASER_EMITTER)) + return; + multiSegments.clear(); + if (!state.getValue(LaserEmitterBlock.POWERED)) { + clearTargets(); + return; + } + Vec3 direction = Vec3.atLowerCornerOf(state.getValue(LaserEmitterBlock.FACING).getNormal()); + Vec3 start = Vec3.atCenterOf(pos).add(direction.scale(0.5)); + double lengthRemaining = PortalCubedConfig.maxBridgeLength; + final Set alreadyHit = new HashSet<>(); + BlockState hitState; + do { + //noinspection DataFlowIssue + final AdvancedEntityRaycast.Result segments = AdvancedEntityRaycast.raycast( + level, + new ClipContext( + start, start.add(direction.scale(lengthRemaining)), + ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, null + ), + (level1, ctx) -> BlockGetter.traverseBlocks( + ctx.getFrom(), ctx.getTo(), ctx, + (ctx1, pos1) -> { + final BlockState block = level1.getBlockState(pos1); + final VoxelShape shape = block.is(PortalCubedBlocks.REFLECTIVE) + ? block.getShape(level1, pos1) + : ctx1.getBlockShape(block, level1, pos1); + return level1.clipWithInteractionOverride(ctx1.getFrom(), ctx1.getTo(), pos1, shape, block); + }, + ctx1 -> { + final Vec3 offset = ctx1.getFrom().subtract(ctx1.getTo()); + return BlockHitResult.miss( + ctx1.getTo(), + Direction.getNearest(offset.x, offset.y, offset.z), + BlockPos.containing(ctx1.getTo()) + ); + } + ), + PortalDirectionUtils.PORTAL_RAYCAST_TRANSFORM, + new AdvancedEntityRaycast.TransformInfo( + e -> e instanceof RedirectionCubeEntity && !alreadyHit.contains(e), + (context, blockHit, entityHit) -> { + final RedirectionCubeEntity entity = (RedirectionCubeEntity)entityHit.getEntity(); + alreadyHit.add(entity); + final double distance = context.getFrom().distanceTo(context.getTo()); + final Vec3 offset = entityHit.getLocation().subtract(context.getFrom()); + final RedirectionCubeEntity destination = entity.getConnection(); + alreadyHit.add(destination); + destination.markActive(); + final Vec3 newOffset = Vec3.directionFromRotation(destination.getXRot(), destination.getYRot()) + .scale(distance - offset.length()); + final Vec3 origin = destination.position().add(new Vec3(0, destination.getBbHeight() / 2, 0)); + return new AdvancedEntityRaycast.TransformResult( + entityHit.getLocation().add(offset.scale(0.25 / offset.length())), + AdvancedEntityRaycast.withStartEnd(context, origin, origin.add(newOffset)) + ); + } + ), + new AdvancedEntityRaycast.TransformInfo( + e -> e instanceof CorePhysicsEntity && !alreadyHit.contains(e), + (context, blockHit, entityHit) -> new AdvancedEntityRaycast.TransformResult(entityHit.getLocation(), null) + ) + ); + direction = segments.finalRay().relative().normalize(); + start = segments.finalRay().end(); + lengthRemaining -= segments.length(); + multiSegments.add(segments); + if (segments.finalHit().getType() == HitResult.Type.BLOCK) { + final BlockHitResult finalHit = (BlockHitResult)segments.finalHit(); + hitState = level.getBlockState(finalHit.getBlockPos()); + if (hitState.is(PortalCubedBlocks.REFLECTIVE)) { + final Direction.Axis axis = finalHit.getDirection().getAxis(); + direction = direction.with(axis, -direction.get(axis)); + } + } else { + hitState = null; + } + } while (hitState != null && (hitState.is(PortalCubedBlocks.LASER_RELAY) || hitState.is(PortalCubedBlocks.REFLECTIVE))); - if (level.isClientSide) { - clientTick(); - return; - } + if (level.isClientSide) { + clientTick(); + return; + } - if (hitState != null && !(hitState.getBlock() instanceof AbstractLaserNodeBlock)) { - final Vec3 finalPos = multiSegments.get(multiSegments.size() - 1).finalRay().end(); - } + if (hitState != null && !(hitState.getBlock() instanceof AbstractLaserNodeBlock)) { + final Vec3 finalPos = multiSegments.get(multiSegments.size() - 1).finalRay().end(); + } - Entity owner = EntityType.MARKER.create(level); - assert owner != null; - alreadyHit.clear(); - for (final AdvancedEntityRaycast.Result result : multiSegments) { - for (final AdvancedEntityRaycast.Result.Ray ray : result.rays()) { - Vec3 rayStart = ray.start(); - EntityHitResult hit; - do { - hit = new AdvancedEntityRaycast.Result.Ray(rayStart, ray.end(), null).entityRaycast(owner, e -> e instanceof LivingEntity && !alreadyHit.contains(e)); - if (hit != null) { - rayStart = hit.getLocation(); - final Entity hitEntity = hit.getEntity(); - alreadyHit.add(hitEntity); - owner = hitEntity; - if (hitEntity instanceof CorePhysicsEntity) { - continue; // TODO: Turrets and chairs burn - } - if (!hitEntity.onGround()) continue; - hitEntity.hurt(pcSources(level).laser(), PortalCubedConfig.laserDamage); - if(PortalCubedConfig.laserDamage > 0) - hitEntity.setRemainingFireTicks(Math.max(10, hitEntity.getRemainingFireTicks())); - final Vec3 velocity = GeneralUtil.calculatePerpendicularVector(ray.start(), ray.end(), hitEntity.position()) - .normalize() - .scale(1.25); - hitEntity.push(velocity.x, velocity.y, velocity.z); - } - } while (hit != null && !GeneralUtil.targetsEqual(hit, ray.hit())); - if (ray.hit() instanceof EntityHitResult entityHitResult) { - owner = entityHitResult.getEntity(); - } - } - } + Entity owner = EntityType.MARKER.create(level); + assert owner != null; + alreadyHit.clear(); + for (final AdvancedEntityRaycast.Result result : multiSegments) { + for (final AdvancedEntityRaycast.Result.Ray ray : result.rays()) { + Vec3 rayStart = ray.start(); + EntityHitResult hit; + do { + hit = new AdvancedEntityRaycast.Result.Ray(rayStart, ray.end(), null).entityRaycast(owner, e -> e instanceof LivingEntity && !alreadyHit.contains(e)); + if (hit != null) { + rayStart = hit.getLocation(); + final Entity hitEntity = hit.getEntity(); + alreadyHit.add(hitEntity); + owner = hitEntity; + if (hitEntity instanceof CorePhysicsEntity) { + continue; // TODO: Turrets and chairs burn + } + if (!hitEntity.onGround()) continue; + hitEntity.hurt(pcSources(level).laser(), PortalCubedConfig.laserDamage); + if(PortalCubedConfig.laserDamage > 0) + hitEntity.setRemainingFireTicks(Math.max(10, hitEntity.getRemainingFireTicks())); + final Vec3 velocity = GeneralUtil.calculatePerpendicularVector(ray.start(), ray.end(), hitEntity.position()) + .normalize() + .scale(1.25); + hitEntity.push(velocity.x, velocity.y, velocity.z); + } + } while (hit != null && !GeneralUtil.targetsEqual(hit, ray.hit())); + if (ray.hit() instanceof EntityHitResult entityHitResult) { + owner = entityHitResult.getEntity(); + } + } + } - final Set newTargets = new HashSet<>(); - final Object2IntMap changes = new Object2IntOpenHashMap<>(targets.size() + multiSegments.size()); - for (final AdvancedEntityRaycast.Result result : multiSegments) { - if (result.finalHit().getType() != HitResult.Type.BLOCK) continue; - final BlockHitResult finalHit = (BlockHitResult)result.finalHit(); - final BlockState hitState1 = level.getBlockState(finalHit.getBlockPos()); - if (hitState1.is(PortalCubedBlocks.LASER_CATCHER) && finalHit.getDirection() != hitState1.getValue(LaserCatcherBlock.FACING)) continue; - final Target target = new Target( - finalHit.getBlockPos(), - hitState1.is(PortalCubedBlocks.LASER_RELAY) ? null : finalHit.getDirection() - ); - newTargets.add(target); - if (targets.add(target)) { - changes.put(target.pos, changes.getOrDefault(target.pos, 0) + 1); - } - } + final Set newTargets = new HashSet<>(); + final Object2IntMap changes = new Object2IntOpenHashMap<>(targets.size() + multiSegments.size()); + for (final AdvancedEntityRaycast.Result result : multiSegments) { + if (result.finalHit().getType() != HitResult.Type.BLOCK) continue; + final BlockHitResult finalHit = (BlockHitResult)result.finalHit(); + final BlockState hitState1 = level.getBlockState(finalHit.getBlockPos()); + if (hitState1.is(PortalCubedBlocks.LASER_CATCHER) && finalHit.getDirection() != hitState1.getValue(LaserCatcherBlock.FACING)) continue; + final Target target = new Target( + finalHit.getBlockPos(), + hitState1.is(PortalCubedBlocks.LASER_RELAY) ? null : finalHit.getDirection() + ); + newTargets.add(target); + if (targets.add(target)) { + changes.put(target.pos, changes.getOrDefault(target.pos, 0) + 1); + } + } - for (final Target target : targets) { - if (!newTargets.contains(target)) { - changes.put(target.pos, changes.getOrDefault(target.pos, 0) - 1); - } - } - targets.retainAll(newTargets); + for (final Target target : targets) { + if (!newTargets.contains(target)) { + changes.put(target.pos, changes.getOrDefault(target.pos, 0) - 1); + } + } + targets.retainAll(newTargets); - for (final var entry : changes.object2IntEntrySet()) { - if (entry.getIntValue() == 0) continue; - final LaserNodeBlockEntity entity = level.getBlockEntity(entry.getKey(), PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).orElse(null); - if (entity == null) continue; - if (entry.getIntValue() > 0) { - for (int i = 0; i < entry.getIntValue(); i++) { - entity.addLaser(); - } - } else { - for (int i = 0; i < -entry.getIntValue(); i++) { - entity.removeLaser(); - } - } - } - if (!changes.isEmpty()) { - setChanged(); - } - } + for (final var entry : changes.object2IntEntrySet()) { + if (entry.getIntValue() == 0) continue; + final LaserNodeBlockEntity entity = level.getBlockEntity(entry.getKey(), PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY).orElse(null); + if (entity == null) continue; + if (entry.getIntValue() > 0) { + for (int i = 0; i < entry.getIntValue(); i++) { + entity.addLaser(); + } + } else { + for (int i = 0; i < -entry.getIntValue(); i++) { + entity.removeLaser(); + } + } + } + if (!changes.isEmpty()) { + setChanged(); + } + } - public List getMultiSegments() { - return multiSegments; - } + public List getMultiSegments() { + return multiSegments; + } - @ClientOnly - protected void clientTick() { - if (musicInstance == null && level != null && level.getBlockState(worldPosition).getValue(LaserEmitterBlock.POWERED)) { - musicInstance = new AbstractTickableSoundInstance(PortalCubedSounds.LASER_BEAM_MUSIC_EVENT, SoundSource.BLOCKS, SoundInstance.createUnseededRandom()) { - { - volume = 0.025f; - looping = true; - } + @ClientOnly + protected void clientTick() { + if (musicInstance == null && level != null && level.getBlockState(worldPosition).getValue(LaserEmitterBlock.POWERED)) { + musicInstance = new AbstractTickableSoundInstance(PortalCubedSounds.LASER_BEAM_MUSIC_EVENT, SoundSource.BLOCKS, SoundInstance.createUnseededRandom()) { + { + volume = 0.025f; + looping = true; + } - @Override - public void tick() { - if (isRemoved() || level == null || !level.getBlockState(worldPosition).getValue(LaserEmitterBlock.POWERED)) { - musicInstance = null; - stop(); - return; - } - final Vec3 cameraPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); - Vec3 usePos = null; - double distanceSq = Double.POSITIVE_INFINITY; - for (final AdvancedEntityRaycast.Result segments : multiSegments) { - for (final AdvancedEntityRaycast.Result.Ray ray : segments.rays()) { - Vec3 tryPos = GeneralUtil.nearestPointOnLine( - ray.start(), ray.end().subtract(ray.start()), cameraPos - ); - double tryDistance = tryPos.distanceToSqr(cameraPos); - if (tryPos.distanceToSqr(ray.start()) > ray.end().distanceToSqr(ray.start())) { - tryPos = ray.end(); - tryDistance = tryPos.distanceToSqr(cameraPos); - } else if (tryPos.distanceToSqr(ray.end()) > ray.end().distanceToSqr(ray.start())) { - tryPos = ray.start(); - tryDistance = tryPos.distanceToSqr(cameraPos); - } - if (tryDistance < distanceSq) { - usePos = tryPos; - distanceSq = tryDistance; - } - } - } - if (usePos == null) { - musicInstance = null; - stop(); - return; - } - x = usePos.x; - y = usePos.y; - z = usePos.z; - } - }; - Minecraft.getInstance().getSoundManager().play(musicInstance); - } - } + @Override + public void tick() { + if (isRemoved() || level == null || !level.getBlockState(worldPosition).getValue(LaserEmitterBlock.POWERED)) { + musicInstance = null; + stop(); + return; + } + final Vec3 cameraPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); + Vec3 usePos = null; + double distanceSq = Double.POSITIVE_INFINITY; + for (final AdvancedEntityRaycast.Result segments : multiSegments) { + for (final AdvancedEntityRaycast.Result.Ray ray : segments.rays()) { + Vec3 tryPos = GeneralUtil.nearestPointOnLine( + ray.start(), ray.end().subtract(ray.start()), cameraPos + ); + double tryDistance = tryPos.distanceToSqr(cameraPos); + if (tryPos.distanceToSqr(ray.start()) > ray.end().distanceToSqr(ray.start())) { + tryPos = ray.end(); + tryDistance = tryPos.distanceToSqr(cameraPos); + } else if (tryPos.distanceToSqr(ray.end()) > ray.end().distanceToSqr(ray.start())) { + tryPos = ray.start(); + tryDistance = tryPos.distanceToSqr(cameraPos); + } + if (tryDistance < distanceSq) { + usePos = tryPos; + distanceSq = tryDistance; + } + } + } + if (usePos == null) { + musicInstance = null; + stop(); + return; + } + x = usePos.x; + y = usePos.y; + z = usePos.z; + } + }; + Minecraft.getInstance().getSoundManager().play(musicInstance); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserNodeBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserNodeBlockEntity.java index acdc1967..dcc021e3 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserNodeBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/LaserNodeBlockEntity.java @@ -26,137 +26,137 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class LaserNodeBlockEntity extends BlockEntity { - private ResourceLocation sound = PortalCubedSounds.LASER_NODE_MUSIC; - private int laserCount; - - @ClientOnly - private SoundInstance musicInstance; - - public LaserNodeBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY, pos, state); - } - - public void updateState(boolean toggle) { - assert level != null; - level.playSound(null, worldPosition, toggle ? PortalCubedSounds.LASER_NODE_ACTIVATE_EVENT : PortalCubedSounds.LASER_NODE_DEACTIVATE_EVENT, SoundSource.BLOCKS, 0.3f, 1f); - level.setBlockAndUpdate(worldPosition, level.getBlockState(worldPosition).setValue(BlockStateProperties.ENABLED, toggle)); - setChanged(); - } - - public void addLaser() { - if (laserCount++ == 0) { - updateState(true); - } - if (laserCount < 0) { - if (laserCount == Integer.MIN_VALUE) { - PortalCubed.LOGGER.warn("More than 2 *billion* lasers hit the laser node at {}!?", worldPosition); - laserCount = Integer.MAX_VALUE; - } else { - PortalCubed.LOGGER.warn("Laser node at {} has a negative number of lasers hitting it?", worldPosition); - laserCount = 0; - } - } - } - - public void removeLaser() { - if (--laserCount <= 0) { - updateState(false); - } - if (laserCount < 0) { - PortalCubed.LOGGER.warn("Laser node at {} has a negative number of lasers hitting it?", worldPosition); - laserCount = 0; - } - } - - @Override - protected void saveAdditional(CompoundTag nbt) { - nbt.putInt("LaserCount", laserCount); - nbt.putString("Sound", sound.toString()); - } - - @Override - public void load(CompoundTag nbt) { - laserCount = nbt.getInt("LaserCount"); - - final String soundStr = nbt.getString("Sound"); - if (!soundStr.isEmpty()) { - sound = new ResourceLocation(soundStr); - } - } - - @NotNull - @Override - public CompoundTag getUpdateTag() { - return saveWithoutMetadata(); - } - - @Nullable - @Override - public Packet getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this); - } - - public static void tick(Level world, BlockPos pos, BlockState state, LaserNodeBlockEntity blockEntity) { - if (world.isClientSide) { - blockEntity.clientTick(state); - } - } - - @ClientOnly - protected void clientTick(BlockState state) { - if (musicInstance == null && level != null && state.getValue(BlockStateProperties.ENABLED)) { - // The sounds played here may actually be stereo, so we may need to handle our own fadeout - musicInstance = new AbstractTickableSoundInstance(SoundEvent.createVariableRangeEvent(sound), SoundSource.BLOCKS, SoundInstance.createUnseededRandom()) { - final ResourceLocation soundId = LaserNodeBlockEntity.this.sound; - final boolean isCustomSound = !soundId.equals(PortalCubedSounds.LASER_NODE_MUSIC); - - { - if (!isCustomSound) { - volume = 0.5f; - } - x = getBlockPos().getX() + 0.5; - y = getBlockPos().getY() + 0.5; - z = getBlockPos().getZ() + 0.5; - looping = true; - } - - @Override - public void tick() { - if (level != null && !isRemoved() && LaserNodeBlockEntity.this.sound.equals(soundId)) { - BlockState state = level.getBlockState(worldPosition); - if (state.hasProperty(BlockStateProperties.ENABLED) && state.getValue(BlockStateProperties.ENABLED)) { - if (!isCustomSound) return; - final Vec3 cameraPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); - final float newVolume = Mth.clampedLerp(0.01f, 1f, 1f - (float)cameraPos.subtract(x, y, z).length() / 16f); - if (newVolume != volume) { - volume = newVolume; - Minecraft.getInstance().getSoundManager().updateSourceVolume(null, 0); - } - return; - } - } - - musicInstance = null; - stop(); - } - }; - Minecraft.getInstance().getSoundManager().play(musicInstance); - } - } - - public ResourceLocation getSound() { - return sound; - } - - public void setSound(ResourceLocation sound) { - this.sound = sound; - updateListeners(); - } - - public void updateListeners() { - setChanged(); - assert level != null; - final BlockState state = level.getBlockState(worldPosition); - level.sendBlockUpdated(worldPosition, state, state, Block.UPDATE_ALL); - } + private ResourceLocation sound = PortalCubedSounds.LASER_NODE_MUSIC; + private int laserCount; + + @ClientOnly + private SoundInstance musicInstance; + + public LaserNodeBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY, pos, state); + } + + public void updateState(boolean toggle) { + assert level != null; + level.playSound(null, worldPosition, toggle ? PortalCubedSounds.LASER_NODE_ACTIVATE_EVENT : PortalCubedSounds.LASER_NODE_DEACTIVATE_EVENT, SoundSource.BLOCKS, 0.3f, 1f); + level.setBlockAndUpdate(worldPosition, level.getBlockState(worldPosition).setValue(BlockStateProperties.ENABLED, toggle)); + setChanged(); + } + + public void addLaser() { + if (laserCount++ == 0) { + updateState(true); + } + if (laserCount < 0) { + if (laserCount == Integer.MIN_VALUE) { + PortalCubed.LOGGER.warn("More than 2 *billion* lasers hit the laser node at {}!?", worldPosition); + laserCount = Integer.MAX_VALUE; + } else { + PortalCubed.LOGGER.warn("Laser node at {} has a negative number of lasers hitting it?", worldPosition); + laserCount = 0; + } + } + } + + public void removeLaser() { + if (--laserCount <= 0) { + updateState(false); + } + if (laserCount < 0) { + PortalCubed.LOGGER.warn("Laser node at {} has a negative number of lasers hitting it?", worldPosition); + laserCount = 0; + } + } + + @Override + protected void saveAdditional(CompoundTag nbt) { + nbt.putInt("LaserCount", laserCount); + nbt.putString("Sound", sound.toString()); + } + + @Override + public void load(CompoundTag nbt) { + laserCount = nbt.getInt("LaserCount"); + + final String soundStr = nbt.getString("Sound"); + if (!soundStr.isEmpty()) { + sound = new ResourceLocation(soundStr); + } + } + + @NotNull + @Override + public CompoundTag getUpdateTag() { + return saveWithoutMetadata(); + } + + @Nullable + @Override + public Packet getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } + + public static void tick(Level world, BlockPos pos, BlockState state, LaserNodeBlockEntity blockEntity) { + if (world.isClientSide) { + blockEntity.clientTick(state); + } + } + + @ClientOnly + protected void clientTick(BlockState state) { + if (musicInstance == null && level != null && state.getValue(BlockStateProperties.ENABLED)) { + // The sounds played here may actually be stereo, so we may need to handle our own fadeout + musicInstance = new AbstractTickableSoundInstance(SoundEvent.createVariableRangeEvent(sound), SoundSource.BLOCKS, SoundInstance.createUnseededRandom()) { + final ResourceLocation soundId = LaserNodeBlockEntity.this.sound; + final boolean isCustomSound = !soundId.equals(PortalCubedSounds.LASER_NODE_MUSIC); + + { + if (!isCustomSound) { + volume = 0.5f; + } + x = getBlockPos().getX() + 0.5; + y = getBlockPos().getY() + 0.5; + z = getBlockPos().getZ() + 0.5; + looping = true; + } + + @Override + public void tick() { + if (level != null && !isRemoved() && LaserNodeBlockEntity.this.sound.equals(soundId)) { + BlockState state = level.getBlockState(worldPosition); + if (state.hasProperty(BlockStateProperties.ENABLED) && state.getValue(BlockStateProperties.ENABLED)) { + if (!isCustomSound) return; + final Vec3 cameraPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); + final float newVolume = Mth.clampedLerp(0.01f, 1f, 1f - (float)cameraPos.subtract(x, y, z).length() / 16f); + if (newVolume != volume) { + volume = newVolume; + Minecraft.getInstance().getSoundManager().updateSourceVolume(null, 0); + } + return; + } + } + + musicInstance = null; + stop(); + } + }; + Minecraft.getInstance().getSoundManager().play(musicInstance); + } + } + + public ResourceLocation getSound() { + return sound; + } + + public void setSound(ResourceLocation sound) { + this.sound = sound; + updateListeners(); + } + + public void updateListeners() { + setChanged(); + assert level != null; + final BlockState state = level.getBlockState(worldPosition); + level.sendBlockUpdated(worldPosition, state, state, Block.UPDATE_ALL); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinBlockEntity.java index f19e3905..7150e799 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinBlockEntity.java @@ -9,34 +9,34 @@ import net.minecraft.world.level.block.state.BlockState; public class NeurotoxinBlockEntity extends BlockEntity { - private int age = 1; + private int age = 1; - public NeurotoxinBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.NEUROTOXIN_BLOCK_ENTITY, pos, state); - } + public NeurotoxinBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.NEUROTOXIN_BLOCK_ENTITY, pos, state); + } - public static void tick(Level world, BlockPos pos, @SuppressWarnings("unused") BlockState state, NeurotoxinBlockEntity blockEntity) { - assert world != null; + public static void tick(Level world, BlockPos pos, @SuppressWarnings("unused") BlockState state, NeurotoxinBlockEntity blockEntity) { + assert world != null; - if (!world.isClientSide) { - blockEntity.age++; - } + if (!world.isClientSide) { + blockEntity.age++; + } - if (!world.isClientSide && blockEntity.age % 5 == 0) { - for (int i = 0; i < 3; i++) { - Direction dir = Direction.getRandom(world.getRandom()); - if (world.getBlockState(blockEntity.getBlockPos().relative(dir)).isAir()) { - world.setBlockAndUpdate(blockEntity.getBlockPos().relative(dir), blockEntity.getBlockState()); - world.setBlockAndUpdate(blockEntity.getBlockPos(), Blocks.AIR.defaultBlockState()); - if (world.getBlockEntity(pos.relative(dir)) instanceof NeurotoxinBlockEntity newBE) { - newBE.age = blockEntity.age; - } - break; - } - } - } + if (!world.isClientSide && blockEntity.age % 5 == 0) { + for (int i = 0; i < 3; i++) { + Direction dir = Direction.getRandom(world.getRandom()); + if (world.getBlockState(blockEntity.getBlockPos().relative(dir)).isAir()) { + world.setBlockAndUpdate(blockEntity.getBlockPos().relative(dir), blockEntity.getBlockState()); + world.setBlockAndUpdate(blockEntity.getBlockPos(), Blocks.AIR.defaultBlockState()); + if (world.getBlockEntity(pos.relative(dir)) instanceof NeurotoxinBlockEntity newBE) { + newBE.age = blockEntity.age; + } + break; + } + } + } - if (world.random.nextInt(blockEntity.age) > 100) - world.setBlockAndUpdate(blockEntity.getBlockPos(), Blocks.AIR.defaultBlockState()); - } + if (world.random.nextInt(blockEntity.age) > 100) + world.setBlockAndUpdate(blockEntity.getBlockPos(), Blocks.AIR.defaultBlockState()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinEmitterBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinEmitterBlockEntity.java index 5e392ff1..432a7a60 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinEmitterBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/NeurotoxinEmitterBlockEntity.java @@ -10,46 +10,46 @@ public class NeurotoxinEmitterBlockEntity extends BlockEntity { - private final BlockPos.MutableBlockPos obstructorPos; - - public NeurotoxinEmitterBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.NEUROTOXIN_EMITTER_ENTITY, pos, state); - this.obstructorPos = pos.mutable(); - } - - - - public static void tick(Level world, BlockPos pos, @SuppressWarnings("unused") BlockState state, NeurotoxinEmitterBlockEntity blockEntity) { - assert world != null; - if (!world.isClientSide) { - boolean redstonePowered = world.hasNeighborSignal(blockEntity.getBlockPos()); - - if (redstonePowered) { - // Update blockstate - if (!world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { - blockEntity.togglePowered(world.getBlockState(pos)); - } - } - if (!redstonePowered) { - // Update blockstate - if (world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { - blockEntity.togglePowered(world.getBlockState(pos)); - } - } - if (world.isEmptyBlock(blockEntity.getBlockPos().relative(blockEntity.getBlockState().getValue(BlockStateProperties.FACING))) && world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { - world.setBlockAndUpdate(blockEntity.getBlockPos().relative(blockEntity.getBlockState().getValue(BlockStateProperties.FACING)), PortalCubedBlocks.NEUROTOXIN_BLOCK.defaultBlockState()); - } - - } - } - - public void spookyUpdateObstructor(BlockPos ownerPos) { - this.obstructorPos.set(ownerPos); - } - - private void togglePowered(BlockState state) { - assert level != null; - level.setBlockAndUpdate(worldPosition, state.cycle(BlockStateProperties.POWERED)); - } + private final BlockPos.MutableBlockPos obstructorPos; + + public NeurotoxinEmitterBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.NEUROTOXIN_EMITTER_ENTITY, pos, state); + this.obstructorPos = pos.mutable(); + } + + + + public static void tick(Level world, BlockPos pos, @SuppressWarnings("unused") BlockState state, NeurotoxinEmitterBlockEntity blockEntity) { + assert world != null; + if (!world.isClientSide) { + boolean redstonePowered = world.hasNeighborSignal(blockEntity.getBlockPos()); + + if (redstonePowered) { + // Update blockstate + if (!world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { + blockEntity.togglePowered(world.getBlockState(pos)); + } + } + if (!redstonePowered) { + // Update blockstate + if (world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { + blockEntity.togglePowered(world.getBlockState(pos)); + } + } + if (world.isEmptyBlock(blockEntity.getBlockPos().relative(blockEntity.getBlockState().getValue(BlockStateProperties.FACING))) && world.getBlockState(pos).getValue(BlockStateProperties.POWERED)) { + world.setBlockAndUpdate(blockEntity.getBlockPos().relative(blockEntity.getBlockState().getValue(BlockStateProperties.FACING)), PortalCubedBlocks.NEUROTOXIN_BLOCK.defaultBlockState()); + } + + } + } + + public void spookyUpdateObstructor(BlockPos ownerPos) { + this.obstructorPos.set(ownerPos); + } + + private void togglePowered(BlockState state) { + assert level != null; + level.setBlockAndUpdate(worldPosition, state.cycle(BlockStateProperties.POWERED)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/OldApFloorButtonBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/OldApFloorButtonBlockEntity.java index ab4ce53a..42d06cfd 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/OldApFloorButtonBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/OldApFloorButtonBlockEntity.java @@ -25,70 +25,70 @@ public class OldApFloorButtonBlockEntity extends BlockEntity { - public OldApFloorButtonBlockEntity(BlockPos pos, BlockState state) { - super(PortalCubedBlocks.OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY, pos, state); - - } - - public static void tick1(Level world, BlockPos pos, BlockState state, OldApFloorButtonBlockEntity blockEntity) { - if (!world.isClientSide) { - Direction storedDirec = blockEntity.getBlockState().getValue(BlockStateProperties.FACING); - Direction storedDirecOpp = storedDirec.getOpposite(); - BlockPos transPos = pos.relative(storedDirec); - - AABB portalCheckBox = new AABB(transPos); - - portalCheckBox = portalCheckBox.deflate(Math.abs(storedDirecOpp.getStepX()) * .75, Math.abs(storedDirecOpp.getStepY()) * .75, Math.abs(storedDirecOpp.getStepZ()) * .75).move(storedDirecOpp.getStepX() * .5, storedDirecOpp.getStepY() * .5, storedDirecOpp.getStepZ() * .5); - List entities = world.getEntitiesOfClass(LivingEntity.class, portalCheckBox); - - boolean isPowered = false; - for (LivingEntity living : entities) { - if (living instanceof Player || living instanceof StorageCubeEntity || living instanceof Portal1CompanionCubeEntity || living instanceof Portal1StorageCubeEntity || living instanceof OldApCubeEntity) { - if (living instanceof CorePhysicsEntity physicsEntity) { - if (physicsEntity.fizzling()) { - physicsEntity.push(0, 0.015, 0); - } else { - isPowered = true; - if (living instanceof StorageCubeEntity cube) { - cube.setButtonTimer(1); - } - } - } else { - isPowered = true; - } - } - } - - if (state.getValue(BlockStateProperties.ENABLED) != isPowered) { - blockEntity.updateState(state, isPowered); - } - - } - - - } - - public void updateState(BlockState state, boolean toggle) { - if (level != null) { - level.setBlock(worldPosition, state.setValue(BlockStateProperties.ENABLED, toggle), 3); - if (!level.isClientSide) { - level.playSound( - null, worldPosition, - toggle ? PortalCubedSounds.OLD_AP_FLOOR_BUTTON_PRESS_EVENT : PortalCubedSounds.OLD_AP_FLOOR_BUTTON_RELEASE_EVENT, - SoundSource.BLOCKS, 0.8f, 1f - ); - } - } - } - - @Override - public void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); - } - - @Override - public void load(CompoundTag tag) { - super.load(tag); - } + public OldApFloorButtonBlockEntity(BlockPos pos, BlockState state) { + super(PortalCubedBlocks.OLD_AP_FLOOR_BUTTON_BLOCK_ENTITY, pos, state); + + } + + public static void tick1(Level world, BlockPos pos, BlockState state, OldApFloorButtonBlockEntity blockEntity) { + if (!world.isClientSide) { + Direction storedDirec = blockEntity.getBlockState().getValue(BlockStateProperties.FACING); + Direction storedDirecOpp = storedDirec.getOpposite(); + BlockPos transPos = pos.relative(storedDirec); + + AABB portalCheckBox = new AABB(transPos); + + portalCheckBox = portalCheckBox.deflate(Math.abs(storedDirecOpp.getStepX()) * .75, Math.abs(storedDirecOpp.getStepY()) * .75, Math.abs(storedDirecOpp.getStepZ()) * .75).move(storedDirecOpp.getStepX() * .5, storedDirecOpp.getStepY() * .5, storedDirecOpp.getStepZ() * .5); + List entities = world.getEntitiesOfClass(LivingEntity.class, portalCheckBox); + + boolean isPowered = false; + for (LivingEntity living : entities) { + if (living instanceof Player || living instanceof StorageCubeEntity || living instanceof Portal1CompanionCubeEntity || living instanceof Portal1StorageCubeEntity || living instanceof OldApCubeEntity) { + if (living instanceof CorePhysicsEntity physicsEntity) { + if (physicsEntity.fizzling()) { + physicsEntity.push(0, 0.015, 0); + } else { + isPowered = true; + if (living instanceof StorageCubeEntity cube) { + cube.setButtonTimer(1); + } + } + } else { + isPowered = true; + } + } + } + + if (state.getValue(BlockStateProperties.ENABLED) != isPowered) { + blockEntity.updateState(state, isPowered); + } + + } + + + } + + public void updateState(BlockState state, boolean toggle) { + if (level != null) { + level.setBlock(worldPosition, state.setValue(BlockStateProperties.ENABLED, toggle), 3); + if (!level.isClientSide) { + level.playSound( + null, worldPosition, + toggle ? PortalCubedSounds.OLD_AP_FLOOR_BUTTON_PRESS_EVENT : PortalCubedSounds.OLD_AP_FLOOR_BUTTON_RELEASE_EVENT, + SoundSource.BLOCKS, 0.8f, 1f + ); + } + } + } + + @Override + public void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + } + + @Override + public void load(CompoundTag tag) { + super.load(tag); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/RocketTurretBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/RocketTurretBlockEntity.java index c55d9587..a5acb634 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/RocketTurretBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/RocketTurretBlockEntity.java @@ -39,255 +39,255 @@ import static com.fusionflux.portalcubed.blocks.RocketTurretBlock.POWERED; public class RocketTurretBlockEntity extends EntityLikeBlockEntity { - public static final int UPDATE_ANGLE = 0; - public static final int UPDATE_LOCKED_TICKS = 1; + public static final int UPDATE_ANGLE = 0; + public static final int UPDATE_LOCKED_TICKS = 1; - public static final int LOCK_TICKS = 30; + public static final int LOCK_TICKS = 30; - private static final Vec3 GUN_OFFSET = new Vec3(0.5, 1.71875, 0.09375); + private static final Vec3 GUN_OFFSET = new Vec3(0.5, 1.71875, 0.09375); - private int lockedTicks; - private UUID rocketUuid = Util.NIL_UUID; + private int lockedTicks; + private UUID rocketUuid = Util.NIL_UUID; - private Vec2 destAngle; - private Boolean powered; - private int opening = -1; - private boolean closing; - public List> aimDests; + private Vec2 destAngle; + private Boolean powered; + private int opening = -1; + private boolean closing; + public List> aimDests; - public final AnimationState activatingAnimation = new AnimationState(); - public final AnimationState deactivatingAnimation = new AnimationState(); - public final AnimationState shootAnimation = new AnimationState(); + public final AnimationState activatingAnimation = new AnimationState(); + public final AnimationState deactivatingAnimation = new AnimationState(); + public final AnimationState shootAnimation = new AnimationState(); - public RocketTurretBlockEntity(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { - super(blockEntityType, blockPos, blockState); - } + public RocketTurretBlockEntity(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { + super(blockEntityType, blockPos, blockState); + } - public RocketTurretBlockEntity(BlockPos blockPos, BlockState blockState) { - this(PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY, blockPos, blockState); - } + public RocketTurretBlockEntity(BlockPos blockPos, BlockState blockState) { + this(PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY, blockPos, blockState); + } - @Override - protected void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); - nbt.putFloat("LockedTicks", lockedTicks); - nbt.putUUID("RocketUUID", rocketUuid); - nbt.putBoolean("Closing", closing); - if (destAngle != null) { - nbt.putIntArray("DestAngle", new int[] {Float.floatToRawIntBits(destAngle.x), Float.floatToRawIntBits(destAngle.y)}); - } - } + @Override + protected void saveAdditional(CompoundTag nbt) { + super.saveAdditional(nbt); + nbt.putFloat("LockedTicks", lockedTicks); + nbt.putUUID("RocketUUID", rocketUuid); + nbt.putBoolean("Closing", closing); + if (destAngle != null) { + nbt.putIntArray("DestAngle", new int[] {Float.floatToRawIntBits(destAngle.x), Float.floatToRawIntBits(destAngle.y)}); + } + } - @Override - public void load(CompoundTag nbt) { - super.load(nbt); - lockedTicks = nbt.getInt("LockedTicks"); - rocketUuid = nbt.getUUID("RocketUUID"); - closing = nbt.getBoolean("Closing"); - final int[] destAngleA = nbt.getIntArray("DestAngle"); - if (destAngleA.length >= 2) { - destAngle = new Vec2( - Float.intBitsToFloat(destAngleA[0]), - Float.intBitsToFloat(destAngleA[1]) - ); - } - } + @Override + public void load(CompoundTag nbt) { + super.load(nbt); + lockedTicks = nbt.getInt("LockedTicks"); + rocketUuid = nbt.getUUID("RocketUUID"); + closing = nbt.getBoolean("Closing"); + final int[] destAngleA = nbt.getIntArray("DestAngle"); + if (destAngleA.length >= 2) { + destAngle = new Vec2( + Float.intBitsToFloat(destAngleA[0]), + Float.intBitsToFloat(destAngleA[1]) + ); + } + } - public void setAngle(Tuple angle) { - yaw = angle.getA(); - pitch = angle.getB(); - } + public void setAngle(Tuple angle) { + yaw = angle.getA(); + pitch = angle.getB(); + } - public void setLockedTicks(int lockedTicks) { - final boolean wasFiring = getState() == State.FIRING; - this.lockedTicks = lockedTicks; - if (!wasFiring && getState() == State.FIRING) { - shootAnimation.start(getAge()); - } - } + public void setLockedTicks(int lockedTicks) { + final boolean wasFiring = getState() == State.FIRING; + this.lockedTicks = lockedTicks; + if (!wasFiring && getState() == State.FIRING) { + shootAnimation.start(getAge()); + } + } - public void fire() { - if (level == null || level.isClientSide) { - PortalCubed.LOGGER.warn("RocketTurretBlockEntity.fire() should only be called on the server, not the client."); - return; - } - final RocketEntity rocket = PortalCubedEntities.ROCKET.create(level); - if (rocket != null) { - rocketUuid = rocket.getUUID(); - rocket.setPos(Vec3.atLowerCornerOf(worldPosition).add(getGunOffset(0))); - rocket.setYRot(yaw - 90); - rocket.setXRot(pitch); - level.addFreshEntity(rocket); - level.playSound(null, rocket, PortalCubedSounds.ROCKET_FIRE_EVENT, SoundSource.HOSTILE, 1, 1); - } - } + public void fire() { + if (level == null || level.isClientSide) { + PortalCubed.LOGGER.warn("RocketTurretBlockEntity.fire() should only be called on the server, not the client."); + return; + } + final RocketEntity rocket = PortalCubedEntities.ROCKET.create(level); + if (rocket != null) { + rocketUuid = rocket.getUUID(); + rocket.setPos(Vec3.atLowerCornerOf(worldPosition).add(getGunOffset(0))); + rocket.setYRot(yaw - 90); + rocket.setXRot(pitch); + level.addFreshEntity(rocket); + level.playSound(null, rocket, PortalCubedSounds.ROCKET_FIRE_EVENT, SoundSource.HOSTILE, 1, 1); + } + } - private void syncLockedTicks() { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBlockPos(worldPosition); - buf.writeByte(UPDATE_LOCKED_TICKS); - buf.writeVarInt(lockedTicks); - sendSyncPacket(buf); - } + private void syncLockedTicks() { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBlockPos(worldPosition); + buf.writeByte(UPDATE_LOCKED_TICKS); + buf.writeVarInt(lockedTicks); + sendSyncPacket(buf); + } - private void syncAngle() { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBlockPos(worldPosition); - buf.writeByte(UPDATE_ANGLE); - buf.writeFloat(yaw); - buf.writeFloat(pitch); - sendSyncPacket(buf); - } + private void syncAngle() { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBlockPos(worldPosition); + buf.writeByte(UPDATE_ANGLE); + buf.writeFloat(yaw); + buf.writeFloat(pitch); + sendSyncPacket(buf); + } - private void sendSyncPacket(FriendlyByteBuf buf) { - if (level == null || level.isClientSide) { - PortalCubed.LOGGER.warn("Shouldn't have called sendSyncPacket from the client"); - return; - } - final ServerLevel serverWorld = (ServerLevel)level; - final int viewDistance = serverWorld.getServer().getPlayerList().getViewDistance() * 16 + 1; - for (final ServerPlayer player : serverWorld.players()) { - if (player.blockPosition().closerThan(getBlockPos(), viewDistance)) { - ServerPlayNetworking.send(player, PortalCubedClientPackets.ROCKET_TURRET_UPDATE_PACKET, buf); - } - } - } + private void sendSyncPacket(FriendlyByteBuf buf) { + if (level == null || level.isClientSide) { + PortalCubed.LOGGER.warn("Shouldn't have called sendSyncPacket from the client"); + return; + } + final ServerLevel serverWorld = (ServerLevel)level; + final int viewDistance = serverWorld.getServer().getPlayerList().getViewDistance() * 16 + 1; + for (final ServerPlayer player : serverWorld.players()) { + if (player.blockPosition().closerThan(getBlockPos(), viewDistance)) { + ServerPlayNetworking.send(player, PortalCubedClientPackets.ROCKET_TURRET_UPDATE_PACKET, buf); + } + } + } - public State getState() { - if (lockedTicks == 0) { - return State.SEARCHING; - } - if (lockedTicks <= LOCK_TICKS) { - return State.LOCKED; - } - return State.FIRING; - } + public State getState() { + if (lockedTicks == 0) { + return State.SEARCHING; + } + if (lockedTicks <= LOCK_TICKS) { + return State.LOCKED; + } + return State.FIRING; + } - @Override - public void tick(Level world, BlockPos pos, BlockState state) { - super.tick(world, pos, state); - if (powered == null) { - powered = state.getValue(POWERED); - if (!powered) { - deactivatingAnimation.start(getAge() - 41); - } - } else if (powered != state.getValue(POWERED)) { - powered = !powered; - if (powered) { - opening = 0; - deactivatingAnimation.stop(); - activatingAnimation.start(getAge()); - closing = false; - } else { - lockedTicks = 0; - closing = true; - } - return; - } - if (opening >= 0 && opening < 80) { - opening++; - return; - } else if (closing) { - if (Math.abs(yaw) > 5 || Math.abs(pitch) > 5) { - setYaw(Mth.rotLerp(0.05f, yaw, 0)); - setPitch(Mth.rotLerp(0.05f, pitch, 0)); - } else { - yaw = 0; - pitch = 0; - activatingAnimation.stop(); - deactivatingAnimation.start(getAge()); - closing = false; - } - } - if (!powered) { - if (world.isClientSide) { - aimDests = null; - } - setYaw(0); - setPitch(0); - return; - } - if (world.isClientSide) { - final Vec3 gunPos = Vec3.atLowerCornerOf(getBlockPos()).add(getGunOffset(0)); - //noinspection DataFlowIssue - aimDests = PortalDirectionUtils.raycast(world, new ClipContext( - gunPos, gunPos.add(Vec3.directionFromRotation(pitch, yaw - 90).scale(127)), - ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, - // We can pass null here because of CollisionContextMixin - null - )).rays().stream().map(r -> new Tuple<>(r.start(), r.end())).toList(); - return; - } - if (lockedTicks > 0) { - if (lockedTicks++ == LOCK_TICKS) { - fire(); - syncLockedTicks(); - } else { - if (destAngle != null) { - setYaw(Mth.rotLerp(0.05f, yaw, destAngle.y)); - setPitch(Mth.rotLerp(0.05f, pitch, destAngle.x)); - syncAngle(); - } - if (lockedTicks == 9) { - world.playSound(null, pos, PortalCubedSounds.ROCKET_LOCKED_EVENT, SoundSource.HOSTILE, 1f, 1f); - } else if ( - lockedTicks > LOCK_TICKS && - world instanceof ServerLevel serverWorld && - (lockedTicks > LOCK_TICKS + 200 || serverWorld.getEntity(rocketUuid) == null) - ) { - lockedTicks = 0; - rocketUuid = Util.NIL_UUID; - syncLockedTicks(); - } - } - return; - } - final BlockPos actualBody = getBlockPos().above(); - final Vec3 eye = Vec3.upFromBottomCenterOf(actualBody, GUN_OFFSET.y - 1); - //noinspection DataFlowIssue - final LivingEntity player = world.getNearestEntity( - LivingEntity.class, - TargetingConditions.forCombat().selector(e -> !(e instanceof CorePhysicsEntity) && e.level().clip(new ClipContext( - eye, e.position().with(Direction.Axis.Y, e.getY(0.5)), ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, null - )).getType() == HitResult.Type.MISS), - null, - pos.getX(), pos.getY(), pos.getZ(), - AABB.ofSize(eye, 128, 128, 128) - ); - if (player != null) { - final Vec3 offset = player.position() - .with(Direction.Axis.Y, player.getY(0.5)) - .subtract( - Vec3.atLowerCornerOf(pos) - .add(getGunOffset(0)) - ); - destAngle = GeneralUtil.normalToRotation(offset); - destAngle = new Vec2(destAngle.x, destAngle.y + 90); - } else if (destAngle != null) { - destAngle = new Vec2(0, destAngle.y); - } else return; - setYaw(Mth.rotLerp(0.05f, yaw, destAngle.y)); - setPitch(Mth.rotLerp(0.05f, pitch, destAngle.x)); - if (player != null && Math.abs(yaw - destAngle.y) <= 1 && Math.abs(pitch - destAngle.x) <= 1) { - lockedTicks++; - syncLockedTicks(); - world.playSound(null, pos, PortalCubedSounds.ROCKET_LOCKING_EVENT, SoundSource.HOSTILE, 1f, 1f); - } - syncAngle(); - } + @Override + public void tick(Level world, BlockPos pos, BlockState state) { + super.tick(world, pos, state); + if (powered == null) { + powered = state.getValue(POWERED); + if (!powered) { + deactivatingAnimation.start(getAge() - 41); + } + } else if (powered != state.getValue(POWERED)) { + powered = !powered; + if (powered) { + opening = 0; + deactivatingAnimation.stop(); + activatingAnimation.start(getAge()); + closing = false; + } else { + lockedTicks = 0; + closing = true; + } + return; + } + if (opening >= 0 && opening < 80) { + opening++; + return; + } else if (closing) { + if (Math.abs(yaw) > 5 || Math.abs(pitch) > 5) { + setYaw(Mth.rotLerp(0.05f, yaw, 0)); + setPitch(Mth.rotLerp(0.05f, pitch, 0)); + } else { + yaw = 0; + pitch = 0; + activatingAnimation.stop(); + deactivatingAnimation.start(getAge()); + closing = false; + } + } + if (!powered) { + if (world.isClientSide) { + aimDests = null; + } + setYaw(0); + setPitch(0); + return; + } + if (world.isClientSide) { + final Vec3 gunPos = Vec3.atLowerCornerOf(getBlockPos()).add(getGunOffset(0)); + //noinspection DataFlowIssue + aimDests = PortalDirectionUtils.raycast(world, new ClipContext( + gunPos, gunPos.add(Vec3.directionFromRotation(pitch, yaw - 90).scale(127)), + ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, + // We can pass null here because of CollisionContextMixin + null + )).rays().stream().map(r -> new Tuple<>(r.start(), r.end())).toList(); + return; + } + if (lockedTicks > 0) { + if (lockedTicks++ == LOCK_TICKS) { + fire(); + syncLockedTicks(); + } else { + if (destAngle != null) { + setYaw(Mth.rotLerp(0.05f, yaw, destAngle.y)); + setPitch(Mth.rotLerp(0.05f, pitch, destAngle.x)); + syncAngle(); + } + if (lockedTicks == 9) { + world.playSound(null, pos, PortalCubedSounds.ROCKET_LOCKED_EVENT, SoundSource.HOSTILE, 1f, 1f); + } else if ( + lockedTicks > LOCK_TICKS && + world instanceof ServerLevel serverWorld && + (lockedTicks > LOCK_TICKS + 200 || serverWorld.getEntity(rocketUuid) == null) + ) { + lockedTicks = 0; + rocketUuid = Util.NIL_UUID; + syncLockedTicks(); + } + } + return; + } + final BlockPos actualBody = getBlockPos().above(); + final Vec3 eye = Vec3.upFromBottomCenterOf(actualBody, GUN_OFFSET.y - 1); + //noinspection DataFlowIssue + final LivingEntity player = world.getNearestEntity( + LivingEntity.class, + TargetingConditions.forCombat().selector(e -> !(e instanceof CorePhysicsEntity) && e.level().clip(new ClipContext( + eye, e.position().with(Direction.Axis.Y, e.getY(0.5)), ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, null + )).getType() == HitResult.Type.MISS), + null, + pos.getX(), pos.getY(), pos.getZ(), + AABB.ofSize(eye, 128, 128, 128) + ); + if (player != null) { + final Vec3 offset = player.position() + .with(Direction.Axis.Y, player.getY(0.5)) + .subtract( + Vec3.atLowerCornerOf(pos) + .add(getGunOffset(0)) + ); + destAngle = GeneralUtil.normalToRotation(offset); + destAngle = new Vec2(destAngle.x, destAngle.y + 90); + } else if (destAngle != null) { + destAngle = new Vec2(0, destAngle.y); + } else return; + setYaw(Mth.rotLerp(0.05f, yaw, destAngle.y)); + setPitch(Mth.rotLerp(0.05f, pitch, destAngle.x)); + if (player != null && Math.abs(yaw - destAngle.y) <= 1 && Math.abs(pitch - destAngle.x) <= 1) { + lockedTicks++; + syncLockedTicks(); + world.playSound(null, pos, PortalCubedSounds.ROCKET_LOCKING_EVENT, SoundSource.HOSTILE, 1f, 1f); + } + syncAngle(); + } - public Vec3 getGunOffset(float tickDelta) { - return GUN_OFFSET - .add(-0.3, -1.475, -0.5) - .zRot((float)Math.toRadians(Mth.rotLerp(tickDelta, prevPitch, pitch))) - .add(-0.2, -0.025, 0.0) - .yRot((float)Math.toRadians(-Mth.rotLerp(tickDelta, prevYaw, yaw))) - .add(0.5, 1.5, 0.5); - } + public Vec3 getGunOffset(float tickDelta) { + return GUN_OFFSET + .add(-0.3, -1.475, -0.5) + .zRot((float)Math.toRadians(Mth.rotLerp(tickDelta, prevPitch, pitch))) + .add(-0.2, -0.025, 0.0) + .yRot((float)Math.toRadians(-Mth.rotLerp(tickDelta, prevYaw, yaw))) + .add(0.5, 1.5, 0.5); + } - public enum State { - SEARCHING, - LOCKED, - FIRING - } + public enum State { + SEARCHING, + LOCKED, + FIRING + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/VelocityHelperBlockEntity.java b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/VelocityHelperBlockEntity.java index 448d0b35..e3118f4a 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/VelocityHelperBlockEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/blockentities/VelocityHelperBlockEntity.java @@ -30,168 +30,168 @@ import java.util.function.ToDoubleFunction; public class VelocityHelperBlockEntity extends BlockEntity implements ExtendedScreenHandlerFactory { - private static final List OPERATORS = List.of( - newOp("!", 1, false, Operator.PRECEDENCE_UNARY_MINUS, d -> d[0] == 0 ? 1 : 0), - newOp("<", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] < d[1] ? 1 : 0), - newOp("<=", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] <= d[1] ? 1 : 0), - newOp(">", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] > d[1] ? 1 : 0), - newOp(">=", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] >= d[1] ? 1 : 0), - newOp("==", 2, true, Operator.PRECEDENCE_ADDITION - 2, d -> d[0] == d[1] ? 1 : 0), - newOp("!=", 2, true, Operator.PRECEDENCE_ADDITION - 2, d -> d[0] != d[1] ? 1 : 0), - newOp("&", 2, true, Operator.PRECEDENCE_ADDITION - 3, d -> (d[0] != 0 && d[1] != 0) ? 1 : 0), - newOp("^", 2, true, Operator.PRECEDENCE_ADDITION - 4, d -> Math.pow(d[0], d[1])), - newOp("|", 2, true, Operator.PRECEDENCE_ADDITION - 5, d -> (d[0] != 0 | d[1] != 0) ? 1 : 0) - ); - - private static final String DEFAULT_IC_STRING = "x"; - private static final Expression DEFAULT_IC = parseExpression(DEFAULT_IC_STRING, "x"); - - private static final String DEFAULT_CONDITION_STRING = "1"; - private static final Expression DEFAULT_CONDITION = parseExpression(DEFAULT_CONDITION_STRING, "x", "y", "z"); - - @Nullable - private BlockPos destination = null; - - private String interpolationCurveString = DEFAULT_IC_STRING; - private Expression interpolationCurve = DEFAULT_IC; - - private String conditionString = DEFAULT_CONDITION_STRING; - private Expression condition = DEFAULT_CONDITION; - - private int flightDuration = 40; - - public VelocityHelperBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { - super(type, pos, state); - } - - public VelocityHelperBlockEntity(BlockPos pos, BlockState state) { - this(PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY, pos, state); - } - - @Override - public void load(CompoundTag nbt) { - final int[] destinationData = nbt.getIntArray("Destination"); - if (destinationData.length >= 3) { - destination = new BlockPos(destinationData[0], destinationData[1], destinationData[2]); - } else { - destination = null; - } - setInterpolationCurve(nbt.getString("InterpolationCurve")); - setCondition(nbt.getString("Condition")); - flightDuration = nbt.getInt("FlightDuration"); - } - - @Override - protected void saveAdditional(CompoundTag nbt) { - if (destination != null) { - nbt.put("Destination", new IntArrayTag(new int[] { - destination.getX(), - destination.getY(), - destination.getZ() - })); - } - nbt.putString("InterpolationCurve", interpolationCurveString); - nbt.putString("Condition", conditionString); - nbt.putInt("FlightDuration", flightDuration); - } - - @NotNull - @Override - public CompoundTag getUpdateTag() { - return saveWithoutMetadata(); - } - - @Nullable - @Override - public Packet getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this); - } - - @Nullable - public BlockPos getDestination() { - return destination; - } - - public void setDestination(@Nullable BlockPos destination) { - this.destination = destination; - } - - public Expression getInterpolationCurve() { - return interpolationCurve; - } - - public String getInterpolationCurveString() { - return interpolationCurveString; - } - - public void setInterpolationCurve(String curve) { - final boolean reparse = !interpolationCurveString.equals(curve); - interpolationCurveString = curve; - if (reparse) { - interpolationCurve = parseExpression(curve, "x"); - } - } - - public Expression getCondition() { - return condition; - } - - public String getConditionString() { - return conditionString; - } - - public void setCondition(String condition) { - final boolean reparse = !conditionString.equals(condition); - conditionString = condition; - if (reparse) { - this.condition = parseExpression(condition, "x", "y", "z"); - } - } - - public int getFlightDuration() { - return flightDuration; - } - - public void setFlightDuration(int flightDuration) { - this.flightDuration = flightDuration; - } - - public void updateListeners() { - setChanged(); - assert level != null; - level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); - } - - @NotNull - @Override - public Component getDisplayName() { - return Component.translatable(getBlockState().getBlock().getDescriptionId()); - } - - @Nullable - @Override - public AbstractContainerMenu createMenu(int syncId, Inventory playerInventory, Player playerEntity) { - return new BlockPosScreenHandler(PortalCubed.VELOCITY_HELPER_SCREEN_HANDLER, syncId, getBlockPos()); - } - - @Override - public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { - buf.writeBlockPos(getBlockPos()); - } - - public static Expression parseExpression(String expression, String... variables) { - return new ExpressionBuilder(expression) - .operator(OPERATORS) - .variables(variables) - .build(); - } - - private static Operator newOp(String symbol, int numberOfOperands, boolean leftAssociative, int precedence, ToDoubleFunction op) { - return new Operator(symbol, numberOfOperands, leftAssociative, precedence) { - @Override - public double apply(double... args) { - return op.applyAsDouble(args); - } - }; - } + private static final List OPERATORS = List.of( + newOp("!", 1, false, Operator.PRECEDENCE_UNARY_MINUS, d -> d[0] == 0 ? 1 : 0), + newOp("<", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] < d[1] ? 1 : 0), + newOp("<=", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] <= d[1] ? 1 : 0), + newOp(">", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] > d[1] ? 1 : 0), + newOp(">=", 2, true, Operator.PRECEDENCE_ADDITION - 1, d -> d[0] >= d[1] ? 1 : 0), + newOp("==", 2, true, Operator.PRECEDENCE_ADDITION - 2, d -> d[0] == d[1] ? 1 : 0), + newOp("!=", 2, true, Operator.PRECEDENCE_ADDITION - 2, d -> d[0] != d[1] ? 1 : 0), + newOp("&", 2, true, Operator.PRECEDENCE_ADDITION - 3, d -> (d[0] != 0 && d[1] != 0) ? 1 : 0), + newOp("^", 2, true, Operator.PRECEDENCE_ADDITION - 4, d -> Math.pow(d[0], d[1])), + newOp("|", 2, true, Operator.PRECEDENCE_ADDITION - 5, d -> (d[0] != 0 | d[1] != 0) ? 1 : 0) + ); + + private static final String DEFAULT_IC_STRING = "x"; + private static final Expression DEFAULT_IC = parseExpression(DEFAULT_IC_STRING, "x"); + + private static final String DEFAULT_CONDITION_STRING = "1"; + private static final Expression DEFAULT_CONDITION = parseExpression(DEFAULT_CONDITION_STRING, "x", "y", "z"); + + @Nullable + private BlockPos destination = null; + + private String interpolationCurveString = DEFAULT_IC_STRING; + private Expression interpolationCurve = DEFAULT_IC; + + private String conditionString = DEFAULT_CONDITION_STRING; + private Expression condition = DEFAULT_CONDITION; + + private int flightDuration = 40; + + public VelocityHelperBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + } + + public VelocityHelperBlockEntity(BlockPos pos, BlockState state) { + this(PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY, pos, state); + } + + @Override + public void load(CompoundTag nbt) { + final int[] destinationData = nbt.getIntArray("Destination"); + if (destinationData.length >= 3) { + destination = new BlockPos(destinationData[0], destinationData[1], destinationData[2]); + } else { + destination = null; + } + setInterpolationCurve(nbt.getString("InterpolationCurve")); + setCondition(nbt.getString("Condition")); + flightDuration = nbt.getInt("FlightDuration"); + } + + @Override + protected void saveAdditional(CompoundTag nbt) { + if (destination != null) { + nbt.put("Destination", new IntArrayTag(new int[] { + destination.getX(), + destination.getY(), + destination.getZ() + })); + } + nbt.putString("InterpolationCurve", interpolationCurveString); + nbt.putString("Condition", conditionString); + nbt.putInt("FlightDuration", flightDuration); + } + + @NotNull + @Override + public CompoundTag getUpdateTag() { + return saveWithoutMetadata(); + } + + @Nullable + @Override + public Packet getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } + + @Nullable + public BlockPos getDestination() { + return destination; + } + + public void setDestination(@Nullable BlockPos destination) { + this.destination = destination; + } + + public Expression getInterpolationCurve() { + return interpolationCurve; + } + + public String getInterpolationCurveString() { + return interpolationCurveString; + } + + public void setInterpolationCurve(String curve) { + final boolean reparse = !interpolationCurveString.equals(curve); + interpolationCurveString = curve; + if (reparse) { + interpolationCurve = parseExpression(curve, "x"); + } + } + + public Expression getCondition() { + return condition; + } + + public String getConditionString() { + return conditionString; + } + + public void setCondition(String condition) { + final boolean reparse = !conditionString.equals(condition); + conditionString = condition; + if (reparse) { + this.condition = parseExpression(condition, "x", "y", "z"); + } + } + + public int getFlightDuration() { + return flightDuration; + } + + public void setFlightDuration(int flightDuration) { + this.flightDuration = flightDuration; + } + + public void updateListeners() { + setChanged(); + assert level != null; + level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); + } + + @NotNull + @Override + public Component getDisplayName() { + return Component.translatable(getBlockState().getBlock().getDescriptionId()); + } + + @Nullable + @Override + public AbstractContainerMenu createMenu(int syncId, Inventory playerInventory, Player playerEntity) { + return new BlockPosScreenHandler(PortalCubed.VELOCITY_HELPER_SCREEN_HANDLER, syncId, getBlockPos()); + } + + @Override + public void writeScreenOpeningData(ServerPlayer player, FriendlyByteBuf buf) { + buf.writeBlockPos(getBlockPos()); + } + + public static Expression parseExpression(String expression, String... variables) { + return new ExpressionBuilder(expression) + .operator(OPERATORS) + .variables(variables) + .build(); + } + + private static Operator newOp(String symbol, int numberOfOperands, boolean leftAssociative, int precedence, ToDoubleFunction op) { + return new Operator(symbol, numberOfOperands, leftAssociative, precedence) { + @Override + public double apply(double... args) { + return op.applyAsDouble(args); + } + }; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/Edge.java b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/Edge.java index f35f37d6..465aaa55 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/Edge.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/Edge.java @@ -14,96 +14,96 @@ import java.util.Map; public enum Edge implements StringRepresentable { - LEFT, RIGHT, DOWN, UP; + LEFT, RIGHT, DOWN, UP; - private final Map facingToAsDirection = new HashMap<>(); + private final Map facingToAsDirection = new HashMap<>(); - public final String serialized = name().toLowerCase(Locale.ROOT); + public final String serialized = name().toLowerCase(Locale.ROOT); - public Edge getClockwise() { - return switch (this) { - case LEFT -> UP; - case DOWN -> LEFT; - case RIGHT -> DOWN; - case UP -> RIGHT; - }; - } + public Edge getClockwise() { + return switch (this) { + case LEFT -> UP; + case DOWN -> LEFT; + case RIGHT -> DOWN; + case UP -> RIGHT; + }; + } - public Edge getCounterClockwise() { - return switch (this) { - case LEFT -> DOWN; - case DOWN -> RIGHT; - case RIGHT -> UP; - case UP -> LEFT; - }; - } + public Edge getCounterClockwise() { + return switch (this) { + case LEFT -> DOWN; + case DOWN -> RIGHT; + case RIGHT -> UP; + case UP -> LEFT; + }; + } - public Edge getOpposite() { - return getClockwise().getClockwise(); - } + public Edge getOpposite() { + return getClockwise().getClockwise(); + } - public Direction toDirection(Direction facing) { - return facingToAsDirection.computeIfAbsent(facing, $ -> { - Axis axis = facing.getAxis(); - Direction currentDirection = getDownOf(facing); - Edge edge = DOWN; - for (int i = 0; i < 4; i++) { - if (edge == this) - return currentDirection; - currentDirection = facing == Direction.UP ? currentDirection.getClockWise(axis) : currentDirection.getCounterClockWise(axis); - edge = edge.getCounterClockwise(); - } - throw new IllegalStateException(); - }); - } + public Direction toDirection(Direction facing) { + return facingToAsDirection.computeIfAbsent(facing, $ -> { + Axis axis = facing.getAxis(); + Direction currentDirection = getDownOf(facing); + Edge edge = DOWN; + for (int i = 0; i < 4; i++) { + if (edge == this) + return currentDirection; + currentDirection = facing == Direction.UP ? currentDirection.getClockWise(axis) : currentDirection.getCounterClockWise(axis); + edge = edge.getCounterClockwise(); + } + throw new IllegalStateException(); + }); + } - public Vec3 offsetTowards(Vec3 pos, Direction facing, double amount) { - Direction direction = toDirection(facing); - Vec3 normal = Vec3.atLowerCornerOf(direction.getNormal()); - Vec3 offset = normal.scale(amount); - return pos.add(offset); - } + public Vec3 offsetTowards(Vec3 pos, Direction facing, double amount) { + Direction direction = toDirection(facing); + Vec3 normal = Vec3.atLowerCornerOf(direction.getNormal()); + Vec3 offset = normal.scale(amount); + return pos.add(offset); + } - @Override - @NotNull - public String getSerializedName() { - return serialized; - } + @Override + @NotNull + public String getSerializedName() { + return serialized; + } - @Override - public String toString() { - return serialized; - } + @Override + public String toString() { + return serialized; + } - public static Edge fromFacingAndSide(Direction facing, Direction side) { - Axis axis = facing.getAxis(); - if (axis == side.getAxis()) - throw new IllegalArgumentException("facing and side cannot share an axis"); - // start with down, rotate around until side matches - Direction currentSide = getDownOf(facing); - Edge edge = DOWN; - for (int i = 0; i < 4; i++) { - if (currentSide == side) - return edge; - currentSide = facing == Direction.UP ? currentSide.getClockWise(axis) : currentSide.getCounterClockWise(axis); - edge = edge.getCounterClockwise(); - } - throw new IllegalStateException(); - } + public static Edge fromFacingAndSide(Direction facing, Direction side) { + Axis axis = facing.getAxis(); + if (axis == side.getAxis()) + throw new IllegalArgumentException("facing and side cannot share an axis"); + // start with down, rotate around until side matches + Direction currentSide = getDownOf(facing); + Edge edge = DOWN; + for (int i = 0; i < 4; i++) { + if (currentSide == side) + return edge; + currentSide = facing == Direction.UP ? currentSide.getClockWise(axis) : currentSide.getCounterClockWise(axis); + edge = edge.getCounterClockwise(); + } + throw new IllegalStateException(); + } - public static Edge teleport(Edge edge, Portal from, Direction fromFacing, Direction toFacing) { - Vec3 edgeNormal = Vec3.atLowerCornerOf(edge.toDirection(fromFacing).getNormal()); - Vector3f otherEdgeNormal = PortalDirectionUtils.rotateVector(from, edgeNormal).toVector3f(); - Direction otherEdgeDirection = Direction.fromDelta(Math.round(otherEdgeNormal.x), Math.round(otherEdgeNormal.y), Math.round(otherEdgeNormal.z)); - if (otherEdgeDirection == null) - otherEdgeDirection = Direction.getNearest(otherEdgeNormal.x, otherEdgeNormal.y, otherEdgeNormal.z); - return fromFacingAndSide(toFacing, otherEdgeDirection); - } + public static Edge teleport(Edge edge, Portal from, Direction fromFacing, Direction toFacing) { + Vec3 edgeNormal = Vec3.atLowerCornerOf(edge.toDirection(fromFacing).getNormal()); + Vector3f otherEdgeNormal = PortalDirectionUtils.rotateVector(from, edgeNormal).toVector3f(); + Direction otherEdgeDirection = Direction.fromDelta(Math.round(otherEdgeNormal.x), Math.round(otherEdgeNormal.y), Math.round(otherEdgeNormal.z)); + if (otherEdgeDirection == null) + otherEdgeDirection = Direction.getNearest(otherEdgeNormal.x, otherEdgeNormal.y, otherEdgeNormal.z); + return fromFacingAndSide(toFacing, otherEdgeDirection); + } - private static Direction getDownOf(Direction facing) { - if (facing.getAxis().isHorizontal()) { - return Direction.DOWN; - } - return facing == Direction.UP ? Direction.NORTH : Direction.SOUTH; - } + private static Direction getDownOf(Direction facing) { + if (facing.getAxis().isHorizontal()) { + return Direction.DOWN; + } + return facing == Direction.UP ? Direction.NORTH : Direction.SOUTH; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeBlock.java index 64d3b080..628735df 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeBlock.java @@ -24,142 +24,142 @@ import java.util.Map; public class HardLightBridgeBlock extends Block implements HardLightBridgePart { - public static final VoxelShape BASE_SHAPE_DOWN = Block.box(2, 1, 0, 14, 2, 16); - public static final VoxelShape BASE_SHAPE_RIGHT = Block.box(1, 2, 0, 2, 14, 16); - public static final VoxelShape BASE_SHAPE_UP = Block.box(2, 14, 0, 14, 15, 16); - public static final VoxelShape BASE_SHAPE_LEFT = Block.box(14, 2, 0, 15, 14, 16); - - public static final Map SHAPERS = Util.make(new HashMap<>(), map -> { - map.put(Edge.DOWN, VoxelShaper.forDirectional(BASE_SHAPE_DOWN, Direction.SOUTH)); - map.put(Edge.RIGHT, VoxelShaper.forDirectional(BASE_SHAPE_RIGHT, Direction.SOUTH)); - map.put(Edge.UP, VoxelShaper.forDirectional(BASE_SHAPE_UP, Direction.SOUTH)); - map.put(Edge.LEFT, VoxelShaper.forDirectional(BASE_SHAPE_LEFT, Direction.SOUTH)); - }); - - private static final Map SHAPES = new HashMap<>(); - - public HardLightBridgeBlock(Properties settings) { - super(settings); - this.registerDefaultState( - stateDefinition.any() - .setValue(EDGE, Edge.DOWN) - .setValue(FACING, Direction.SOUTH) - ); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(EDGE, FACING); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPES.computeIfAbsent(state, HardLightBridgeBlock::makeShape); - } - - @SuppressWarnings("deprecation") - @Override - public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - boolean supported = hasSupportingBlockBehind(level, pos, state.getValue(FACING), state.getValue(EDGE), (behind, facing, edge) -> { - if (behind.is(this) || behind.is(PortalCubedBlocks.HLB_EMITTER_BLOCK)) { - return behind.getValue(FACING) == facing && behind.getValue(EDGE) == edge; - } - return false; - }); - if (!supported) - level.destroyBlock(pos, false); - } - - @SuppressWarnings("deprecation") - @Override - public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { - if (level instanceof ServerLevel serverLevel && !HardLightBridgeEmitterBlock.suppressUpdates) - HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, false); - } - - @SuppressWarnings("deprecation") - @Override - public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { - if (!(level instanceof ServerLevel serverLevel) || HardLightBridgeEmitterBlock.suppressUpdates) - return; - Direction facing = state.getValue(FACING); - if (!pos.relative(facing).equals(fromPos)) - return; // only care about pos in front - BlockState newState = level.getBlockState(fromPos); - if (!newState.isAir()) // removed, try to extend - return; - HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, true); - } - - @SuppressWarnings("deprecation") - @Override - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - if (stateFrom.is(this) || stateFrom.is(PortalCubedBlocks.HLB_EMITTER_BLOCK)) { - return stateFrom.getValue(FACING) == state.getValue(FACING); - } - return false; - } - - static VoxelShape makeShape(BlockState state) { - Direction facing = state.getValue(FACING); - Edge edge = state.getValue(EDGE); - if (facing.getAxis().isVertical()) - edge = edge.getOpposite(); - return SHAPERS.get(edge).get(facing); - } - - @Override - public void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { - Direction facing = state.getValue(FACING); - if (facing != portal.getFacingDirection().getOpposite()) - return; - // propagate through - HardLightBridgeEmitterBlock.updateEmission(level, state, pos, true); - } - - @Override - public void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { - Direction facing = state.getValue(FACING); - if (facing == portal.getFacingDirection()) { // portal is behind, remove bridge since support is gone - BlockPos start = pos.relative(facing.getOpposite()); - HardLightBridgeEmitterBlock.updateEmission(level, state, start, false); - } else if (facing == portal.getFacingDirection().getOpposite()) { // portal in front, remove bridge on other side. - HardLightBridgeEmitterBlock.updateEmission(level, state, pos, false); - } - // else: don't care - } - - public static boolean hasSupportingBlockBehind(Level level, BlockPos pos, Direction facing, Edge edge, SupportTest test) { - Direction back = facing.getOpposite(); - BlockState behind = level.getBlockState(pos.relative(back)); - if (test.test(behind, facing, edge)) - return true; - // check through portals. - for (Portal portal : level.getEntitiesOfClass(Portal.class, new AABB(pos), Portal::isGridAligned)) { - Direction portalFacing = portal.getFacingDirection(); - if (portalFacing != facing) - continue; - Portal linked = portal.findLinkedPortal(); - if (linked == null) - continue; - Direction linkedFacing = linked.getFacingDirection(); - Vec3 portalToPos = Vec3.atCenterOf(pos).subtract(portal.getOriginPos()) - .with(portalFacing.getAxis(), 0); // fixme: this override is needed because the rotated offset is negated. why??? - Vec3 linkedToOtherPos = PortalDirectionUtils.rotateVector(portal, portalToPos) - .with(linkedFacing.getAxis(), linkedFacing.getAxisDirection().getStep() / 2f); - BlockPos otherSide = BlockPos.containing(linked.getOriginPos().add(linkedToOtherPos)); - BlockState otherSideState = level.getBlockState(otherSide); - Direction otherSideFacing = linkedFacing.getOpposite(); - Edge otherSideEdge = Edge.teleport(edge, portal, facing, otherSideFacing); - if (test.test(otherSideState, otherSideFacing, otherSideEdge)) - return true; - } - return false; - } - - public interface SupportTest { - boolean test(BlockState behind, Direction facing, Edge edge); - } + public static final VoxelShape BASE_SHAPE_DOWN = Block.box(2, 1, 0, 14, 2, 16); + public static final VoxelShape BASE_SHAPE_RIGHT = Block.box(1, 2, 0, 2, 14, 16); + public static final VoxelShape BASE_SHAPE_UP = Block.box(2, 14, 0, 14, 15, 16); + public static final VoxelShape BASE_SHAPE_LEFT = Block.box(14, 2, 0, 15, 14, 16); + + public static final Map SHAPERS = Util.make(new HashMap<>(), map -> { + map.put(Edge.DOWN, VoxelShaper.forDirectional(BASE_SHAPE_DOWN, Direction.SOUTH)); + map.put(Edge.RIGHT, VoxelShaper.forDirectional(BASE_SHAPE_RIGHT, Direction.SOUTH)); + map.put(Edge.UP, VoxelShaper.forDirectional(BASE_SHAPE_UP, Direction.SOUTH)); + map.put(Edge.LEFT, VoxelShaper.forDirectional(BASE_SHAPE_LEFT, Direction.SOUTH)); + }); + + private static final Map SHAPES = new HashMap<>(); + + public HardLightBridgeBlock(Properties settings) { + super(settings); + this.registerDefaultState( + stateDefinition.any() + .setValue(EDGE, Edge.DOWN) + .setValue(FACING, Direction.SOUTH) + ); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(EDGE, FACING); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPES.computeIfAbsent(state, HardLightBridgeBlock::makeShape); + } + + @SuppressWarnings("deprecation") + @Override + public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { + boolean supported = hasSupportingBlockBehind(level, pos, state.getValue(FACING), state.getValue(EDGE), (behind, facing, edge) -> { + if (behind.is(this) || behind.is(PortalCubedBlocks.HLB_EMITTER_BLOCK)) { + return behind.getValue(FACING) == facing && behind.getValue(EDGE) == edge; + } + return false; + }); + if (!supported) + level.destroyBlock(pos, false); + } + + @SuppressWarnings("deprecation") + @Override + public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { + if (level instanceof ServerLevel serverLevel && !HardLightBridgeEmitterBlock.suppressUpdates) + HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, false); + } + + @SuppressWarnings("deprecation") + @Override + public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { + if (!(level instanceof ServerLevel serverLevel) || HardLightBridgeEmitterBlock.suppressUpdates) + return; + Direction facing = state.getValue(FACING); + if (!pos.relative(facing).equals(fromPos)) + return; // only care about pos in front + BlockState newState = level.getBlockState(fromPos); + if (!newState.isAir()) // removed, try to extend + return; + HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, true); + } + + @SuppressWarnings("deprecation") + @Override + public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { + if (stateFrom.is(this) || stateFrom.is(PortalCubedBlocks.HLB_EMITTER_BLOCK)) { + return stateFrom.getValue(FACING) == state.getValue(FACING); + } + return false; + } + + static VoxelShape makeShape(BlockState state) { + Direction facing = state.getValue(FACING); + Edge edge = state.getValue(EDGE); + if (facing.getAxis().isVertical()) + edge = edge.getOpposite(); + return SHAPERS.get(edge).get(facing); + } + + @Override + public void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { + Direction facing = state.getValue(FACING); + if (facing != portal.getFacingDirection().getOpposite()) + return; + // propagate through + HardLightBridgeEmitterBlock.updateEmission(level, state, pos, true); + } + + @Override + public void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { + Direction facing = state.getValue(FACING); + if (facing == portal.getFacingDirection()) { // portal is behind, remove bridge since support is gone + BlockPos start = pos.relative(facing.getOpposite()); + HardLightBridgeEmitterBlock.updateEmission(level, state, start, false); + } else if (facing == portal.getFacingDirection().getOpposite()) { // portal in front, remove bridge on other side. + HardLightBridgeEmitterBlock.updateEmission(level, state, pos, false); + } + // else: don't care + } + + public static boolean hasSupportingBlockBehind(Level level, BlockPos pos, Direction facing, Edge edge, SupportTest test) { + Direction back = facing.getOpposite(); + BlockState behind = level.getBlockState(pos.relative(back)); + if (test.test(behind, facing, edge)) + return true; + // check through portals. + for (Portal portal : level.getEntitiesOfClass(Portal.class, new AABB(pos), Portal::isGridAligned)) { + Direction portalFacing = portal.getFacingDirection(); + if (portalFacing != facing) + continue; + Portal linked = portal.findLinkedPortal(); + if (linked == null) + continue; + Direction linkedFacing = linked.getFacingDirection(); + Vec3 portalToPos = Vec3.atCenterOf(pos).subtract(portal.getOriginPos()) + .with(portalFacing.getAxis(), 0); // fixme: this override is needed because the rotated offset is negated. why??? + Vec3 linkedToOtherPos = PortalDirectionUtils.rotateVector(portal, portalToPos) + .with(linkedFacing.getAxis(), linkedFacing.getAxisDirection().getStep() / 2f); + BlockPos otherSide = BlockPos.containing(linked.getOriginPos().add(linkedToOtherPos)); + BlockState otherSideState = level.getBlockState(otherSide); + Direction otherSideFacing = linkedFacing.getOpposite(); + Edge otherSideEdge = Edge.teleport(edge, portal, facing, otherSideFacing); + if (test.test(otherSideState, otherSideFacing, otherSideEdge)) + return true; + } + return false; + } + + public interface SupportTest { + boolean test(BlockState behind, Direction facing, Edge edge); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeEmitterBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeEmitterBlock.java index ea759a67..3b79282c 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeEmitterBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgeEmitterBlock.java @@ -37,218 +37,218 @@ import java.util.Map; public class HardLightBridgeEmitterBlock extends Block implements HardLightBridgePart { - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - - public static final VoxelShape BASE_SHAPE_DOWN = Block.box(0, 0, 0, 16, 4, 4); - public static final VoxelShape BASE_SHAPE_RIGHT = Block.box(0, 0, 0, 4, 16, 4); - public static final VoxelShape BASE_SHAPE_UP = Block.box(0, 12, 0, 16, 16, 4); - public static final VoxelShape BASE_SHAPE_LEFT = Block.box(12, 0, 0, 16, 16, 4); - - public static final Map SHAPERS = Util.make(new HashMap<>(), map -> { - map.put(Edge.DOWN, VoxelShaper.forDirectional(BASE_SHAPE_DOWN, Direction.SOUTH)); - map.put(Edge.RIGHT, VoxelShaper.forDirectional(BASE_SHAPE_RIGHT, Direction.SOUTH)); - map.put(Edge.UP, VoxelShaper.forDirectional(BASE_SHAPE_UP, Direction.SOUTH)); - map.put(Edge.LEFT, VoxelShaper.forDirectional(BASE_SHAPE_LEFT, Direction.SOUTH)); - }); - - private static final Map SHAPES = new HashMap<>(); - - static boolean suppressUpdates; - - public HardLightBridgeEmitterBlock(Properties settings) { - super(settings); - registerDefaultState( - stateDefinition.any() - .setValue(EDGE, Edge.DOWN) - .setValue(FACING, Direction.SOUTH) - .setValue(POWERED, false) - ); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(EDGE, FACING, POWERED); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) - return InteractionResult.PASS; - if (!(level instanceof ServerLevel serverLevel)) - return InteractionResult.SUCCESS; - Edge edge = state.getValue(EDGE).getClockwise(); - BlockState newState = state.setValue(EDGE, edge); - level.setBlockAndUpdate(pos, newState); - updateEmission(serverLevel, newState, pos, newState.getValue(POWERED)); - return InteractionResult.SUCCESS; - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - Direction facing = ctx.getNearestLookingDirection().getOpposite(); - Edge edge = Edge.DOWN; - if (facing.getAxis().isHorizontal()) { - if (ctx.getClickLocation().y - ctx.getClickedPos().getY() > 0.5) - edge = Edge.UP; - } else { - Direction edgeSide = ctx.getHorizontalDirection(); - if (facing == Direction.UP) - edgeSide = edgeSide.getOpposite(); - edge = Edge.fromFacingAndSide(facing, edgeSide); - } - return defaultBlockState().setValue(FACING, facing).setValue(EDGE, edge); - } - - @SuppressWarnings("deprecation") - @Override - public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { - if (!(level instanceof ServerLevel serverLevel) || HardLightBridgeEmitterBlock.suppressUpdates) - return; - boolean update = false; - Direction facing = state.getValue(FACING); - if (pos.relative(facing).equals(fromPos)) { // pos in front - BlockState newState = level.getBlockState(fromPos); - if (newState.isAir()) // removed, try to extend - update = true; - } - - boolean powered = level.hasNeighborSignal(pos); - update |= powered != state.getValue(POWERED); - if (!update) - return; - BlockState newState = state.setValue(POWERED, powered); - level.setBlockAndUpdate(pos, newState); - updateEmission(serverLevel, newState, pos, powered); - } - - @SuppressWarnings("deprecation") - @Override - public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { - if (level instanceof ServerLevel serverLevel && !HardLightBridgeEmitterBlock.suppressUpdates && state.getValue(POWERED)) - HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, false); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return SHAPES.computeIfAbsent(state, HardLightBridgeEmitterBlock::makeShape); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); - } - - @SuppressWarnings("deprecation") - @Override - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - if (stateFrom.is(this) || stateFrom.is(PortalCubedBlocks.HLB_BLOCK)) { - return stateFrom.getValue(FACING) == state.getValue(FACING); - } - return false; - } - - public static void updateEmission(ServerLevel level, BlockState emitterState, BlockPos emitterPos, boolean powered) { - withUpdatesSuppressed(() -> { - Direction facing = emitterState.getValue(FACING); - Edge edge = emitterState.getValue(EDGE); - BlockState bridgeState = !powered ? Blocks.AIR.defaultBlockState() - : PortalCubedBlocks.HLB_BLOCK.defaultBlockState() - .setValue(FACING, facing).setValue(EDGE, edge); - - MutableBlockPos pos = emitterPos.mutable(); - distance: for (int i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { - pos.move(facing); - if (canPlaceBridge(level, pos, facing)) { - level.setBlockAndUpdate(pos, bridgeState); - } else { // hit a wall, check for portals - pos.move(facing.getOpposite()); // step back - AABB box = new AABB(pos); - List portals = level.getEntitiesOfClass(Portal.class, box); - for (Portal portal : portals) { - Direction portalFacing = portal.getFacingDirection(); - if (portalFacing.getOpposite() != facing) - continue; - Portal linked = portal.findLinkedPortal(); - if (linked == null) - continue; - if (!portal.snapToGrid() || !linked.snapToGrid()) - continue; - Vec3 bridgePos = edge.offsetTowards(Vec3.atCenterOf(pos), facing, 0.4); - Vec3 relative = bridgePos.subtract(portal.getOriginPos()); - Axis xAxis = Edge.RIGHT.toDirection(facing).getAxis(); - double x = relative.get(xAxis); - Axis yAxis = Edge.UP.toDirection(facing).getAxis(); - double y = relative.get(yAxis); - Vec3 linkedBase = linked.getPointInPlane(-x, -y); // negative??? - Vec3 linkedBridgePos = linkedBase.relative(linked.getFacingDirection(), 0.5); - - // successfully teleported. update stuff and continue propagating. - pos.set(linkedBridgePos.x, linkedBridgePos.y, linkedBridgePos.z); - edge = Edge.teleport(edge, portal, facing, linked.getFacingDirection()); - facing = linked.getFacingDirection(); - - pos.move(facing.getOpposite()); // step back, will move forward again on next loop - bridgeState = !powered ? Blocks.AIR.defaultBlockState() - : PortalCubedBlocks.HLB_BLOCK.defaultBlockState() - .setValue(FACING, facing).setValue(EDGE, edge); - continue distance; - } - return; // couldn't teleport - } - } - }); - } - - public static void withUpdatesSuppressed(Runnable runnable) { - try { - suppressUpdates = true; - runnable.run(); - } finally { - suppressUpdates = false; - } - } - - private static boolean canPlaceBridge(ServerLevel level, BlockPos pos, Direction facing) { - if (!level.isLoaded(pos)) - return false; - BlockState state = level.getBlockState(pos); - if (!state.is(PortalCubedBlocks.HLB_BLOCK)) - return state.isAir(); - return state.getValue(FACING) == facing; - } - - private static VoxelShape makeShape(BlockState state) { - Direction facing = state.getValue(FACING); - Edge edge = state.getValue(EDGE); - if (facing.getAxis().isVertical()) - edge = edge.getOpposite(); - VoxelShape shape = SHAPERS.get(edge).get(facing); - if (state.getValue(POWERED)) { - shape = Shapes.or(shape, HardLightBridgeBlock.makeShape(state)); - } - return shape; - } - - @Override - public void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { - Direction facing = state.getValue(FACING); - if (facing != portal.getFacingDirection().getOpposite()) - return; - // propagate through - HardLightBridgeEmitterBlock.updateEmission(level, state, pos, true); - } - - @Override - public void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { - Direction facing = state.getValue(FACING); - if (facing == portal.getFacingDirection().getOpposite()) { // portal in front, remove bridge on other side. - HardLightBridgeEmitterBlock.updateEmission(level, state, pos, false); - } - } + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + + public static final VoxelShape BASE_SHAPE_DOWN = Block.box(0, 0, 0, 16, 4, 4); + public static final VoxelShape BASE_SHAPE_RIGHT = Block.box(0, 0, 0, 4, 16, 4); + public static final VoxelShape BASE_SHAPE_UP = Block.box(0, 12, 0, 16, 16, 4); + public static final VoxelShape BASE_SHAPE_LEFT = Block.box(12, 0, 0, 16, 16, 4); + + public static final Map SHAPERS = Util.make(new HashMap<>(), map -> { + map.put(Edge.DOWN, VoxelShaper.forDirectional(BASE_SHAPE_DOWN, Direction.SOUTH)); + map.put(Edge.RIGHT, VoxelShaper.forDirectional(BASE_SHAPE_RIGHT, Direction.SOUTH)); + map.put(Edge.UP, VoxelShaper.forDirectional(BASE_SHAPE_UP, Direction.SOUTH)); + map.put(Edge.LEFT, VoxelShaper.forDirectional(BASE_SHAPE_LEFT, Direction.SOUTH)); + }); + + private static final Map SHAPES = new HashMap<>(); + + static boolean suppressUpdates; + + public HardLightBridgeEmitterBlock(Properties settings) { + super(settings); + registerDefaultState( + stateDefinition.any() + .setValue(EDGE, Edge.DOWN) + .setValue(FACING, Direction.SOUTH) + .setValue(POWERED, false) + ); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(EDGE, FACING, POWERED); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) + return InteractionResult.PASS; + if (!(level instanceof ServerLevel serverLevel)) + return InteractionResult.SUCCESS; + Edge edge = state.getValue(EDGE).getClockwise(); + BlockState newState = state.setValue(EDGE, edge); + level.setBlockAndUpdate(pos, newState); + updateEmission(serverLevel, newState, pos, newState.getValue(POWERED)); + return InteractionResult.SUCCESS; + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + Direction facing = ctx.getNearestLookingDirection().getOpposite(); + Edge edge = Edge.DOWN; + if (facing.getAxis().isHorizontal()) { + if (ctx.getClickLocation().y - ctx.getClickedPos().getY() > 0.5) + edge = Edge.UP; + } else { + Direction edgeSide = ctx.getHorizontalDirection(); + if (facing == Direction.UP) + edgeSide = edgeSide.getOpposite(); + edge = Edge.fromFacingAndSide(facing, edgeSide); + } + return defaultBlockState().setValue(FACING, facing).setValue(EDGE, edge); + } + + @SuppressWarnings("deprecation") + @Override + public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { + if (!(level instanceof ServerLevel serverLevel) || HardLightBridgeEmitterBlock.suppressUpdates) + return; + boolean update = false; + Direction facing = state.getValue(FACING); + if (pos.relative(facing).equals(fromPos)) { // pos in front + BlockState newState = level.getBlockState(fromPos); + if (newState.isAir()) // removed, try to extend + update = true; + } + + boolean powered = level.hasNeighborSignal(pos); + update |= powered != state.getValue(POWERED); + if (!update) + return; + BlockState newState = state.setValue(POWERED, powered); + level.setBlockAndUpdate(pos, newState); + updateEmission(serverLevel, newState, pos, powered); + } + + @SuppressWarnings("deprecation") + @Override + public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { + if (level instanceof ServerLevel serverLevel && !HardLightBridgeEmitterBlock.suppressUpdates && state.getValue(POWERED)) + HardLightBridgeEmitterBlock.updateEmission(serverLevel, state, pos, false); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return SHAPES.computeIfAbsent(state, HardLightBridgeEmitterBlock::makeShape); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public BlockState rotate(BlockState state, Rotation rotation) { + return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + } + + @SuppressWarnings("deprecation") + @Override + public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { + if (stateFrom.is(this) || stateFrom.is(PortalCubedBlocks.HLB_BLOCK)) { + return stateFrom.getValue(FACING) == state.getValue(FACING); + } + return false; + } + + public static void updateEmission(ServerLevel level, BlockState emitterState, BlockPos emitterPos, boolean powered) { + withUpdatesSuppressed(() -> { + Direction facing = emitterState.getValue(FACING); + Edge edge = emitterState.getValue(EDGE); + BlockState bridgeState = !powered ? Blocks.AIR.defaultBlockState() + : PortalCubedBlocks.HLB_BLOCK.defaultBlockState() + .setValue(FACING, facing).setValue(EDGE, edge); + + MutableBlockPos pos = emitterPos.mutable(); + distance: for (int i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { + pos.move(facing); + if (canPlaceBridge(level, pos, facing)) { + level.setBlockAndUpdate(pos, bridgeState); + } else { // hit a wall, check for portals + pos.move(facing.getOpposite()); // step back + AABB box = new AABB(pos); + List portals = level.getEntitiesOfClass(Portal.class, box); + for (Portal portal : portals) { + Direction portalFacing = portal.getFacingDirection(); + if (portalFacing.getOpposite() != facing) + continue; + Portal linked = portal.findLinkedPortal(); + if (linked == null) + continue; + if (!portal.snapToGrid() || !linked.snapToGrid()) + continue; + Vec3 bridgePos = edge.offsetTowards(Vec3.atCenterOf(pos), facing, 0.4); + Vec3 relative = bridgePos.subtract(portal.getOriginPos()); + Axis xAxis = Edge.RIGHT.toDirection(facing).getAxis(); + double x = relative.get(xAxis); + Axis yAxis = Edge.UP.toDirection(facing).getAxis(); + double y = relative.get(yAxis); + Vec3 linkedBase = linked.getPointInPlane(-x, -y); // negative??? + Vec3 linkedBridgePos = linkedBase.relative(linked.getFacingDirection(), 0.5); + + // successfully teleported. update stuff and continue propagating. + pos.set(linkedBridgePos.x, linkedBridgePos.y, linkedBridgePos.z); + edge = Edge.teleport(edge, portal, facing, linked.getFacingDirection()); + facing = linked.getFacingDirection(); + + pos.move(facing.getOpposite()); // step back, will move forward again on next loop + bridgeState = !powered ? Blocks.AIR.defaultBlockState() + : PortalCubedBlocks.HLB_BLOCK.defaultBlockState() + .setValue(FACING, facing).setValue(EDGE, edge); + continue distance; + } + return; // couldn't teleport + } + } + }); + } + + public static void withUpdatesSuppressed(Runnable runnable) { + try { + suppressUpdates = true; + runnable.run(); + } finally { + suppressUpdates = false; + } + } + + private static boolean canPlaceBridge(ServerLevel level, BlockPos pos, Direction facing) { + if (!level.isLoaded(pos)) + return false; + BlockState state = level.getBlockState(pos); + if (!state.is(PortalCubedBlocks.HLB_BLOCK)) + return state.isAir(); + return state.getValue(FACING) == facing; + } + + private static VoxelShape makeShape(BlockState state) { + Direction facing = state.getValue(FACING); + Edge edge = state.getValue(EDGE); + if (facing.getAxis().isVertical()) + edge = edge.getOpposite(); + VoxelShape shape = SHAPERS.get(edge).get(facing); + if (state.getValue(POWERED)) { + shape = Shapes.or(shape, HardLightBridgeBlock.makeShape(state)); + } + return shape; + } + + @Override + public void onPortalCreate(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { + Direction facing = state.getValue(FACING); + if (facing != portal.getFacingDirection().getOpposite()) + return; + // propagate through + HardLightBridgeEmitterBlock.updateEmission(level, state, pos, true); + } + + @Override + public void beforePortalRemove(ServerLevel level, BlockState state, BlockPos pos, Portal portal) { + Direction facing = state.getValue(FACING); + if (facing == portal.getFacingDirection().getOpposite()) { // portal in front, remove bridge on other side. + HardLightBridgeEmitterBlock.updateEmission(level, state, pos, false); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgePart.java b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgePart.java index c1343e94..f1380091 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgePart.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/bridge/HardLightBridgePart.java @@ -6,7 +6,7 @@ import net.minecraft.world.level.block.state.properties.EnumProperty; public interface HardLightBridgePart extends PortalMoveListeningBlock { - DirectionProperty FACING = BlockStateProperties.FACING; - EnumProperty EDGE = EnumProperty.create("edge", Edge.class); + DirectionProperty FACING = BlockStateProperties.FACING; + EnumProperty EDGE = EnumProperty.create("edge", Edge.class); } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/AbstractFizzlerBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/AbstractFizzlerBlock.java index f64898eb..6171ede0 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/AbstractFizzlerBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/AbstractFizzlerBlock.java @@ -33,103 +33,103 @@ import static com.fusionflux.portalcubed.mechanics.PortalCubedDamageSources.pcSources; public abstract class AbstractFizzlerBlock extends Block { - public static final BooleanProperty NS = BooleanProperty.create("ns"); - public static final BooleanProperty EW = BooleanProperty.create("ew"); - public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; - - private static final VoxelShape NS_SHAPE = box(7.5, 0, 0, 8.5, 16, 16); - private static final VoxelShape EW_SHAPE = box(0, 0, 7.5, 16, 16, 8.5); - private static final VoxelShape BOTH_SHAPE = Shapes.or(NS_SHAPE, EW_SHAPE); - - public AbstractFizzlerBlock(Properties settings) { - super(settings); - registerDefaultState( - getStateDefinition().any() - .setValue(NS, false) - .setValue(EW, false) - .setValue(HALF, DoubleBlockHalf.LOWER) - ); - } - - public static BooleanProperty getStateForAxis(Direction.Axis axis) { - return axis == Direction.Axis.Z ? NS : EW; - } - - public static boolean isEmpty(BlockState state) { - return !state.getValue(NS) && !state.getValue(EW); - } - - @NotNull - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos, @NotNull CollisionContext context) { - if (state.getValue(NS) && state.getValue(EW)) { - return BOTH_SHAPE; - } - if (state.getValue(NS)) { - return NS_SHAPE; - } - if (state.getValue(EW)) { - return EW_SHAPE; - } - return Shapes.empty(); - } - - @Override - @SuppressWarnings("deprecation") - public float getShadeBrightness(@NotNull BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos) { - return 1; - } - - @Override - public boolean propagatesSkylightDown(@NotNull BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos) { - return true; - } - - @Override - @SuppressWarnings("deprecation") - public boolean skipRendering(@NotNull BlockState state, BlockState stateFrom, @NotNull Direction direction) { - return stateFrom.is(this) || super.skipRendering(state, stateFrom, direction); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(NS, EW, HALF); - } - - public abstract void applyEffectsTo(Entity entity); - - protected final void fizzlePortals(Entity entity) { - if (entity.level().isClientSide) return; - boolean foundPortal = false; - for (final UUID portal : List.copyOf(CalledValues.getPortals(entity))) { - final Entity checkPortal = ((ServerLevel)entity.level()).getEntity(portal); - if (checkPortal != null) { - foundPortal = true; - checkPortal.kill(); - } - } - if (foundPortal && entity instanceof ServerPlayer player) { - player.playNotifySound(PortalCubedSounds.ENTITY_PORTAL_FIZZLE, SoundSource.NEUTRAL, 0.5f, 1f); - ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); - } - } - - protected final void fizzlePhysicsEntity(Entity entity) { - if (entity.level().isClientSide) return; - if (entity instanceof Fizzleable fizzleable && fizzleable.getFizzleType() == Fizzleable.FizzleType.OBJECT) { - fizzleable.fizzle(); - } - } - - protected final void fizzleLiving(Entity entity) { - if (entity.level().isClientSide) return; - // TODO: Fizzle players visually? - if (entity instanceof Fizzleable fizzleable ? fizzleable.getFizzleType() == Fizzleable.FizzleType.LIVING : entity instanceof LivingEntity) { - entity.hurt(pcSources(entity.level()).fizzle(), PortalCubedConfig.fizzlerDamage); - if (entity instanceof Fizzleable fizzleable && fizzleable.getFizzleType() != Fizzleable.FizzleType.NOT) { - fizzleable.fizzle(); - } - } - } + public static final BooleanProperty NS = BooleanProperty.create("ns"); + public static final BooleanProperty EW = BooleanProperty.create("ew"); + public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; + + private static final VoxelShape NS_SHAPE = box(7.5, 0, 0, 8.5, 16, 16); + private static final VoxelShape EW_SHAPE = box(0, 0, 7.5, 16, 16, 8.5); + private static final VoxelShape BOTH_SHAPE = Shapes.or(NS_SHAPE, EW_SHAPE); + + public AbstractFizzlerBlock(Properties settings) { + super(settings); + registerDefaultState( + getStateDefinition().any() + .setValue(NS, false) + .setValue(EW, false) + .setValue(HALF, DoubleBlockHalf.LOWER) + ); + } + + public static BooleanProperty getStateForAxis(Direction.Axis axis) { + return axis == Direction.Axis.Z ? NS : EW; + } + + public static boolean isEmpty(BlockState state) { + return !state.getValue(NS) && !state.getValue(EW); + } + + @NotNull + @Override + @SuppressWarnings("deprecation") + public VoxelShape getShape(BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos, @NotNull CollisionContext context) { + if (state.getValue(NS) && state.getValue(EW)) { + return BOTH_SHAPE; + } + if (state.getValue(NS)) { + return NS_SHAPE; + } + if (state.getValue(EW)) { + return EW_SHAPE; + } + return Shapes.empty(); + } + + @Override + @SuppressWarnings("deprecation") + public float getShadeBrightness(@NotNull BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos) { + return 1; + } + + @Override + public boolean propagatesSkylightDown(@NotNull BlockState state, @NotNull BlockGetter world, @NotNull BlockPos pos) { + return true; + } + + @Override + @SuppressWarnings("deprecation") + public boolean skipRendering(@NotNull BlockState state, BlockState stateFrom, @NotNull Direction direction) { + return stateFrom.is(this) || super.skipRendering(state, stateFrom, direction); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(NS, EW, HALF); + } + + public abstract void applyEffectsTo(Entity entity); + + protected final void fizzlePortals(Entity entity) { + if (entity.level().isClientSide) return; + boolean foundPortal = false; + for (final UUID portal : List.copyOf(CalledValues.getPortals(entity))) { + final Entity checkPortal = ((ServerLevel)entity.level()).getEntity(portal); + if (checkPortal != null) { + foundPortal = true; + checkPortal.kill(); + } + } + if (foundPortal && entity instanceof ServerPlayer player) { + player.playNotifySound(PortalCubedSounds.ENTITY_PORTAL_FIZZLE, SoundSource.NEUTRAL, 0.5f, 1f); + ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); + } + } + + protected final void fizzlePhysicsEntity(Entity entity) { + if (entity.level().isClientSide) return; + if (entity instanceof Fizzleable fizzleable && fizzleable.getFizzleType() == Fizzleable.FizzleType.OBJECT) { + fizzleable.fizzle(); + } + } + + protected final void fizzleLiving(Entity entity) { + if (entity.level().isClientSide) return; + // TODO: Fizzle players visually? + if (entity instanceof Fizzleable fizzleable ? fizzleable.getFizzleType() == Fizzleable.FizzleType.LIVING : entity instanceof LivingEntity) { + entity.hurt(pcSources(entity.level()).fizzle(), PortalCubedConfig.fizzlerDamage); + if (entity instanceof Fizzleable fizzleable && fizzleable.getFizzleType() != Fizzleable.FizzleType.NOT) { + fizzleable.fizzle(); + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/DeathFizzlerBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/DeathFizzlerBlock.java index 61d5e5f3..e96a6fe8 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/DeathFizzlerBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/DeathFizzlerBlock.java @@ -3,14 +3,14 @@ import net.minecraft.world.entity.Entity; public class DeathFizzlerBlock extends AbstractFizzlerBlock { - public DeathFizzlerBlock(Properties settings) { - super(settings); - } + public DeathFizzlerBlock(Properties settings) { + super(settings); + } - @Override - public void applyEffectsTo(Entity entity) { - fizzlePortals(entity); - fizzlePhysicsEntity(entity); - fizzleLiving(entity); - } + @Override + public void applyEffectsTo(Entity entity) { + fizzlePortals(entity); + fizzlePhysicsEntity(entity); + fizzleLiving(entity); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerBlock.java index 533e0f71..5fbbe5af 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerBlock.java @@ -3,13 +3,13 @@ import net.minecraft.world.entity.Entity; public class FizzlerBlock extends AbstractFizzlerBlock { - public FizzlerBlock(Properties settings) { - super(settings); - } + public FizzlerBlock(Properties settings) { + super(settings); + } - @Override - public void applyEffectsTo(Entity entity) { - fizzlePortals(entity); - fizzlePhysicsEntity(entity); - } + @Override + public void applyEffectsTo(Entity entity) { + fizzlePortals(entity); + fizzlePhysicsEntity(entity); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerEmitter.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerEmitter.java index 1c9333ab..65a30435 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerEmitter.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/FizzlerEmitter.java @@ -22,135 +22,135 @@ import org.jetbrains.annotations.Nullable; public class FizzlerEmitter extends HorizontalDirectionalBlock { - public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final EnumProperty HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - private final AbstractFizzlerBlock fizzlerBlock; + private final AbstractFizzlerBlock fizzlerBlock; - public FizzlerEmitter(Properties settings, AbstractFizzlerBlock fizzlerBlock) { - super(settings); - this.fizzlerBlock = fizzlerBlock; - registerDefaultState( - getStateDefinition().any() - .setValue(FACING, Direction.NORTH) - .setValue(HALF, DoubleBlockHalf.LOWER) - .setValue(POWERED, false) - ); - } + public FizzlerEmitter(Properties settings, AbstractFizzlerBlock fizzlerBlock) { + super(settings); + this.fizzlerBlock = fizzlerBlock; + registerDefaultState( + getStateDefinition().any() + .setValue(FACING, Direction.NORTH) + .setValue(HALF, DoubleBlockHalf.LOWER) + .setValue(POWERED, false) + ); + } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, HALF, POWERED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, HALF, POWERED); + } - @NotNull - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape(BlockState state, Direction direction, @NotNull BlockState neighborState, @NotNull LevelAccessor world, @NotNull BlockPos pos, @NotNull BlockPos neighborPos) { - final DoubleBlockHalf half = state.getValue(HALF); - if (direction.getAxis() != Direction.Axis.Y || half == DoubleBlockHalf.LOWER != (direction == Direction.UP)) { - return half == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) - ? Blocks.AIR.defaultBlockState() - : super.updateShape(state, direction, neighborState, world, pos, neighborPos); - } - return neighborState.is(this) && neighborState.getValue(HALF) != half - ? state.setValue(FACING, neighborState.getValue(FACING)) - .setValue(POWERED, neighborState.getValue(POWERED)) - : Blocks.AIR.defaultBlockState(); - } + @NotNull + @Override + @SuppressWarnings("deprecation") + public BlockState updateShape(BlockState state, Direction direction, @NotNull BlockState neighborState, @NotNull LevelAccessor world, @NotNull BlockPos pos, @NotNull BlockPos neighborPos) { + final DoubleBlockHalf half = state.getValue(HALF); + if (direction.getAxis() != Direction.Axis.Y || half == DoubleBlockHalf.LOWER != (direction == Direction.UP)) { + return half == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(world, pos) + ? Blocks.AIR.defaultBlockState() + : super.updateShape(state, direction, neighborState, world, pos, neighborPos); + } + return neighborState.is(this) && neighborState.getValue(HALF) != half + ? state.setValue(FACING, neighborState.getValue(FACING)) + .setValue(POWERED, neighborState.getValue(POWERED)) + : Blocks.AIR.defaultBlockState(); + } - @Override - public void playerWillDestroy(@NotNull Level world, @NotNull BlockPos pos, BlockState state, @NotNull Player player) { - if (state.getValue(POWERED)) { - updateGrill(world, pos.immutable(), state, false); - updateGrill(world, state.getValue(HALF) == DoubleBlockHalf.UPPER ? pos.below() : pos.above(), state.cycle(HALF), false); - } - if (!world.isClientSide && player.isCreative()) { - onBreakInCreative(world, pos, state, player); - } + @Override + public void playerWillDestroy(@NotNull Level world, @NotNull BlockPos pos, BlockState state, @NotNull Player player) { + if (state.getValue(POWERED)) { + updateGrill(world, pos.immutable(), state, false); + updateGrill(world, state.getValue(HALF) == DoubleBlockHalf.UPPER ? pos.below() : pos.above(), state.cycle(HALF), false); + } + if (!world.isClientSide && player.isCreative()) { + onBreakInCreative(world, pos, state, player); + } - super.playerWillDestroy(world, pos, state, player); - } + super.playerWillDestroy(world, pos, state, player); + } - protected static void onBreakInCreative(Level world, BlockPos pos, BlockState state, Player player) { - DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); - if (doubleBlockHalf == DoubleBlockHalf.UPPER) { - BlockPos blockPos = pos.below(); - BlockState blockState = world.getBlockState(blockPos); - if (blockState.is(state.getBlock()) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER) { - BlockState blockState2 = blockState.hasProperty(BlockStateProperties.WATERLOGGED) && blockState.getValue(BlockStateProperties.WATERLOGGED) - ? Blocks.WATER.defaultBlockState() - : Blocks.AIR.defaultBlockState(); - world.setBlock(blockPos, blockState2, 35); - world.levelEvent(player, 2001, blockPos, Block.getId(blockState)); - } - } - } + protected static void onBreakInCreative(Level world, BlockPos pos, BlockState state, Player player) { + DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); + if (doubleBlockHalf == DoubleBlockHalf.UPPER) { + BlockPos blockPos = pos.below(); + BlockState blockState = world.getBlockState(blockPos); + if (blockState.is(state.getBlock()) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER) { + BlockState blockState2 = blockState.hasProperty(BlockStateProperties.WATERLOGGED) && blockState.getValue(BlockStateProperties.WATERLOGGED) + ? Blocks.WATER.defaultBlockState() + : Blocks.AIR.defaultBlockState(); + world.setBlock(blockPos, blockState2, 35); + world.levelEvent(player, 2001, blockPos, Block.getId(blockState)); + } + } + } - @Nullable - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - final BlockPos pos = ctx.getClickedPos(); - final Level world = ctx.getLevel(); - if (pos.getY() < world.getMaxBuildHeight() - 1 && world.getBlockState(pos.above()).canBeReplaced(ctx)) { - return defaultBlockState() - .setValue(FACING, ctx.getHorizontalDirection().getOpposite()) - .setValue(HALF, DoubleBlockHalf.LOWER) - .setValue(POWERED, world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.above())); - } - return null; - } + @Nullable + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + final BlockPos pos = ctx.getClickedPos(); + final Level world = ctx.getLevel(); + if (pos.getY() < world.getMaxBuildHeight() - 1 && world.getBlockState(pos.above()).canBeReplaced(ctx)) { + return defaultBlockState() + .setValue(FACING, ctx.getHorizontalDirection().getOpposite()) + .setValue(HALF, DoubleBlockHalf.LOWER) + .setValue(POWERED, world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.above())); + } + return null; + } - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, @NotNull ItemStack itemStack) { - final BlockPos otherPos = pos.above(); - final BlockState otherState = state.setValue(HALF, DoubleBlockHalf.UPPER); - world.setBlockAndUpdate(otherPos, otherState); - if (state.getValue(POWERED)) { - updateGrill(world, pos, state, true); - updateGrill(world, otherPos, otherState, true); - } - } + @Override + public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, @NotNull ItemStack itemStack) { + final BlockPos otherPos = pos.above(); + final BlockState otherState = state.setValue(HALF, DoubleBlockHalf.UPPER); + world.setBlockAndUpdate(otherPos, otherState); + if (state.getValue(POWERED)) { + updateGrill(world, pos, state, true); + updateGrill(world, otherPos, otherState, true); + } + } - @Override - @SuppressWarnings("deprecation") - public void neighborChanged(BlockState state, Level world, BlockPos pos, @NotNull Block block, @NotNull BlockPos fromPos, boolean notify) { - final BlockPos otherPos = pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN); - final boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(otherPos); - if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { - updateGrill(world, pos, state, powered); - updateGrill(world, otherPos, state.cycle(HALF), powered); - world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); - } - } + @Override + @SuppressWarnings("deprecation") + public void neighborChanged(BlockState state, Level world, BlockPos pos, @NotNull Block block, @NotNull BlockPos fromPos, boolean notify) { + final BlockPos otherPos = pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN); + final boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(otherPos); + if (!defaultBlockState().is(block) && powered != state.getValue(POWERED)) { + updateGrill(world, pos, state, powered); + updateGrill(world, otherPos, state.cycle(HALF), powered); + world.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); + } + } - private void updateGrill(Level world, BlockPos pos, BlockState state, boolean placed) { - if (world.isClientSide) return; - final Direction searchDir = state.getValue(FACING); - final BooleanProperty grillAxis = AbstractFizzlerBlock.getStateForAxis(searchDir.getAxis()); - final BlockState targetState = state.setValue(FACING, searchDir.getOpposite()).setValue(POWERED, placed); - BlockPos searchPos = pos.relative(searchDir); - int i; - for (i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { - final BlockState checkState = world.getBlockState(searchPos); - if (checkState.equals(targetState)) break; - if (placed && !checkState.canBeReplaced() && !checkState.is(fizzlerBlock)) return; - if (!placed && checkState.is(fizzlerBlock)) { - final BlockState newState = checkState.setValue(grillAxis, false); - world.setBlockAndUpdate(searchPos, AbstractFizzlerBlock.isEmpty(newState) ? Blocks.AIR.defaultBlockState() : newState); - } - searchPos = searchPos.relative(searchDir); - } - if (!placed || i == PortalCubedConfig.maxBridgeLength) return; - final BlockState placedState = fizzlerBlock.defaultBlockState() - .setValue(grillAxis, true) - .setValue(HALF, state.getValue(HALF)); - searchPos = pos.relative(searchDir); - for (i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { - final BlockState checkState = world.getBlockState(searchPos); - if (checkState.equals(targetState)) break; - world.setBlockAndUpdate(searchPos, checkState.canBeReplaced() ? placedState : checkState.setValue(grillAxis, true)); - searchPos = searchPos.relative(searchDir); - } - } + private void updateGrill(Level world, BlockPos pos, BlockState state, boolean placed) { + if (world.isClientSide) return; + final Direction searchDir = state.getValue(FACING); + final BooleanProperty grillAxis = AbstractFizzlerBlock.getStateForAxis(searchDir.getAxis()); + final BlockState targetState = state.setValue(FACING, searchDir.getOpposite()).setValue(POWERED, placed); + BlockPos searchPos = pos.relative(searchDir); + int i; + for (i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { + final BlockState checkState = world.getBlockState(searchPos); + if (checkState.equals(targetState)) break; + if (placed && !checkState.canBeReplaced() && !checkState.is(fizzlerBlock)) return; + if (!placed && checkState.is(fizzlerBlock)) { + final BlockState newState = checkState.setValue(grillAxis, false); + world.setBlockAndUpdate(searchPos, AbstractFizzlerBlock.isEmpty(newState) ? Blocks.AIR.defaultBlockState() : newState); + } + searchPos = searchPos.relative(searchDir); + } + if (!placed || i == PortalCubedConfig.maxBridgeLength) return; + final BlockState placedState = fizzlerBlock.defaultBlockState() + .setValue(grillAxis, true) + .setValue(HALF, state.getValue(HALF)); + searchPos = pos.relative(searchDir); + for (i = 0; i < PortalCubedConfig.maxBridgeLength; i++) { + final BlockState checkState = world.getBlockState(searchPos); + if (checkState.equals(targetState)) break; + world.setBlockAndUpdate(searchPos, checkState.canBeReplaced() ? placedState : checkState.setValue(grillAxis, true)); + searchPos = searchPos.relative(searchDir); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/LaserFizzlerBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/LaserFizzlerBlock.java index d76c823e..75135b1c 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/LaserFizzlerBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/LaserFizzlerBlock.java @@ -3,12 +3,12 @@ import net.minecraft.world.entity.Entity; public class LaserFizzlerBlock extends AbstractFizzlerBlock { - public LaserFizzlerBlock(Properties settings) { - super(settings); - } + public LaserFizzlerBlock(Properties settings) { + super(settings); + } - @Override - public void applyEffectsTo(Entity entity) { - fizzleLiving(entity); - } + @Override + public void applyEffectsTo(Entity entity) { + fizzleLiving(entity); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/MatterInquisitionField.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/MatterInquisitionField.java index 14781eb3..f5b2e089 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/MatterInquisitionField.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/MatterInquisitionField.java @@ -3,12 +3,12 @@ import net.minecraft.world.entity.Entity; public class MatterInquisitionField extends AbstractFizzlerBlock { - public MatterInquisitionField(Properties settings) { - super(settings); - } + public MatterInquisitionField(Properties settings) { + super(settings); + } - @Override - public void applyEffectsTo(Entity entity) { - fizzlePhysicsEntity(entity); - } + @Override + public void applyEffectsTo(Entity entity) { + fizzlePhysicsEntity(entity); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/PhysicsRepulsionField.java b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/PhysicsRepulsionField.java index 6f2958bd..2feb03d7 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/PhysicsRepulsionField.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/fizzler/PhysicsRepulsionField.java @@ -10,18 +10,18 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class PhysicsRepulsionField extends AbstractFizzlerBlock { - public PhysicsRepulsionField(Properties settings) { - super(settings); - } + public PhysicsRepulsionField(Properties settings) { + super(settings); + } - @Override - public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - return context instanceof EntityCollisionContext entityCtx && entityCtx.getEntity() instanceof CorePhysicsEntity - ? getShape(state, world, pos, context) - : super.getCollisionShape(state, world, pos, context); - } + @Override + public VoxelShape getCollisionShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + return context instanceof EntityCollisionContext entityCtx && entityCtx.getEntity() instanceof CorePhysicsEntity + ? getShape(state, world, pos, context) + : super.getCollisionShape(state, world, pos, context); + } - @Override - public void applyEffectsTo(Entity entity) { - } + @Override + public void applyEffectsTo(Entity entity) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/funnel/ExcursionFunnelEmitterBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/funnel/ExcursionFunnelEmitterBlock.java index 82c3ea4a..399707ff 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/funnel/ExcursionFunnelEmitterBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/funnel/ExcursionFunnelEmitterBlock.java @@ -38,194 +38,194 @@ import java.util.UUID; public class ExcursionFunnelEmitterBlock extends BaseEntityBlock implements TwoByTwoFacingMultiblockBlock { - public static final EnumProperty MODE = EnumProperty.create("mode", Mode.class); - public static final Map FACING_TO_SHAPE = Util.make(new EnumMap<>(Direction.class), map -> { - map.put(Direction.UP, Block.box(0, 0, 0, 16, 4, 16)); - map.put(Direction.DOWN, Block.box(0, 12, 0, 16, 16, 16)); - map.put(Direction.WEST, Block.box(12, 0, 0, 16, 16, 16)); - map.put(Direction.EAST, Block.box(0, 0, 0, 4, 16, 16)); - map.put(Direction.SOUTH, Block.box(0, 0, 0, 16, 16, 4)); - map.put(Direction.NORTH, Block.box(0, 0, 12, 16, 16, 16)); - }); - - public ExcursionFunnelEmitterBlock(Properties settings) { - super(settings); - this.registerDefaultState(this.stateDefinition.any() - .setValue(FACING, Direction.NORTH) - .setValue(MODE, Mode.FORWARD_OFF) - .setValue(QUADRANT, 1) - ); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, MODE, QUADRANT); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) - return InteractionResult.PASS; - if (!(level instanceof ServerLevel serverLevel)) - return InteractionResult.SUCCESS; - Direction facing = state.getValue(FACING); - TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant(pos, state.getValue(QUADRANT), facing); - if (!(level.getBlockEntity(pos) instanceof ExcursionFunnelEmitterBlockEntity emitter)) - return InteractionResult.FAIL; - ToggleMode mode = emitter.getToggleMode(); - boolean powered = state.getValue(MODE) == mode.on; - ToggleMode newToggleMode = mode.next(); - emitter.setToggleMode(newToggleMode); - // sync with others - multiblock.forEach(part -> { - if (part != pos && level.getBlockEntity(part) instanceof ExcursionFunnelEmitterBlockEntity be) - be.setToggleMode(newToggleMode); - }); - // update emitter - Mode newMode = powered ? newToggleMode.on : newToggleMode.off; - updateEmitter(serverLevel, multiblock, newMode); - updateEmission(serverLevel, multiblock, facing, newMode); - return InteractionResult.SUCCESS; - } - - @Nullable - @Override - public BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState().setValue( - FACING, - context.getPlayer() == null ? Direction.SOUTH : context.getNearestLookingDirection() - ); - } - - @SuppressWarnings("deprecation") - @Override - @NotNull - public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(FACING); - return FACING_TO_SHAPE.get(facing); - } - - @Override - @NotNull - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - - @SuppressWarnings("deprecation") - @Override - public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { - if (!(level instanceof ServerLevel serverLevel)) - return; - Direction facing = state.getValue(FACING); - TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant( - pos, state.getValue(QUADRANT), facing - ); - if (multiblock.contains(fromPos)) - return; // ignore updates from self - if (!(level.getBlockEntity(pos) instanceof ExcursionFunnelEmitterBlockEntity be)) - return; - boolean anyPowered = anyPartPowered(level, multiblock); - Mode currentMode = state.getValue(MODE); - ToggleMode toggleMode = be.getToggleMode(); - boolean currentlyPowered = toggleMode.on == currentMode; - if (currentlyPowered == anyPowered) - return; // up to date - Mode newMode = anyPowered ? toggleMode.on : toggleMode.off; - updateEmitter(serverLevel, multiblock, newMode); - updateEmission(serverLevel, multiblock, facing, newMode); - } - - @SuppressWarnings("deprecation") - @Override - public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { - if (level instanceof ServerLevel serverLevel && !state.is(newState.getBlock())) - destroyMultiblock(serverLevel, state, pos, true); - super.onRemove(state, level, pos, newState, isMoving); - } - - @Override - public void playerWillDestroy(Level level, BlockPos pos, BlockState state, Player player) { - if (level instanceof ServerLevel serverLevel && player.isCreative()) - destroyMultiblock(serverLevel, state, pos, false); // intercept the destruction in creative to prevent drops - super.playerWillDestroy(level, pos, state, player); - } - - public void updateEmitter(ServerLevel level, TwoByTwo multiblock, Mode newMode) { - multiblock.forEach(part -> { - BlockState partState = level.getBlockState(part); - if (!partState.is(this)) - return; - BlockState newState = partState.setValue(MODE, newMode); - level.setBlockAndUpdate(part, newState); - }); - } - - private static void updateEmission(ServerLevel level, TwoByTwo multiblock, Direction facing, Mode newMode) { - // remove old entity - BlockEntity be = level.getBlockEntity(multiblock.byQuadrant(1)); - if (be instanceof ExcursionFunnelEmitterBlockEntity emitter) { - UUID id = emitter.getFunnelEntityId(); - if (id != null && level.getEntity(id) instanceof ExcursionFunnelEntity entity) { - entity.discard(); - } - if (newMode.isOn) // spawn new entity if enabled - spawnFunnelEntity(level, multiblock, facing, newMode.isReversed, emitter.getMaxLength()); - } - } - - private static void spawnFunnelEntity(ServerLevel level, TwoByTwo multiblock, Direction facing, boolean reversed, float maxLength) { - Vec3 start = multiblock.getCenter().relative(facing, -0.3); - ExcursionFunnelEntity entity = ExcursionFunnelEntity.spawnAndEmit(level, start, facing, reversed, maxLength); - // block entity tracks entity - BlockEntity be = level.getBlockEntity(multiblock.byQuadrant(1)); - if (be instanceof ExcursionFunnelEmitterBlockEntity emitter) - emitter.setFunnelEntityId(entity.getUUID()); - } - - protected void destroyMultiblock(ServerLevel level, BlockState state, BlockPos thisPos, boolean dropItem) { - TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant( - thisPos, state.getValue(QUADRANT), state.getValue(FACING) - ); - for (BlockPos pos : multiblock) { - if (pos != thisPos && level.getBlockState(pos).is(this)) { - level.destroyBlock(pos, dropItem); - } - } - Mode mode = state.getValue(MODE); - if (mode.isOn) // remove the funnel - updateEmission(level, multiblock, state.getValue(FACING), Mode.FORWARD_OFF); - } - - private static boolean anyPartPowered(Level level, TwoByTwo multiblock) { - boolean anyPowered = false; - for (BlockPos partPos : multiblock) { - if (level.hasNeighborSignal(partPos)) { - anyPowered = true; - break; - } - } - return anyPowered; - } - - @Override - @Nullable - public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new ExcursionFunnelEmitterBlockEntity(pos, state); - } - - public enum Mode implements StringRepresentable { - FORWARD_OFF, FORWARD_ON, REVERSED_OFF, REVERSED_ON; - - public final String serialized = name().toLowerCase(Locale.ROOT); - public final boolean isOn = serialized.contains("on"); - public final boolean isReversed = serialized.contains("reverse"); - - @Override - @NotNull - public String getSerializedName() { - return serialized; - } - } + public static final EnumProperty MODE = EnumProperty.create("mode", Mode.class); + public static final Map FACING_TO_SHAPE = Util.make(new EnumMap<>(Direction.class), map -> { + map.put(Direction.UP, Block.box(0, 0, 0, 16, 4, 16)); + map.put(Direction.DOWN, Block.box(0, 12, 0, 16, 16, 16)); + map.put(Direction.WEST, Block.box(12, 0, 0, 16, 16, 16)); + map.put(Direction.EAST, Block.box(0, 0, 0, 4, 16, 16)); + map.put(Direction.SOUTH, Block.box(0, 0, 0, 16, 16, 4)); + map.put(Direction.NORTH, Block.box(0, 0, 12, 16, 16, 16)); + }); + + public ExcursionFunnelEmitterBlock(Properties settings) { + super(settings); + this.registerDefaultState(this.stateDefinition.any() + .setValue(FACING, Direction.NORTH) + .setValue(MODE, Mode.FORWARD_OFF) + .setValue(QUADRANT, 1) + ); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(FACING, MODE, QUADRANT); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (!player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) + return InteractionResult.PASS; + if (!(level instanceof ServerLevel serverLevel)) + return InteractionResult.SUCCESS; + Direction facing = state.getValue(FACING); + TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant(pos, state.getValue(QUADRANT), facing); + if (!(level.getBlockEntity(pos) instanceof ExcursionFunnelEmitterBlockEntity emitter)) + return InteractionResult.FAIL; + ToggleMode mode = emitter.getToggleMode(); + boolean powered = state.getValue(MODE) == mode.on; + ToggleMode newToggleMode = mode.next(); + emitter.setToggleMode(newToggleMode); + // sync with others + multiblock.forEach(part -> { + if (part != pos && level.getBlockEntity(part) instanceof ExcursionFunnelEmitterBlockEntity be) + be.setToggleMode(newToggleMode); + }); + // update emitter + Mode newMode = powered ? newToggleMode.on : newToggleMode.off; + updateEmitter(serverLevel, multiblock, newMode); + updateEmission(serverLevel, multiblock, facing, newMode); + return InteractionResult.SUCCESS; + } + + @Nullable + @Override + public BlockState getStateForPlacement(BlockPlaceContext context) { + return defaultBlockState().setValue( + FACING, + context.getPlayer() == null ? Direction.SOUTH : context.getNearestLookingDirection() + ); + } + + @SuppressWarnings("deprecation") + @Override + @NotNull + public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { + Direction facing = state.getValue(FACING); + return FACING_TO_SHAPE.get(facing); + } + + @Override + @NotNull + public RenderShape getRenderShape(BlockState state) { + return RenderShape.MODEL; + } + + @SuppressWarnings("deprecation") + @Override + public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving) { + if (!(level instanceof ServerLevel serverLevel)) + return; + Direction facing = state.getValue(FACING); + TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant( + pos, state.getValue(QUADRANT), facing + ); + if (multiblock.contains(fromPos)) + return; // ignore updates from self + if (!(level.getBlockEntity(pos) instanceof ExcursionFunnelEmitterBlockEntity be)) + return; + boolean anyPowered = anyPartPowered(level, multiblock); + Mode currentMode = state.getValue(MODE); + ToggleMode toggleMode = be.getToggleMode(); + boolean currentlyPowered = toggleMode.on == currentMode; + if (currentlyPowered == anyPowered) + return; // up to date + Mode newMode = anyPowered ? toggleMode.on : toggleMode.off; + updateEmitter(serverLevel, multiblock, newMode); + updateEmission(serverLevel, multiblock, facing, newMode); + } + + @SuppressWarnings("deprecation") + @Override + public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { + if (level instanceof ServerLevel serverLevel && !state.is(newState.getBlock())) + destroyMultiblock(serverLevel, state, pos, true); + super.onRemove(state, level, pos, newState, isMoving); + } + + @Override + public void playerWillDestroy(Level level, BlockPos pos, BlockState state, Player player) { + if (level instanceof ServerLevel serverLevel && player.isCreative()) + destroyMultiblock(serverLevel, state, pos, false); // intercept the destruction in creative to prevent drops + super.playerWillDestroy(level, pos, state, player); + } + + public void updateEmitter(ServerLevel level, TwoByTwo multiblock, Mode newMode) { + multiblock.forEach(part -> { + BlockState partState = level.getBlockState(part); + if (!partState.is(this)) + return; + BlockState newState = partState.setValue(MODE, newMode); + level.setBlockAndUpdate(part, newState); + }); + } + + private static void updateEmission(ServerLevel level, TwoByTwo multiblock, Direction facing, Mode newMode) { + // remove old entity + BlockEntity be = level.getBlockEntity(multiblock.byQuadrant(1)); + if (be instanceof ExcursionFunnelEmitterBlockEntity emitter) { + UUID id = emitter.getFunnelEntityId(); + if (id != null && level.getEntity(id) instanceof ExcursionFunnelEntity entity) { + entity.discard(); + } + if (newMode.isOn) // spawn new entity if enabled + spawnFunnelEntity(level, multiblock, facing, newMode.isReversed, emitter.getMaxLength()); + } + } + + private static void spawnFunnelEntity(ServerLevel level, TwoByTwo multiblock, Direction facing, boolean reversed, float maxLength) { + Vec3 start = multiblock.getCenter().relative(facing, -0.3); + ExcursionFunnelEntity entity = ExcursionFunnelEntity.spawnAndEmit(level, start, facing, reversed, maxLength); + // block entity tracks entity + BlockEntity be = level.getBlockEntity(multiblock.byQuadrant(1)); + if (be instanceof ExcursionFunnelEmitterBlockEntity emitter) + emitter.setFunnelEntityId(entity.getUUID()); + } + + protected void destroyMultiblock(ServerLevel level, BlockState state, BlockPos thisPos, boolean dropItem) { + TwoByTwo multiblock = TwoByTwoFacingMultiblockBlock.makeMultiblockFromQuadrant( + thisPos, state.getValue(QUADRANT), state.getValue(FACING) + ); + for (BlockPos pos : multiblock) { + if (pos != thisPos && level.getBlockState(pos).is(this)) { + level.destroyBlock(pos, dropItem); + } + } + Mode mode = state.getValue(MODE); + if (mode.isOn) // remove the funnel + updateEmission(level, multiblock, state.getValue(FACING), Mode.FORWARD_OFF); + } + + private static boolean anyPartPowered(Level level, TwoByTwo multiblock) { + boolean anyPowered = false; + for (BlockPos partPos : multiblock) { + if (level.hasNeighborSignal(partPos)) { + anyPowered = true; + break; + } + } + return anyPowered; + } + + @Override + @Nullable + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new ExcursionFunnelEmitterBlockEntity(pos, state); + } + + public enum Mode implements StringRepresentable { + FORWARD_OFF, FORWARD_ON, REVERSED_OFF, REVERSED_ON; + + public final String serialized = name().toLowerCase(Locale.ROOT); + public final boolean isOn = serialized.contains("on"); + public final boolean isReversed = serialized.contains("reverse"); + + @Override + @NotNull + public String getSerializedName() { + return serialized; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/funnel/TwoByTwoFacingMultiblockBlock.java b/src/main/java/com/fusionflux/portalcubed/blocks/funnel/TwoByTwoFacingMultiblockBlock.java index f64586e4..e47bd512 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/funnel/TwoByTwoFacingMultiblockBlock.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/funnel/TwoByTwoFacingMultiblockBlock.java @@ -12,67 +12,67 @@ import java.util.Map; public interface TwoByTwoFacingMultiblockBlock { - IntegerProperty QUADRANT = IntegerProperty.create("quadrant", 1, 4); - DirectionProperty FACING = BlockStateProperties.FACING; + IntegerProperty QUADRANT = IntegerProperty.create("quadrant", 1, 4); + DirectionProperty FACING = BlockStateProperties.FACING; - // oh the misery - @SuppressWarnings("unchecked") - Map[] QUADRANT_INDEX_FACING_TO_NEXT = Util.make(new Map[4], (Map[] array) -> { - array[0] = Map.of( - Direction.NORTH, Direction.EAST, - Direction.EAST, Direction.SOUTH, - Direction.SOUTH, Direction.WEST, - Direction.WEST, Direction.NORTH, - Direction.UP, Direction.EAST, - Direction.DOWN, Direction.EAST - ); - array[1] = Map.of( - Direction.NORTH, Direction.DOWN, - Direction.EAST, Direction.DOWN, - Direction.SOUTH, Direction.DOWN, - Direction.WEST, Direction.DOWN, - Direction.UP, Direction.NORTH, - Direction.DOWN, Direction.SOUTH - ); + // oh the misery + @SuppressWarnings("unchecked") + Map[] QUADRANT_INDEX_FACING_TO_NEXT = Util.make(new Map[4], (Map[] array) -> { + array[0] = Map.of( + Direction.NORTH, Direction.EAST, + Direction.EAST, Direction.SOUTH, + Direction.SOUTH, Direction.WEST, + Direction.WEST, Direction.NORTH, + Direction.UP, Direction.EAST, + Direction.DOWN, Direction.EAST + ); + array[1] = Map.of( + Direction.NORTH, Direction.DOWN, + Direction.EAST, Direction.DOWN, + Direction.SOUTH, Direction.DOWN, + Direction.WEST, Direction.DOWN, + Direction.UP, Direction.NORTH, + Direction.DOWN, Direction.SOUTH + ); - Map three = new HashMap<>(); - array[0].forEach((facing, next) -> three.put(facing, next.getOpposite())); - array[2] = three; + Map three = new HashMap<>(); + array[0].forEach((facing, next) -> three.put(facing, next.getOpposite())); + array[2] = three; - Map four = new HashMap<>(); - array[1].forEach((facing, next) -> four.put(facing, next.getOpposite())); - array[3] = four; - }); + Map four = new HashMap<>(); + array[1].forEach((facing, next) -> four.put(facing, next.getOpposite())); + array[3] = four; + }); - static Direction directionToNextQuadrant(int quadrant, Direction facing) { - return QUADRANT_INDEX_FACING_TO_NEXT[quadrant - 1].get(facing); - } + static Direction directionToNextQuadrant(int quadrant, Direction facing) { + return QUADRANT_INDEX_FACING_TO_NEXT[quadrant - 1].get(facing); + } - static Direction directionToPreviousQuadrant(int quadrant, Direction facing) { - int prevQuadrant = quadrant == 1 ? 4 : quadrant - 1; - return QUADRANT_INDEX_FACING_TO_NEXT[prevQuadrant - 1].get(facing).getOpposite(); - } + static Direction directionToPreviousQuadrant(int quadrant, Direction facing) { + int prevQuadrant = quadrant == 1 ? 4 : quadrant - 1; + return QUADRANT_INDEX_FACING_TO_NEXT[prevQuadrant - 1].get(facing).getOpposite(); + } - static TwoByTwo makeMultiblockFromQuadrant(BlockPos pos, int quadrant, Direction facing) { - if (quadrant < 1 || quadrant > 4) - throw new IllegalArgumentException("Invalid quadrant: " + quadrant); - if (quadrant == 1) { - Direction toNext = directionToNextQuadrant(quadrant, facing); - pos = pos.relative(toNext); - quadrant = 2; - } else if (quadrant == 3) { - Direction toNext = directionToNextQuadrant(quadrant, facing); - pos = pos.relative(toNext); - quadrant = 4; - } - if (quadrant == 2) { - Direction right = directionToPreviousQuadrant(2, facing); - Direction down = directionToNextQuadrant(2, facing); - return TwoByTwo.fromTopLeftCorner(pos, right, down); - } else { // quadrant == 4 - Direction left = directionToPreviousQuadrant(4, facing); - Direction up = directionToNextQuadrant(4, facing); - return TwoByTwo.fromBottomRightCorner(pos, left, up); - } - } + static TwoByTwo makeMultiblockFromQuadrant(BlockPos pos, int quadrant, Direction facing) { + if (quadrant < 1 || quadrant > 4) + throw new IllegalArgumentException("Invalid quadrant: " + quadrant); + if (quadrant == 1) { + Direction toNext = directionToNextQuadrant(quadrant, facing); + pos = pos.relative(toNext); + quadrant = 2; + } else if (quadrant == 3) { + Direction toNext = directionToNextQuadrant(quadrant, facing); + pos = pos.relative(toNext); + quadrant = 4; + } + if (quadrant == 2) { + Direction right = directionToPreviousQuadrant(2, facing); + Direction down = directionToNextQuadrant(2, facing); + return TwoByTwo.fromTopLeftCorner(pos, right, down); + } else { // quadrant == 4 + Direction left = directionToPreviousQuadrant(4, facing); + Direction up = directionToNextQuadrant(4, facing); + return TwoByTwo.fromBottomRightCorner(pos, left, up); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/properties/FluidType.java b/src/main/java/com/fusionflux/portalcubed/blocks/properties/FluidType.java index 91a422f0..8a69552b 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/properties/FluidType.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/properties/FluidType.java @@ -9,30 +9,30 @@ import java.util.Locale; public enum FluidType implements StringRepresentable { - EMPTY(Fluids.EMPTY), - WATER(Fluids.WATER), - LAVA(Fluids.LAVA), - TOXIC_GOO(PortalCubedFluids.TOXIC_GOO.still); + EMPTY(Fluids.EMPTY), + WATER(Fluids.WATER), + LAVA(Fluids.LAVA), + TOXIC_GOO(PortalCubedFluids.TOXIC_GOO.still); - private final String id = name().toLowerCase(Locale.ROOT); - public final Fluid fluid; + private final String id = name().toLowerCase(Locale.ROOT); + public final Fluid fluid; - FluidType(Fluid fluid) { - this.fluid = fluid; - } + FluidType(Fluid fluid) { + this.fluid = fluid; + } - @NotNull - @Override - public String getSerializedName() { - return id; - } + @NotNull + @Override + public String getSerializedName() { + return id; + } - public static FluidType getByFluid(Fluid fluid) { - for (final FluidType type : values()) { - if (type.fluid == fluid) { - return type; - } - } - return null; - } + public static FluidType getByFluid(Fluid fluid) { + for (final FluidType type : values()) { + if (type.fluid == fluid) { + return type; + } + } + return null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/blocks/properties/PortalCubedProperties.java b/src/main/java/com/fusionflux/portalcubed/blocks/properties/PortalCubedProperties.java index b6e80696..129966ac 100644 --- a/src/main/java/com/fusionflux/portalcubed/blocks/properties/PortalCubedProperties.java +++ b/src/main/java/com/fusionflux/portalcubed/blocks/properties/PortalCubedProperties.java @@ -7,17 +7,17 @@ public class PortalCubedProperties { - public static final BooleanProperty RUP = BooleanProperty.create("rup"); - public static final BooleanProperty RDOWN = BooleanProperty.create("rdown"); - public static final BooleanProperty RNORTH = BooleanProperty.create("rnorth"); - public static final BooleanProperty REAST = BooleanProperty.create("reast"); - public static final BooleanProperty RSOUTH = BooleanProperty.create("rsouth"); - public static final BooleanProperty RWEST = BooleanProperty.create("rwest"); - public static final BooleanProperty REVERSED = BooleanProperty.create("reversed"); - public static final BooleanProperty REFLECT = BooleanProperty.create("reflect"); - public static final DirectionProperty HFACINGUP = DirectionProperty.create("hfacingup", Direction.Plane.HORIZONTAL); - public static final DirectionProperty HFACINGDOWN = DirectionProperty.create("hfacingdown", Direction.Plane.HORIZONTAL); - public static final DirectionProperty HORIFACING = DirectionProperty.create("horifacing", Direction.Plane.HORIZONTAL); - public static final EnumProperty LOGGING = EnumProperty.create("logging", FluidType.class); + public static final BooleanProperty RUP = BooleanProperty.create("rup"); + public static final BooleanProperty RDOWN = BooleanProperty.create("rdown"); + public static final BooleanProperty RNORTH = BooleanProperty.create("rnorth"); + public static final BooleanProperty REAST = BooleanProperty.create("reast"); + public static final BooleanProperty RSOUTH = BooleanProperty.create("rsouth"); + public static final BooleanProperty RWEST = BooleanProperty.create("rwest"); + public static final BooleanProperty REVERSED = BooleanProperty.create("reversed"); + public static final BooleanProperty REFLECT = BooleanProperty.create("reflect"); + public static final DirectionProperty HFACINGUP = DirectionProperty.create("hfacingup", Direction.Plane.HORIZONTAL); + public static final DirectionProperty HFACINGDOWN = DirectionProperty.create("hfacingdown", Direction.Plane.HORIZONTAL); + public static final DirectionProperty HORIFACING = DirectionProperty.create("horifacing", Direction.Plane.HORIZONTAL); + public static final EnumProperty LOGGING = EnumProperty.create("logging", FluidType.class); } diff --git a/src/main/java/com/fusionflux/portalcubed/client/AdhesionGravityVerifier.java b/src/main/java/com/fusionflux/portalcubed/client/AdhesionGravityVerifier.java index 40676a65..4a5326a2 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/AdhesionGravityVerifier.java +++ b/src/main/java/com/fusionflux/portalcubed/client/AdhesionGravityVerifier.java @@ -13,32 +13,32 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class AdhesionGravityVerifier { - public static final ResourceLocation FIELD_GRAVITY_SOURCE = id("adhesion_gel"); - public static final int FIELD_GRAVITY_PRIORITY = 10; - public static final int FIELD_GRAVITY_MAX_DURATION = 2; + public static final ResourceLocation FIELD_GRAVITY_SOURCE = id("adhesion_gel"); + public static final int FIELD_GRAVITY_PRIORITY = 10; + public static final int FIELD_GRAVITY_MAX_DURATION = 2; - public static Gravity newFieldGravity(Direction direction) { - return new Gravity(direction, FIELD_GRAVITY_PRIORITY, FIELD_GRAVITY_MAX_DURATION, FIELD_GRAVITY_SOURCE.toString(), new RotationParameters().rotateVelocity(true).alternateCenter(true)); - } + public static Gravity newFieldGravity(Direction direction) { + return new Gravity(direction, FIELD_GRAVITY_PRIORITY, FIELD_GRAVITY_MAX_DURATION, FIELD_GRAVITY_SOURCE.toString(), new RotationParameters().rotateVelocity(true).alternateCenter(true)); + } - public static boolean check(ServerPlayer player, FriendlyByteBuf info, UpdateGravityPacket packet) { - if (packet.gravity.duration() > FIELD_GRAVITY_MAX_DURATION) return false; + public static boolean check(ServerPlayer player, FriendlyByteBuf info, UpdateGravityPacket packet) { + if (packet.gravity.duration() > FIELD_GRAVITY_MAX_DURATION) return false; - if (packet.gravity.priority() > FIELD_GRAVITY_PRIORITY) return false; + if (packet.gravity.priority() > FIELD_GRAVITY_PRIORITY) return false; - if (!packet.gravity.source().equals(FIELD_GRAVITY_SOURCE.toString())) return false; + if (!packet.gravity.source().equals(FIELD_GRAVITY_SOURCE.toString())) return false; - if (packet.gravity.direction() == null) return false; - info.readBlockPos(); - /*Return true if the block is a field generator or plating and could have triggered the gravity change.*/ - return true; - } + if (packet.gravity.direction() == null) return false; + info.readBlockPos(); + /*Return true if the block is a field generator or plating and could have triggered the gravity change.*/ + return true; + } - public static FriendlyByteBuf packInfo(BlockPos block) { - var buf = PacketByteBufs.create(); - buf.writeBlockPos(block); - return buf; - } + public static FriendlyByteBuf packInfo(BlockPos block) { + var buf = PacketByteBufs.create(); + buf.writeBlockPos(block); + return buf; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/PortalCubedClient.java b/src/main/java/com/fusionflux/portalcubed/client/PortalCubedClient.java index 85f4dde2..6c5334aa 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/PortalCubedClient.java +++ b/src/main/java/com/fusionflux/portalcubed/client/PortalCubedClient.java @@ -107,722 +107,722 @@ @ClientOnly public class PortalCubedClient implements ClientModInitializer { - private static final Item[] PORTAL_HUD_DESIRABLES = { - PortalCubedItems.PORTAL_GUN, - PortalCubedItems.PORTAL_GUN_PRIMARY, - PortalCubedItems.PORTAL_GUN_SECONDARY, - PortalCubedItems.PAINT_GUN, - PortalCubedItems.CROWBAR, - Items.AIR - }; - public static final int ZOOM_TIME = 2; - - private static final DecimalFormat CL_SHOWPOS_FORMAT = new DecimalFormat("0.00"); - - private static final File GLOBAL_ADVANCEMENTS_FILE = QuiltLoader.getGameDir().resolve("portal_cubed_global_advancements.dat").toFile(); - private static final Set GLOBAL_ADVANCEMENTS = new HashSet<>(); - - public static long shakeStart; - @Nullable public static BlockPos velocityHelperDragStart; - private static boolean hiddenBlocksVisible; - public static boolean allowCfg; - private static SoundInstance excursionFunnelMusic; - private static boolean portalHudMode = false; - public static FogSettings customFog = null; - - public static int zoomTimer; - public static int zoomDir; - - public static int gelOverlayTimer = -1; - public static ResourceLocation gelOverlayTexture = TextureManager.INTENTIONAL_MISSING_TEXTURE; - - private static PortalRendererImpl renderer; - private static PortalRenderers rendererType; - - public static IPQuaternion cameraInterpStart; - public static long cameraInterpStartTime; - - public static Portal cameraTransformedThroughPortal; - - public static WorldRenderContext worldRenderContext; // QFAPI impl detail: this is a mutable singleton - - public static boolean showPos = false; - - @Override - public void onInitializeClient(ModContainer mod) { - - MenuScreens.register(PortalCubed.FAITH_PLATE_SCREEN_HANDLER, FaithPlateScreen::new); - MenuScreens.register(PortalCubed.VELOCITY_HELPER_SCREEN_HANDLER, VelocityHelperScreen::new); - - registerEntityRenderers(); - registerColorProviders(); - registerEmissiveModels(mod); - PortalCubedClientPackets.registerPackets(); - PortalCubedKeyBindings.register(); - AnimatedEntityTextures.init(); - - HudRenderCallback.EVENT.register(PortalHud::renderPortals); - - // Thanks to https://github.com/JulianWww/Amazia-fabric/blob/main/src/main/java/net/denanu/amazia/GUI/debug/VillagePathingOverlay.java for some code -// WorldRenderEvents.BEFORE_DEBUG_RENDER.register(context -> { -// final BlockPos origin = velocityHelperDragStart; -// if (origin != null) { -// RenderSystem.enableDepthTest(); -// RenderSystem.setShader(GameRenderer::getPositionColorShader); -// final Tessellator tessellator = Tessellator.getInstance(); -// final BufferBuilder bufferBuilder = tessellator.getBufferBuilder(); -// RenderSystem.disableTexture(); -// RenderSystem.disableBlend(); -// RenderSystem.lineWidth(5f); -// bufferBuilder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); + private static final Item[] PORTAL_HUD_DESIRABLES = { + PortalCubedItems.PORTAL_GUN, + PortalCubedItems.PORTAL_GUN_PRIMARY, + PortalCubedItems.PORTAL_GUN_SECONDARY, + PortalCubedItems.PAINT_GUN, + PortalCubedItems.CROWBAR, + Items.AIR + }; + public static final int ZOOM_TIME = 2; + + private static final DecimalFormat CL_SHOWPOS_FORMAT = new DecimalFormat("0.00"); + + private static final File GLOBAL_ADVANCEMENTS_FILE = QuiltLoader.getGameDir().resolve("portal_cubed_global_advancements.dat").toFile(); + private static final Set GLOBAL_ADVANCEMENTS = new HashSet<>(); + + public static long shakeStart; + @Nullable public static BlockPos velocityHelperDragStart; + private static boolean hiddenBlocksVisible; + public static boolean allowCfg; + private static SoundInstance excursionFunnelMusic; + private static boolean portalHudMode = false; + public static FogSettings customFog = null; + + public static int zoomTimer; + public static int zoomDir; + + public static int gelOverlayTimer = -1; + public static ResourceLocation gelOverlayTexture = TextureManager.INTENTIONAL_MISSING_TEXTURE; + + private static PortalRendererImpl renderer; + private static PortalRenderers rendererType; + + public static IPQuaternion cameraInterpStart; + public static long cameraInterpStartTime; + + public static Portal cameraTransformedThroughPortal; + + public static WorldRenderContext worldRenderContext; // QFAPI impl detail: this is a mutable singleton + + public static boolean showPos = false; + + @Override + public void onInitializeClient(ModContainer mod) { + + MenuScreens.register(PortalCubed.FAITH_PLATE_SCREEN_HANDLER, FaithPlateScreen::new); + MenuScreens.register(PortalCubed.VELOCITY_HELPER_SCREEN_HANDLER, VelocityHelperScreen::new); + + registerEntityRenderers(); + registerColorProviders(); + registerEmissiveModels(mod); + PortalCubedClientPackets.registerPackets(); + PortalCubedKeyBindings.register(); + AnimatedEntityTextures.init(); + + HudRenderCallback.EVENT.register(PortalHud::renderPortals); + + // Thanks to https://github.com/JulianWww/Amazia-fabric/blob/main/src/main/java/net/denanu/amazia/GUI/debug/VillagePathingOverlay.java for some code +// WorldRenderEvents.BEFORE_DEBUG_RENDER.register(context -> { +// final BlockPos origin = velocityHelperDragStart; +// if (origin != null) { +// RenderSystem.enableDepthTest(); +// RenderSystem.setShader(GameRenderer::getPositionColorShader); +// final Tessellator tessellator = Tessellator.getInstance(); +// final BufferBuilder bufferBuilder = tessellator.getBufferBuilder(); +// RenderSystem.disableTexture(); +// RenderSystem.disableBlend(); +// RenderSystem.lineWidth(5f); +// bufferBuilder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // -// final Vec3d camPos = context.camera().getPos(); +// final Vec3d camPos = context.camera().getPos(); // -// context.matrixStack().push(); +// context.matrixStack().push(); // -// final Frustum frustum = new Frustum(context.matrixStack().peek().getModel(), RenderSystem.getProjectionMatrix()); -// frustum.setPosition(camPos.x, camPos.y, camPos.z); +// final Frustum frustum = new Frustum(context.matrixStack().peek().getModel(), RenderSystem.getProjectionMatrix()); +// frustum.setPosition(camPos.x, camPos.y, camPos.z); // -// bufferBuilder.vertex( -// velocityHelperDragStart.getX() - camPos.x + 0.5, -// velocityHelperDragStart.getY() - camPos.y + 0.5, -// velocityHelperDragStart.getZ() - camPos.z + 0.5 -// ).color(0.0f, 0.5f, 1.0f, 1.0f).next(); -// assert MinecraftClient.getInstance().cameraEntity != null; -// bufferBuilder.vertex(0, MinecraftClient.getInstance().cameraEntity.getEyeY() - camPos.y, 0).color(0.0f, 0.5f, 1.0f, 1.0f).next(); +// bufferBuilder.vertex( +// velocityHelperDragStart.getX() - camPos.x + 0.5, +// velocityHelperDragStart.getY() - camPos.y + 0.5, +// velocityHelperDragStart.getZ() - camPos.z + 0.5 +// ).color(0.0f, 0.5f, 1.0f, 1.0f).next(); +// assert MinecraftClient.getInstance().cameraEntity != null; +// bufferBuilder.vertex(0, MinecraftClient.getInstance().cameraEntity.getEyeY() - camPos.y, 0).color(0.0f, 0.5f, 1.0f, 1.0f).next(); // -// context.matrixStack().pop(); +// context.matrixStack().pop(); // -// tessellator.draw(); -// RenderSystem.lineWidth(1f); -// RenderSystem.enableBlend(); -// RenderSystem.enableTexture(); -// } -// }); - - ClientTickEvents.START.register(client -> { - if (zoomDir != 0) { - zoomTimer++; - if (zoomDir < 0 && zoomTimer >= ZOOM_TIME) { - zoomDir = 0; - zoomTimer = 0; - } - } - if (isPortalHudMode()) { - assert client.player != null; - while (client.options.keyInventory.consumeClick()) { - PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); - ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); - } - while (client.options.keyPickItem.consumeClick()) { - if (zoomDir == 0) { - zoomDir = 1; - zoomTimer = 0; - } else { - zoomDir = -zoomDir; - zoomTimer = Math.max(ZOOM_TIME - zoomTimer, 0); - } - } - } else if (zoomDir > 0) { - zoomDir = -1; - zoomTimer = Math.max(ZOOM_TIME - zoomTimer, 0); - } - if (zoomDir > 0 && zoomTimer > 100 && client.player.input.getMoveVector().lengthSquared() > 0.1) { - zoomDir = -1; - zoomTimer = 0; - } - if (gelOverlayTimer >= 0) { - gelOverlayTimer++; - } - }); - - ClientTickEvents.END.register(client -> { - if (client.player == null) return; - if (((EntityExt)client.player).isInFunnel()) { - if (excursionFunnelMusic == null) { - excursionFunnelMusic = new SimpleSoundInstance( - PortalCubedSounds.TBEAM_TRAVEL, SoundSource.BLOCKS, - 0.3f, 1f, SoundInstance.createUnseededRandom(), - true, 0, SoundInstance.Attenuation.NONE, - 0.0, 0.0, 0.0, true - ); - client.getSoundManager().play(excursionFunnelMusic); - } else if (excursionFunnelMusic.getVolume() < .3f && excursionFunnelMusic instanceof AbstractSoundInstanceAccessor access) { - access.setVolume(excursionFunnelMusic.getVolume() + 0.05f); - if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor cAccess) { - cAccess.setVolume(1f - excursionFunnelMusic.getVolume() / 2); - } - client.getSoundManager().updateSourceVolume(null, 0); // If first argument is null, all it does is refresh SoundInstance volumes - } - } else if (excursionFunnelMusic != null) { - if (excursionFunnelMusic.getVolume() <= 0f) { - client.getSoundManager().stop(excursionFunnelMusic); - excursionFunnelMusic = null; - if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor access) { - access.setVolume(1f); - client.getSoundManager().updateSourceVolume(null, 0); // See above - } - } else if (excursionFunnelMusic instanceof AbstractSoundInstanceAccessor access) { - access.setVolume(excursionFunnelMusic.getVolume() - 0.05f); - if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor cAccess) { - cAccess.setVolume(1f - excursionFunnelMusic.getVolume() / 2); - } - client.getSoundManager().updateSourceVolume(null, 0); // See above - } - } - if (isPortalHudMode() && !client.player.shouldShowDeathScreen() && client.screen instanceof DeathScreenAccessor deathScreen && deathScreen.getDelayTicker() >= 50) { - client.player.respawn(); - } - }); - - final ResourceLocation toxicGooStillSpriteId = id("block/toxic_goo_still"); - final ResourceLocation toxicGooFlowSpriteId = id("block/toxic_goo_flow"); - FluidRenderHandlerRegistry.INSTANCE.register(PortalCubedFluids.TOXIC_GOO.still, PortalCubedFluids.TOXIC_GOO.flowing, new SimpleFluidRenderHandler(toxicGooStillSpriteId, toxicGooFlowSpriteId)); - - // TODO: Remove this code if it's truly unnecessary -// ClientSpriteRegistryCallback.event(InventoryMenu.BLOCK_ATLAS).register((atlasTexture, registry) -> { -// registry.register(toxicGooStillSpriteId); -// registry.register(toxicGooFlowSpriteId); -// }); - - ItemProperties.register( - PortalCubedBlocks.POWER_BLOCK.asItem(), - new ResourceLocation("level"), - (ClampedItemPropertyFunction)ItemProperties.getProperty( - Items.LIGHT, new ResourceLocation("level") - ) - ); - - WorldRenderEvents.END.register(ctx -> { - final var cameraEntity = ctx.camera().getEntity(); - if (!(ctx.consumers() instanceof final MultiBufferSource.BufferSource consumers)) return; - final var cameraPos = ctx.camera().getPosition(); - ctx.matrixStack().pushPose(); - ctx.matrixStack().translate(-cameraPos.x, -cameraPos.y, -cameraPos.z); - PortalRenderer.renderPhase = PortalRenderPhase.TRACER; - final EntityRenderDispatcher dispatcher = ctx.gameRenderer().getMinecraft().getEntityRenderDispatcher(); - final boolean renderHitboxes = dispatcher.shouldRenderHitBoxes(); - dispatcher.setRenderHitBoxes(false); - for (UUID portalUuid : CalledValues.getPortals(cameraEntity)) { - if ( - !(((LevelExt) ctx.world()).getEntityByUuid(portalUuid) instanceof Portal portal) || - !cameraEntity.getUUID().equals(portal.getOwnerUUID().orElse(null)) - ) continue; - dispatcher.render(portal, portal.getX(), portal.getY(), portal.getZ(), portal.getYRot(), ctx.tickDelta(), ctx.matrixStack(), consumers, LightTexture.FULL_BRIGHT); - } - dispatcher.setRenderHitBoxes(renderHitboxes); - ctx.matrixStack().popPose(); - - RenderSystem.disableCull(); - // depth func change handled in RenderSystemMixin - consumers.endLastBatch(); - PortalRenderer.renderPhase = PortalRenderPhase.ENTITY; - RenderSystem.depthFunc(GL11.GL_LEQUAL); - RenderSystem.enableCull(); - }); - - PortalBlocksLoader.initClient(); - - FloorButtonBlock.enableEasterEgg = true; - - ClientLoginConnectionEvents.INIT.register((handler, client) -> { - allowCfg = true; - portalHudMode = false; - customFog = null; - }); - - ClientTickEvents.START.register(client -> { - if (client.player == null || !isPortalHudMode()) return; - assert client.gameMode != null; - final Inventory inventory = client.player.getInventory(); - inventory.selected = 0; - outer: - for (final Item desirable : PORTAL_HUD_DESIRABLES) { - for (int i = 0, l = inventory.getContainerSize(); i < l; i++) { - if (inventory.getItem(i).is(desirable)) { - if (i != 0) { - for (final Slot slot : client.player.inventoryMenu.slots) { - if (slot.getContainerSlot() == i) { - client.gameMode.handleInventoryMouseClick(0, slot.index, 0, ClickType.SWAP, client.player); - break; - } - } - } - break outer; - } - } - } - if (!inventory.offhand.get(0).isEmpty()) { - boolean found = false; - for (int i = 1; i < inventory.items.size(); ++i) { - if (inventory.items.get(i).isEmpty()) { - found = true; - client.gameMode.handleInventoryMouseClick(0, 45, i, ClickType.SWAP, client.player); - break; - } - } - if (!found) { - client.gameMode.handleInventoryMouseClick(0, 45, 1, ClickType.THROW, client.player); - } - } - }); - - HudRenderCallback.EVENT.register((graphics, tickDelta) -> { - if (!isPortalHudMode()) return; - final Minecraft client = Minecraft.getInstance(); - assert client.player != null; - RenderSystem.setShader(GameRenderer::getPositionColorShader); - RenderSystem.enableBlend(); - final boolean fadeOut = !client.player.shouldShowDeathScreen() && client.screen instanceof DeathScreenAccessor; - if (!fadeOut && client.player.getAbilities().invulnerable) return; - final float red = fadeOut ? 0f : 1f; - final float alpha = fadeOut - ? Math.min(((DeathScreenAccessor)client.screen).getDelayTicker() / 40f, 1f) - : client.player.isDeadOrDying() - ? 0.5f : 1f - Mth.clamp(Mth.lerp( - client.player.getHealth() / client.player.getMaxHealth(), 0.65f, 1f - ), 0f, 1f); - BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); - final Matrix4f matrix = graphics.pose().last().pose(); - final float w = client.getWindow().getGuiScaledWidth(); - final float h = client.getWindow().getGuiScaledHeight(); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - bufferBuilder.vertex(matrix, 0, h, 0).color(red, 0f, 0f, alpha).endVertex(); - bufferBuilder.vertex(matrix, w, h, 0).color(red, 0f, 0f, alpha).endVertex(); - bufferBuilder.vertex(matrix, w, 0, 0).color(red, 0f, 0f, alpha).endVertex(); - bufferBuilder.vertex(matrix, 0, 0, 0).color(red, 0f, 0f, alpha).endVertex(); - BufferUploader.drawWithShader(bufferBuilder.end()); - }); - - HudRenderCallback.EVENT.register((graphics, tickDelta) -> { - if (gelOverlayTimer < 0) return; - if (gelOverlayTimer > 100) { - gelOverlayTimer = -1; - return; - } - float alpha; - if (gelOverlayTimer <= 40) { - alpha = 1; - } else { - alpha = Math.max(0, 1 - (gelOverlayTimer + tickDelta - 40) / 60f); - } - alpha *= PortalCubedConfig.gelOverlayOpacity / 100f; - if (alpha <= 0) return; - - final Minecraft client = Minecraft.getInstance(); - RenderSystem.setShader(GameRenderer::getPositionTexColorShader); - RenderSystem.enableBlend(); - RenderSystem.setShaderTexture(0, gelOverlayTexture); - BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); - final Matrix4f matrix = graphics.pose().last().pose(); - final float w = client.getWindow().getGuiScaledWidth(); - final float h = client.getWindow().getGuiScaledHeight(); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); - bufferBuilder.vertex(matrix, 0, h, 0).uv(0f, 0f).color(1f, 1f, 1f, alpha).endVertex(); - bufferBuilder.vertex(matrix, w, h, 0).uv(1f, 0f).color(1f, 1f, 1f, alpha).endVertex(); - bufferBuilder.vertex(matrix, w, 0, 0).uv(1f, 1f).color(1f, 1f, 1f, alpha).endVertex(); - bufferBuilder.vertex(matrix, 0, 0, 0).uv(0f, 1f).color(1f, 1f, 1f, alpha).endVertex(); - BufferUploader.drawWithShader(bufferBuilder.end()); - }); - - //noinspection UnstableApiUsage - ItemGroupEvents.modifyEntriesEvent(CreativeModeTabs.TOOLS_AND_UTILITIES).register(e -> e.addAfter( - i -> i.getItem() instanceof RecordItem, - List.of( - new ItemStack(PortalCubedItems.STILL_ALIVE), - new ItemStack(PortalCubedItems.CARA_MIA_ADDIO), - new ItemStack(PortalCubedItems.WANT_YOU_GONE), - new ItemStack(PortalCubedItems.RECONSTRUCTING_MORE_SCIENCE) - ), - CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS - )); - - WorldRenderEvents.START.register(context -> worldRenderContext = context); - - HudRenderCallback.EVENT.register((graphics, tickDelta) -> { - if (!showPos) return; - final Minecraft minecraft = Minecraft.getInstance(); - if (minecraft.options.renderDebug) return; - final LocalPlayer player = minecraft.player; - if (player == null) return; - - graphics.drawString(minecraft.font, Component.literal("name: ").append(player.getName()), 2, 11, 0xffffffff); - - graphics.drawString( - minecraft.font, - "pos: " + CL_SHOWPOS_FORMAT.format(player.getX()) + - ' ' + CL_SHOWPOS_FORMAT.format(player.getY()) + - ' ' + CL_SHOWPOS_FORMAT.format(player.getZ()), - 2, 20, 0xffffffff - ); - - IPQuaternion quat = IPQuaternion.getCameraRotation(player.getXRot(), player.getYRot()); - final Optional rotation = interpCamera(); - if (rotation.isPresent()) { - quat = quat.hamiltonProduct(rotation.get()); - } - final Vector3d angle = quat.toQuaterniond().getEulerAnglesZXY(new Vector3d()); - graphics.drawString( - minecraft.font, - "ang: " + CL_SHOWPOS_FORMAT.format(Math.toDegrees(angle.x)) + - ' ' + CL_SHOWPOS_FORMAT.format(Mth.wrapDegrees(Math.toDegrees(angle.y) + 180)) + - ' ' + CL_SHOWPOS_FORMAT.format(Math.toDegrees(angle.z)), - 2, 29, 0xffffffff - ); - - graphics.drawString( - minecraft.font, - "vel: " + CL_SHOWPOS_FORMAT.format(player.getDeltaMovement().length()), - 2, 38, 0xffffffff - ); - }); - - WorldRenderEvents.BLOCK_OUTLINE.register((worldRenderContext, blockOutlineContext) -> { - final Minecraft minecraft = Minecraft.getInstance(); - final HitResult hitResult = minecraft.hitResult; - if (hitResult == null || hitResult.getType() != HitResult.Type.BLOCK) { - return true; - } - final Player player = minecraft.player; - assert player != null; - ItemStack useStack = null; - InteractionHand useHand = null; - MultiblockItem useItem = null; - for (final InteractionHand hand : InteractionHand.values()) { - final ItemStack stack = player.getItemInHand(hand); - if ( - stack.getItem() instanceof MultiblockItem multiblockItem - ) { - useStack = stack; - useHand = hand; - useItem = multiblockItem; - break; - } - } - if (useItem == null) { - return true; - } - final BlockHitResult blockHitResult = (BlockHitResult)hitResult; - final BlockPlaceContext blockPlaceContext = new BlockPlaceContext(player, useHand, useStack, blockHitResult); - BlockPos pos = blockHitResult.getBlockPos(); - if (!worldRenderContext.world().getBlockState(pos).canBeReplaced(blockPlaceContext)) { - pos = pos.relative(blockHitResult.getDirection()); - } - final TwoByTwo twoByTwo = useItem.findValidPlacement( - worldRenderContext.world(), - useItem.getMultiblockBlock().getStateForPlacement(blockPlaceContext), - pos, - blockPlaceContext.getHorizontalDirection() - ); - if (twoByTwo != null) { - //noinspection DataFlowIssue - LevelRenderer.renderLineBox( - worldRenderContext.matrixStack(), - worldRenderContext.consumers().getBuffer(RenderType.lines()), - twoByTwo.toBox(0).expandTowards(1, 1, 1).move( - -blockOutlineContext.cameraX(), - -blockOutlineContext.cameraY(), - -blockOutlineContext.cameraZ() - ), - 0.25f, 0.25f, 1f, 0.6f - ); - } - return true; - }); - - try { - final CompoundTag compound = NbtIo.readCompressed(GLOBAL_ADVANCEMENTS_FILE); - for (final Tag element : compound.getList("Advancements", Tag.TAG_STRING)) { - GLOBAL_ADVANCEMENTS.add(new ResourceLocation(element.getAsString())); - } - } catch (Exception e) { - LOGGER.warn("Failed to load global advancements", e); - } - - ClientCommandRegistrationCallback.EVENT.register((dispatcher, buildContext, environment) -> { - if (QuiltLoader.isDevelopmentEnvironment()) { - dispatcher.register(literal("face") - .executes(ctx -> { - final Entity entity = ctx.getSource().getEntity(); - final Direction direction = entity.getDirection(); - entity.setXRot(entity.getXRot() < -45 ? -90 : entity.getXRot() > 45 ? 90 : 0); - entity.setYRot(direction.toYRot()); - return 1; - }) - ); - dispatcher.register(literal("center") - .executes(ctx -> { - final Entity entity = ctx.getSource().getEntity(); - entity.setPos( - entity.onGround() - ? Vec3.atBottomCenterOf(entity.blockPosition()) - : Vec3.atCenterOf(entity.blockPosition()) - ); - return 1; - }) - ); - } - dispatcher.register(literal("showpos") - .then(argument("enabled", BoolArgumentType.bool()) - .executes(ctx -> { - showPos = BoolArgumentType.getBool(ctx, "enabled"); - ctx.getSource().sendFeedback(Component.literal("showpos = " + showPos)); - return showPos ? 1 : 0; - }) - ) - .executes(ctx -> { - ctx.getSource().sendFeedback(Component.literal("showpos = " + showPos)); - return showPos ? 1 : 0; - }) - ); - }); - } - - public static void zoomGoBrrrr(MutableDouble fov) { - var tickDelta = Minecraft.getInstance().getFrameTime(); - if (zoomDir == 0) return; - if (zoomDir > 0) { - if (zoomTimer < ZOOM_TIME) { - fov.setValue(Mth.lerp((zoomTimer + tickDelta) / ZOOM_TIME, fov.getValue(), fov.getValue() / 2)); - } else { - fov.setValue(fov.getValue() * .5); - } - } else { - fov.setValue(Mth.lerp((zoomTimer + tickDelta) / ZOOM_TIME, fov.getValue() / 2, fov.getValue())); - } - } - - public static void moveCameraIfDead(Camera camera, Entity cameraEntity, CameraType perspective, float tickDelta, CameraControl ctrl) { - var pos = ctrl.getPos(); - - final var minecraft = Minecraft.getInstance(); - if (PortalCubedClient.isPortalHudMode() && minecraft.screen instanceof DeathScreen) { - ctrl.setPos(pos.add(0, -1, 0)); - } - } - - public static void transformCameraIntersectingPortal(Camera camera, Entity cameraEntity, CameraType perspective, float tickDelta, CameraControl ctrl) { - final Vec3 entityPos = cameraEntity.getPosition(tickDelta); - final Vec3 startPos = entityPos.add(ctrl.getPos().subtract(entityPos).normalize().scale(0.1)); - final Vec3 endPos = ctrl.getPos(); - final var transformed = PortalDirectionUtils.simpleTransformPassingVector( - cameraEntity, startPos, endPos, p -> p.getNormal().y < 0 - ); - if (transformed != null) { - cameraTransformedThroughPortal = transformed.second(); - ctrl.setPos(transformed.first()); - final Quaternionf cameraRot = camera.rotation().mul( - cameraTransformedThroughPortal.getTransformQuat().toQuaternionf() - ); - camera.getLookVector().set(0.0F, 0.0F, 1.0F).rotate(cameraRot); - camera.getUpVector().set(0.0F, 1.0F, 0.0F).rotate(cameraRot); - camera.getLeftVector().set(1.0F, 0.0F, 0.0F).rotate(cameraRot); - if (camera.isDetached()) { - ((CameraExt)camera).backCameraUp(transformed.first()); - ctrl.setPos(camera.getPosition()); - } - } else { - cameraTransformedThroughPortal = null; - } - } - - private void registerEmissiveModels(ModContainer mod) { - try (Reader reader = Files.newBufferedReader(mod.getPath("emissives.json"), StandardCharsets.UTF_8)) { - for (final var entry : GsonHelper.parse(reader).entrySet()) { - if (entry.getValue().isJsonArray()) { - for (final var value : entry.getValue().getAsJsonArray()) { - EmissiveSpriteRegistry.register(id(entry.getKey()), id(value.getAsString())); - } - } else { - EmissiveSpriteRegistry.register(id(entry.getKey()), id(entry.getValue().getAsString())); - } - } - } catch (IOException e) { - PortalCubed.LOGGER.error("Failed to load emissives.json", e); - } - } - - private void registerColorProviders() { - ColorProviderRegistry.ITEM.register( - (stack, tintIndex) -> tintIndex > 0 ? -1 : ((PortalGun) stack.getItem()).getSidedColor(stack), - PortalCubedItems.PORTAL_GUN, PortalCubedItems.PORTAL_GUN_PRIMARY, PortalCubedItems.PORTAL_GUN_SECONDARY - ); - } - - private void registerEntityRenderers() { - EntityModelLayerRegistry.registerModelLayer(PortalModel.MAIN_LAYER, PortalModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.PORTAL, PortalRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(StorageCubeModel.STORAGE_CUBE_MAIN_LAYER, StorageCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.STORAGE_CUBE, StorageCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER, CompanionCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.COMPANION_CUBE, CompanionCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(RadioModel.RADIO_MAIN_LAYER, RadioModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.RADIO, RadioRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(RedirectionCubeModel.REDIRECTION_CUBE_MAIN_LAYER, RedirectionCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.REDIRECTION_CUBE, RedirectionCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(SchrodingerCubeModel.SCHRODINGER_CUBE_MAIN_LAYER, SchrodingerCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.SCHRODINGER_CUBE, SchrodingerCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(OldApModel.OLD_AP_CUBE_MAIN_LAYER, OldApModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.OLD_AP_CUBE, OldApRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(Portal1CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER, Portal1CompanionCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, Portal1CompanionCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(Portal1StorageCubeModel.COMPANION_CUBE_MAIN_LAYER, Portal1StorageCubeModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, Portal1StorageCubeRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(BeansModel.BEANS_LAYER, BeansModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.BEANS, BeansRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(MugModel.MUG_LAYER, MugModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.MUG, MugRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(JugModel.JUG_LAYER, JugModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.JUG, JugRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(ComputerModel.COMPUTER_LAYER, ComputerModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.COMPUTER, ComputerRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(ChairModel.CHAIR_LAYER, ChairModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.CHAIR, ChairRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(LilPineappleModel.LIL_PINEAPPLE, LilPineappleModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.LIL_PINEAPPLE, LilPineappleRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(HoopyModel.HOOPY_LAYER, HoopyModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.HOOPY, HoopyRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(CoreFrameModel.CORE_FRAME_LAYER, CoreFrameModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.CORE_FRAME, CoreFrameRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(AngerCoreModel.ANGER_CORE_LAYER, AngerCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.ANGER_CORE, AngerCoreRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(CakeCoreModel.CAKE_CORE_LAYER, CakeCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.CAKE_CORE, CakeCoreRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(CuriosityCoreModel.CURIOSITY_CORE_LAYER, CuriosityCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.CURIOSITY_CORE, CuriosityCoreRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(MoralityCoreModel.MORTALITY_CORE_LAYER, MoralityCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.MORALITY_CORE, MoralityCoreRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(SpaceCoreModel.SPACE_CORE_LAYER, SpaceCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.SPACE_CORE, SpaceCoreRenderer::new); - EntityModelLayerRegistry.registerModelLayer(FactCoreModel.FACT_CORE_LAYER, FactCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.FACT_CORE, FactCoreRenderer::new); - EntityModelLayerRegistry.registerModelLayer(AdventureCoreModel.ADVENTURE_CORE_LAYER, AdventureCoreModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.ADVENTURE_CORE, AdventureCoreRenderer::new); - - EntityRendererRegistry.register(PortalCubedEntities.PROPULSION_GEL_BLOB, GelBlobRenderer::new); - EntityRendererRegistry.register(PortalCubedEntities.REPULSION_GEL_BLOB, GelBlobRenderer::new); - EntityRendererRegistry.register(PortalCubedEntities.ADHESION_GEL_BLOB, GelBlobRenderer::new); - EntityRendererRegistry.register(PortalCubedEntities.CONVERSION_GEL_BLOB, GelBlobRenderer::new); - EntityRendererRegistry.register(PortalCubedEntities.REFLECTION_GEL_BLOB, GelBlobRenderer::new); - - EntityRendererRegistry.register(PortalCubedEntities.EXCURSION_FUNNEL, ExcursionFunnelRenderer::new); - - BlockEntityRenderers.register(PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY, VelocityHelperRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(RocketTurretRenderer.ROCKET_TURRET_LAYER, RocketTurretModel::getTexturedModelData); - BlockEntityRenderers.register(PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY, RocketTurretRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(RocketRenderer.ROCKET_LAYER, RocketModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.ROCKET, RocketRenderer::new); - - EntityRendererRegistry.register(PortalCubedEntities.ENERGY_PELLET, EnergyPelletRenderer::new); - - BlockEntityRenderers.register(PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY, LaserEmitterRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(FaithPlateRenderer.FAITH_PLATE_LAYER, FaithPlateModel::getTexturedModelData); - BlockEntityRenderers.register(PortalCubedBlocks.FAITH_PLATE_BLOCK_ENTITY, FaithPlateRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(BetaFaithPlateRenderer.BETA_FAITH_PLATE_LAYER, BetaFaithPlateModel::getTexturedModelData); - BlockEntityRenderers.register(PortalCubedBlocks.BETA_FAITH_PLATE_BLOCK_ENTITY, BetaFaithPlateRenderer::new); - - EntityModelLayerRegistry.registerModelLayer(TurretRenderer.TURRET_LAYER, TurretModel::getTexturedModelData); - EntityRendererRegistry.register(PortalCubedEntities.TURRET, TurretRenderer::new); +// tessellator.draw(); +// RenderSystem.lineWidth(1f); +// RenderSystem.enableBlend(); +// RenderSystem.enableTexture(); +// } +// }); + + ClientTickEvents.START.register(client -> { + if (zoomDir != 0) { + zoomTimer++; + if (zoomDir < 0 && zoomTimer >= ZOOM_TIME) { + zoomDir = 0; + zoomTimer = 0; + } + } + if (isPortalHudMode()) { + assert client.player != null; + while (client.options.keyInventory.consumeClick()) { + PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); + ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); + } + while (client.options.keyPickItem.consumeClick()) { + if (zoomDir == 0) { + zoomDir = 1; + zoomTimer = 0; + } else { + zoomDir = -zoomDir; + zoomTimer = Math.max(ZOOM_TIME - zoomTimer, 0); + } + } + } else if (zoomDir > 0) { + zoomDir = -1; + zoomTimer = Math.max(ZOOM_TIME - zoomTimer, 0); + } + if (zoomDir > 0 && zoomTimer > 100 && client.player.input.getMoveVector().lengthSquared() > 0.1) { + zoomDir = -1; + zoomTimer = 0; + } + if (gelOverlayTimer >= 0) { + gelOverlayTimer++; + } + }); + + ClientTickEvents.END.register(client -> { + if (client.player == null) return; + if (((EntityExt)client.player).isInFunnel()) { + if (excursionFunnelMusic == null) { + excursionFunnelMusic = new SimpleSoundInstance( + PortalCubedSounds.TBEAM_TRAVEL, SoundSource.BLOCKS, + 0.3f, 1f, SoundInstance.createUnseededRandom(), + true, 0, SoundInstance.Attenuation.NONE, + 0.0, 0.0, 0.0, true + ); + client.getSoundManager().play(excursionFunnelMusic); + } else if (excursionFunnelMusic.getVolume() < .3f && excursionFunnelMusic instanceof AbstractSoundInstanceAccessor access) { + access.setVolume(excursionFunnelMusic.getVolume() + 0.05f); + if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor cAccess) { + cAccess.setVolume(1f - excursionFunnelMusic.getVolume() / 2); + } + client.getSoundManager().updateSourceVolume(null, 0); // If first argument is null, all it does is refresh SoundInstance volumes + } + } else if (excursionFunnelMusic != null) { + if (excursionFunnelMusic.getVolume() <= 0f) { + client.getSoundManager().stop(excursionFunnelMusic); + excursionFunnelMusic = null; + if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor access) { + access.setVolume(1f); + client.getSoundManager().updateSourceVolume(null, 0); // See above + } + } else if (excursionFunnelMusic instanceof AbstractSoundInstanceAccessor access) { + access.setVolume(excursionFunnelMusic.getVolume() - 0.05f); + if (((MusicManagerAccessor)client.getMusicManager()).getCurrentMusic() instanceof AbstractSoundInstanceAccessor cAccess) { + cAccess.setVolume(1f - excursionFunnelMusic.getVolume() / 2); + } + client.getSoundManager().updateSourceVolume(null, 0); // See above + } + } + if (isPortalHudMode() && !client.player.shouldShowDeathScreen() && client.screen instanceof DeathScreenAccessor deathScreen && deathScreen.getDelayTicker() >= 50) { + client.player.respawn(); + } + }); + + final ResourceLocation toxicGooStillSpriteId = id("block/toxic_goo_still"); + final ResourceLocation toxicGooFlowSpriteId = id("block/toxic_goo_flow"); + FluidRenderHandlerRegistry.INSTANCE.register(PortalCubedFluids.TOXIC_GOO.still, PortalCubedFluids.TOXIC_GOO.flowing, new SimpleFluidRenderHandler(toxicGooStillSpriteId, toxicGooFlowSpriteId)); + + // TODO: Remove this code if it's truly unnecessary +// ClientSpriteRegistryCallback.event(InventoryMenu.BLOCK_ATLAS).register((atlasTexture, registry) -> { +// registry.register(toxicGooStillSpriteId); +// registry.register(toxicGooFlowSpriteId); +// }); + + ItemProperties.register( + PortalCubedBlocks.POWER_BLOCK.asItem(), + new ResourceLocation("level"), + (ClampedItemPropertyFunction)ItemProperties.getProperty( + Items.LIGHT, new ResourceLocation("level") + ) + ); + + WorldRenderEvents.END.register(ctx -> { + final var cameraEntity = ctx.camera().getEntity(); + if (!(ctx.consumers() instanceof final MultiBufferSource.BufferSource consumers)) return; + final var cameraPos = ctx.camera().getPosition(); + ctx.matrixStack().pushPose(); + ctx.matrixStack().translate(-cameraPos.x, -cameraPos.y, -cameraPos.z); + PortalRenderer.renderPhase = PortalRenderPhase.TRACER; + final EntityRenderDispatcher dispatcher = ctx.gameRenderer().getMinecraft().getEntityRenderDispatcher(); + final boolean renderHitboxes = dispatcher.shouldRenderHitBoxes(); + dispatcher.setRenderHitBoxes(false); + for (UUID portalUuid : CalledValues.getPortals(cameraEntity)) { + if ( + !(((LevelExt) ctx.world()).getEntityByUuid(portalUuid) instanceof Portal portal) || + !cameraEntity.getUUID().equals(portal.getOwnerUUID().orElse(null)) + ) continue; + dispatcher.render(portal, portal.getX(), portal.getY(), portal.getZ(), portal.getYRot(), ctx.tickDelta(), ctx.matrixStack(), consumers, LightTexture.FULL_BRIGHT); + } + dispatcher.setRenderHitBoxes(renderHitboxes); + ctx.matrixStack().popPose(); + + RenderSystem.disableCull(); + // depth func change handled in RenderSystemMixin + consumers.endLastBatch(); + PortalRenderer.renderPhase = PortalRenderPhase.ENTITY; + RenderSystem.depthFunc(GL11.GL_LEQUAL); + RenderSystem.enableCull(); + }); + + PortalBlocksLoader.initClient(); + + FloorButtonBlock.enableEasterEgg = true; + + ClientLoginConnectionEvents.INIT.register((handler, client) -> { + allowCfg = true; + portalHudMode = false; + customFog = null; + }); + + ClientTickEvents.START.register(client -> { + if (client.player == null || !isPortalHudMode()) return; + assert client.gameMode != null; + final Inventory inventory = client.player.getInventory(); + inventory.selected = 0; + outer: + for (final Item desirable : PORTAL_HUD_DESIRABLES) { + for (int i = 0, l = inventory.getContainerSize(); i < l; i++) { + if (inventory.getItem(i).is(desirable)) { + if (i != 0) { + for (final Slot slot : client.player.inventoryMenu.slots) { + if (slot.getContainerSlot() == i) { + client.gameMode.handleInventoryMouseClick(0, slot.index, 0, ClickType.SWAP, client.player); + break; + } + } + } + break outer; + } + } + } + if (!inventory.offhand.get(0).isEmpty()) { + boolean found = false; + for (int i = 1; i < inventory.items.size(); ++i) { + if (inventory.items.get(i).isEmpty()) { + found = true; + client.gameMode.handleInventoryMouseClick(0, 45, i, ClickType.SWAP, client.player); + break; + } + } + if (!found) { + client.gameMode.handleInventoryMouseClick(0, 45, 1, ClickType.THROW, client.player); + } + } + }); + + HudRenderCallback.EVENT.register((graphics, tickDelta) -> { + if (!isPortalHudMode()) return; + final Minecraft client = Minecraft.getInstance(); + assert client.player != null; + RenderSystem.setShader(GameRenderer::getPositionColorShader); + RenderSystem.enableBlend(); + final boolean fadeOut = !client.player.shouldShowDeathScreen() && client.screen instanceof DeathScreenAccessor; + if (!fadeOut && client.player.getAbilities().invulnerable) return; + final float red = fadeOut ? 0f : 1f; + final float alpha = fadeOut + ? Math.min(((DeathScreenAccessor)client.screen).getDelayTicker() / 40f, 1f) + : client.player.isDeadOrDying() + ? 0.5f : 1f - Mth.clamp(Mth.lerp( + client.player.getHealth() / client.player.getMaxHealth(), 0.65f, 1f + ), 0f, 1f); + BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); + final Matrix4f matrix = graphics.pose().last().pose(); + final float w = client.getWindow().getGuiScaledWidth(); + final float h = client.getWindow().getGuiScaledHeight(); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + bufferBuilder.vertex(matrix, 0, h, 0).color(red, 0f, 0f, alpha).endVertex(); + bufferBuilder.vertex(matrix, w, h, 0).color(red, 0f, 0f, alpha).endVertex(); + bufferBuilder.vertex(matrix, w, 0, 0).color(red, 0f, 0f, alpha).endVertex(); + bufferBuilder.vertex(matrix, 0, 0, 0).color(red, 0f, 0f, alpha).endVertex(); + BufferUploader.drawWithShader(bufferBuilder.end()); + }); + + HudRenderCallback.EVENT.register((graphics, tickDelta) -> { + if (gelOverlayTimer < 0) return; + if (gelOverlayTimer > 100) { + gelOverlayTimer = -1; + return; + } + float alpha; + if (gelOverlayTimer <= 40) { + alpha = 1; + } else { + alpha = Math.max(0, 1 - (gelOverlayTimer + tickDelta - 40) / 60f); + } + alpha *= PortalCubedConfig.gelOverlayOpacity / 100f; + if (alpha <= 0) return; + + final Minecraft client = Minecraft.getInstance(); + RenderSystem.setShader(GameRenderer::getPositionTexColorShader); + RenderSystem.enableBlend(); + RenderSystem.setShaderTexture(0, gelOverlayTexture); + BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); + final Matrix4f matrix = graphics.pose().last().pose(); + final float w = client.getWindow().getGuiScaledWidth(); + final float h = client.getWindow().getGuiScaledHeight(); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + bufferBuilder.vertex(matrix, 0, h, 0).uv(0f, 0f).color(1f, 1f, 1f, alpha).endVertex(); + bufferBuilder.vertex(matrix, w, h, 0).uv(1f, 0f).color(1f, 1f, 1f, alpha).endVertex(); + bufferBuilder.vertex(matrix, w, 0, 0).uv(1f, 1f).color(1f, 1f, 1f, alpha).endVertex(); + bufferBuilder.vertex(matrix, 0, 0, 0).uv(0f, 1f).color(1f, 1f, 1f, alpha).endVertex(); + BufferUploader.drawWithShader(bufferBuilder.end()); + }); + + //noinspection UnstableApiUsage + ItemGroupEvents.modifyEntriesEvent(CreativeModeTabs.TOOLS_AND_UTILITIES).register(e -> e.addAfter( + i -> i.getItem() instanceof RecordItem, + List.of( + new ItemStack(PortalCubedItems.STILL_ALIVE), + new ItemStack(PortalCubedItems.CARA_MIA_ADDIO), + new ItemStack(PortalCubedItems.WANT_YOU_GONE), + new ItemStack(PortalCubedItems.RECONSTRUCTING_MORE_SCIENCE) + ), + CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS + )); + + WorldRenderEvents.START.register(context -> worldRenderContext = context); + + HudRenderCallback.EVENT.register((graphics, tickDelta) -> { + if (!showPos) return; + final Minecraft minecraft = Minecraft.getInstance(); + if (minecraft.options.renderDebug) return; + final LocalPlayer player = minecraft.player; + if (player == null) return; + + graphics.drawString(minecraft.font, Component.literal("name: ").append(player.getName()), 2, 11, 0xffffffff); + + graphics.drawString( + minecraft.font, + "pos: " + CL_SHOWPOS_FORMAT.format(player.getX()) + + ' ' + CL_SHOWPOS_FORMAT.format(player.getY()) + + ' ' + CL_SHOWPOS_FORMAT.format(player.getZ()), + 2, 20, 0xffffffff + ); + + IPQuaternion quat = IPQuaternion.getCameraRotation(player.getXRot(), player.getYRot()); + final Optional rotation = interpCamera(); + if (rotation.isPresent()) { + quat = quat.hamiltonProduct(rotation.get()); + } + final Vector3d angle = quat.toQuaterniond().getEulerAnglesZXY(new Vector3d()); + graphics.drawString( + minecraft.font, + "ang: " + CL_SHOWPOS_FORMAT.format(Math.toDegrees(angle.x)) + + ' ' + CL_SHOWPOS_FORMAT.format(Mth.wrapDegrees(Math.toDegrees(angle.y) + 180)) + + ' ' + CL_SHOWPOS_FORMAT.format(Math.toDegrees(angle.z)), + 2, 29, 0xffffffff + ); + + graphics.drawString( + minecraft.font, + "vel: " + CL_SHOWPOS_FORMAT.format(player.getDeltaMovement().length()), + 2, 38, 0xffffffff + ); + }); + + WorldRenderEvents.BLOCK_OUTLINE.register((worldRenderContext, blockOutlineContext) -> { + final Minecraft minecraft = Minecraft.getInstance(); + final HitResult hitResult = minecraft.hitResult; + if (hitResult == null || hitResult.getType() != HitResult.Type.BLOCK) { + return true; + } + final Player player = minecraft.player; + assert player != null; + ItemStack useStack = null; + InteractionHand useHand = null; + MultiblockItem useItem = null; + for (final InteractionHand hand : InteractionHand.values()) { + final ItemStack stack = player.getItemInHand(hand); + if ( + stack.getItem() instanceof MultiblockItem multiblockItem + ) { + useStack = stack; + useHand = hand; + useItem = multiblockItem; + break; + } + } + if (useItem == null) { + return true; + } + final BlockHitResult blockHitResult = (BlockHitResult)hitResult; + final BlockPlaceContext blockPlaceContext = new BlockPlaceContext(player, useHand, useStack, blockHitResult); + BlockPos pos = blockHitResult.getBlockPos(); + if (!worldRenderContext.world().getBlockState(pos).canBeReplaced(blockPlaceContext)) { + pos = pos.relative(blockHitResult.getDirection()); + } + final TwoByTwo twoByTwo = useItem.findValidPlacement( + worldRenderContext.world(), + useItem.getMultiblockBlock().getStateForPlacement(blockPlaceContext), + pos, + blockPlaceContext.getHorizontalDirection() + ); + if (twoByTwo != null) { + //noinspection DataFlowIssue + LevelRenderer.renderLineBox( + worldRenderContext.matrixStack(), + worldRenderContext.consumers().getBuffer(RenderType.lines()), + twoByTwo.toBox(0).expandTowards(1, 1, 1).move( + -blockOutlineContext.cameraX(), + -blockOutlineContext.cameraY(), + -blockOutlineContext.cameraZ() + ), + 0.25f, 0.25f, 1f, 0.6f + ); + } + return true; + }); + + try { + final CompoundTag compound = NbtIo.readCompressed(GLOBAL_ADVANCEMENTS_FILE); + for (final Tag element : compound.getList("Advancements", Tag.TAG_STRING)) { + GLOBAL_ADVANCEMENTS.add(new ResourceLocation(element.getAsString())); + } + } catch (Exception e) { + LOGGER.warn("Failed to load global advancements", e); + } + + ClientCommandRegistrationCallback.EVENT.register((dispatcher, buildContext, environment) -> { + if (QuiltLoader.isDevelopmentEnvironment()) { + dispatcher.register(literal("face") + .executes(ctx -> { + final Entity entity = ctx.getSource().getEntity(); + final Direction direction = entity.getDirection(); + entity.setXRot(entity.getXRot() < -45 ? -90 : entity.getXRot() > 45 ? 90 : 0); + entity.setYRot(direction.toYRot()); + return 1; + }) + ); + dispatcher.register(literal("center") + .executes(ctx -> { + final Entity entity = ctx.getSource().getEntity(); + entity.setPos( + entity.onGround() + ? Vec3.atBottomCenterOf(entity.blockPosition()) + : Vec3.atCenterOf(entity.blockPosition()) + ); + return 1; + }) + ); + } + dispatcher.register(literal("showpos") + .then(argument("enabled", BoolArgumentType.bool()) + .executes(ctx -> { + showPos = BoolArgumentType.getBool(ctx, "enabled"); + ctx.getSource().sendFeedback(Component.literal("showpos = " + showPos)); + return showPos ? 1 : 0; + }) + ) + .executes(ctx -> { + ctx.getSource().sendFeedback(Component.literal("showpos = " + showPos)); + return showPos ? 1 : 0; + }) + ); + }); + } + + public static void zoomGoBrrrr(MutableDouble fov) { + var tickDelta = Minecraft.getInstance().getFrameTime(); + if (zoomDir == 0) return; + if (zoomDir > 0) { + if (zoomTimer < ZOOM_TIME) { + fov.setValue(Mth.lerp((zoomTimer + tickDelta) / ZOOM_TIME, fov.getValue(), fov.getValue() / 2)); + } else { + fov.setValue(fov.getValue() * .5); + } + } else { + fov.setValue(Mth.lerp((zoomTimer + tickDelta) / ZOOM_TIME, fov.getValue() / 2, fov.getValue())); + } + } + + public static void moveCameraIfDead(Camera camera, Entity cameraEntity, CameraType perspective, float tickDelta, CameraControl ctrl) { + var pos = ctrl.getPos(); + + final var minecraft = Minecraft.getInstance(); + if (PortalCubedClient.isPortalHudMode() && minecraft.screen instanceof DeathScreen) { + ctrl.setPos(pos.add(0, -1, 0)); + } + } + + public static void transformCameraIntersectingPortal(Camera camera, Entity cameraEntity, CameraType perspective, float tickDelta, CameraControl ctrl) { + final Vec3 entityPos = cameraEntity.getPosition(tickDelta); + final Vec3 startPos = entityPos.add(ctrl.getPos().subtract(entityPos).normalize().scale(0.1)); + final Vec3 endPos = ctrl.getPos(); + final var transformed = PortalDirectionUtils.simpleTransformPassingVector( + cameraEntity, startPos, endPos, p -> p.getNormal().y < 0 + ); + if (transformed != null) { + cameraTransformedThroughPortal = transformed.second(); + ctrl.setPos(transformed.first()); + final Quaternionf cameraRot = camera.rotation().mul( + cameraTransformedThroughPortal.getTransformQuat().toQuaternionf() + ); + camera.getLookVector().set(0.0F, 0.0F, 1.0F).rotate(cameraRot); + camera.getUpVector().set(0.0F, 1.0F, 0.0F).rotate(cameraRot); + camera.getLeftVector().set(1.0F, 0.0F, 0.0F).rotate(cameraRot); + if (camera.isDetached()) { + ((CameraExt)camera).backCameraUp(transformed.first()); + ctrl.setPos(camera.getPosition()); + } + } else { + cameraTransformedThroughPortal = null; + } + } + + private void registerEmissiveModels(ModContainer mod) { + try (Reader reader = Files.newBufferedReader(mod.getPath("emissives.json"), StandardCharsets.UTF_8)) { + for (final var entry : GsonHelper.parse(reader).entrySet()) { + if (entry.getValue().isJsonArray()) { + for (final var value : entry.getValue().getAsJsonArray()) { + EmissiveSpriteRegistry.register(id(entry.getKey()), id(value.getAsString())); + } + } else { + EmissiveSpriteRegistry.register(id(entry.getKey()), id(entry.getValue().getAsString())); + } + } + } catch (IOException e) { + PortalCubed.LOGGER.error("Failed to load emissives.json", e); + } + } + + private void registerColorProviders() { + ColorProviderRegistry.ITEM.register( + (stack, tintIndex) -> tintIndex > 0 ? -1 : ((PortalGun) stack.getItem()).getSidedColor(stack), + PortalCubedItems.PORTAL_GUN, PortalCubedItems.PORTAL_GUN_PRIMARY, PortalCubedItems.PORTAL_GUN_SECONDARY + ); + } + + private void registerEntityRenderers() { + EntityModelLayerRegistry.registerModelLayer(PortalModel.MAIN_LAYER, PortalModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.PORTAL, PortalRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(StorageCubeModel.STORAGE_CUBE_MAIN_LAYER, StorageCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.STORAGE_CUBE, StorageCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER, CompanionCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.COMPANION_CUBE, CompanionCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(RadioModel.RADIO_MAIN_LAYER, RadioModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.RADIO, RadioRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(RedirectionCubeModel.REDIRECTION_CUBE_MAIN_LAYER, RedirectionCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.REDIRECTION_CUBE, RedirectionCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(SchrodingerCubeModel.SCHRODINGER_CUBE_MAIN_LAYER, SchrodingerCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.SCHRODINGER_CUBE, SchrodingerCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(OldApModel.OLD_AP_CUBE_MAIN_LAYER, OldApModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.OLD_AP_CUBE, OldApRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(Portal1CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER, Portal1CompanionCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, Portal1CompanionCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(Portal1StorageCubeModel.COMPANION_CUBE_MAIN_LAYER, Portal1StorageCubeModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, Portal1StorageCubeRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(BeansModel.BEANS_LAYER, BeansModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.BEANS, BeansRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(MugModel.MUG_LAYER, MugModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.MUG, MugRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(JugModel.JUG_LAYER, JugModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.JUG, JugRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(ComputerModel.COMPUTER_LAYER, ComputerModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.COMPUTER, ComputerRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(ChairModel.CHAIR_LAYER, ChairModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.CHAIR, ChairRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(LilPineappleModel.LIL_PINEAPPLE, LilPineappleModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.LIL_PINEAPPLE, LilPineappleRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(HoopyModel.HOOPY_LAYER, HoopyModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.HOOPY, HoopyRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(CoreFrameModel.CORE_FRAME_LAYER, CoreFrameModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.CORE_FRAME, CoreFrameRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(AngerCoreModel.ANGER_CORE_LAYER, AngerCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.ANGER_CORE, AngerCoreRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(CakeCoreModel.CAKE_CORE_LAYER, CakeCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.CAKE_CORE, CakeCoreRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(CuriosityCoreModel.CURIOSITY_CORE_LAYER, CuriosityCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.CURIOSITY_CORE, CuriosityCoreRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(MoralityCoreModel.MORTALITY_CORE_LAYER, MoralityCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.MORALITY_CORE, MoralityCoreRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(SpaceCoreModel.SPACE_CORE_LAYER, SpaceCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.SPACE_CORE, SpaceCoreRenderer::new); + EntityModelLayerRegistry.registerModelLayer(FactCoreModel.FACT_CORE_LAYER, FactCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.FACT_CORE, FactCoreRenderer::new); + EntityModelLayerRegistry.registerModelLayer(AdventureCoreModel.ADVENTURE_CORE_LAYER, AdventureCoreModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.ADVENTURE_CORE, AdventureCoreRenderer::new); + + EntityRendererRegistry.register(PortalCubedEntities.PROPULSION_GEL_BLOB, GelBlobRenderer::new); + EntityRendererRegistry.register(PortalCubedEntities.REPULSION_GEL_BLOB, GelBlobRenderer::new); + EntityRendererRegistry.register(PortalCubedEntities.ADHESION_GEL_BLOB, GelBlobRenderer::new); + EntityRendererRegistry.register(PortalCubedEntities.CONVERSION_GEL_BLOB, GelBlobRenderer::new); + EntityRendererRegistry.register(PortalCubedEntities.REFLECTION_GEL_BLOB, GelBlobRenderer::new); + + EntityRendererRegistry.register(PortalCubedEntities.EXCURSION_FUNNEL, ExcursionFunnelRenderer::new); + + BlockEntityRenderers.register(PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY, VelocityHelperRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(RocketTurretRenderer.ROCKET_TURRET_LAYER, RocketTurretModel::getTexturedModelData); + BlockEntityRenderers.register(PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY, RocketTurretRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(RocketRenderer.ROCKET_LAYER, RocketModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.ROCKET, RocketRenderer::new); + + EntityRendererRegistry.register(PortalCubedEntities.ENERGY_PELLET, EnergyPelletRenderer::new); + + BlockEntityRenderers.register(PortalCubedBlocks.LASER_EMITTER_BLOCK_ENTITY, LaserEmitterRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(FaithPlateRenderer.FAITH_PLATE_LAYER, FaithPlateModel::getTexturedModelData); + BlockEntityRenderers.register(PortalCubedBlocks.FAITH_PLATE_BLOCK_ENTITY, FaithPlateRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(BetaFaithPlateRenderer.BETA_FAITH_PLATE_LAYER, BetaFaithPlateModel::getTexturedModelData); + BlockEntityRenderers.register(PortalCubedBlocks.BETA_FAITH_PLATE_BLOCK_ENTITY, BetaFaithPlateRenderer::new); + + EntityModelLayerRegistry.registerModelLayer(TurretRenderer.TURRET_LAYER, TurretModel::getTexturedModelData); + EntityRendererRegistry.register(PortalCubedEntities.TURRET, TurretRenderer::new); - BlockEntityRenderers.register(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER_ENTITY, ExcursionFunnelEmitterBlockEntityRenderer::new); - EntityModelLayerRegistry.registerModelLayer(ExcursionFunnelEmitterCenterModel.LAYER, ExcursionFunnelEmitterCenterModel::createBodyLayer); - EntityModelLayerRegistry.registerModelLayer(ExcursionFunnelEmitterCenterModel.LAYER_REVERSED, ExcursionFunnelEmitterCenterModel::createBodyLayer); - } - - private static final class VisibleBarriersCompat { - static boolean isVisible() { - return VisibleBarriers.isVisibilityEnabled(); - } - } - - public static boolean hiddenBlocksVisible() { - return hiddenBlocksVisible || (QuiltLoader.isModLoaded("visiblebarriers") && VisibleBarriersCompat.isVisible()); - } - - public static void toggleHiddenBlocksVisible() { - hiddenBlocksVisible = !hiddenBlocksVisible; - } - - public static boolean isPortalHudMode() { - return portalHudMode || PortalCubedConfig.portalHudMode; - } - - public static boolean isPortalHudModeServer() { - return portalHudMode; - } - - public static void setPortalHudMode(boolean portalHudMode) { - PortalCubedClient.portalHudMode = portalHudMode; - } - - public static boolean hasGlobalAdvancement(ResourceLocation advancement) { - return GLOBAL_ADVANCEMENTS.contains(advancement); - } - - public static void addGlobalAdvancement(ResourceLocation advancement) { - if (GLOBAL_ADVANCEMENTS.add(advancement)) { - try { - final CompoundTag compound = new CompoundTag(); - final ListTag list = new ListTag(); - for (final ResourceLocation id : GLOBAL_ADVANCEMENTS) { - list.add(StringTag.valueOf(id.toString())); - } - compound.put("Advancements", list); - NbtIo.writeCompressed(compound, GLOBAL_ADVANCEMENTS_FILE); - } catch (Exception e) { - LOGGER.error("Failed to save global advancements", e); - } - } - } - - public static int globalAdvancementsSize() { - return GLOBAL_ADVANCEMENTS.size(); - } - - @NotNull - public static PortalRendererImpl getRenderer() { - if (rendererType != PortalCubedConfig.renderer) { - rendererType = PortalCubedConfig.renderer; - renderer = rendererType.creator.get(); - } - return renderer; - } - - public static Optional interpCamera() { - final long time = System.currentTimeMillis(); - final long endTime = PortalCubedClient.cameraInterpStartTime + PortalCubedConfig.portalSmoothTime; - if (time >= endTime) { - return Optional.empty(); - } - return Optional.of(IPQuaternion.interpolate( - PortalCubedClient.cameraInterpStart, - IPQuaternion.IDENTITY, - (time - PortalCubedClient.cameraInterpStartTime) / (double)PortalCubedConfig.portalSmoothTime - )); - } + BlockEntityRenderers.register(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER_ENTITY, ExcursionFunnelEmitterBlockEntityRenderer::new); + EntityModelLayerRegistry.registerModelLayer(ExcursionFunnelEmitterCenterModel.LAYER, ExcursionFunnelEmitterCenterModel::createBodyLayer); + EntityModelLayerRegistry.registerModelLayer(ExcursionFunnelEmitterCenterModel.LAYER_REVERSED, ExcursionFunnelEmitterCenterModel::createBodyLayer); + } + + private static final class VisibleBarriersCompat { + static boolean isVisible() { + return VisibleBarriers.isVisibilityEnabled(); + } + } + + public static boolean hiddenBlocksVisible() { + return hiddenBlocksVisible || (QuiltLoader.isModLoaded("visiblebarriers") && VisibleBarriersCompat.isVisible()); + } + + public static void toggleHiddenBlocksVisible() { + hiddenBlocksVisible = !hiddenBlocksVisible; + } + + public static boolean isPortalHudMode() { + return portalHudMode || PortalCubedConfig.portalHudMode; + } + + public static boolean isPortalHudModeServer() { + return portalHudMode; + } + + public static void setPortalHudMode(boolean portalHudMode) { + PortalCubedClient.portalHudMode = portalHudMode; + } + + public static boolean hasGlobalAdvancement(ResourceLocation advancement) { + return GLOBAL_ADVANCEMENTS.contains(advancement); + } + + public static void addGlobalAdvancement(ResourceLocation advancement) { + if (GLOBAL_ADVANCEMENTS.add(advancement)) { + try { + final CompoundTag compound = new CompoundTag(); + final ListTag list = new ListTag(); + for (final ResourceLocation id : GLOBAL_ADVANCEMENTS) { + list.add(StringTag.valueOf(id.toString())); + } + compound.put("Advancements", list); + NbtIo.writeCompressed(compound, GLOBAL_ADVANCEMENTS_FILE); + } catch (Exception e) { + LOGGER.error("Failed to save global advancements", e); + } + } + } + + public static int globalAdvancementsSize() { + return GLOBAL_ADVANCEMENTS.size(); + } + + @NotNull + public static PortalRendererImpl getRenderer() { + if (rendererType != PortalCubedConfig.renderer) { + rendererType = PortalCubedConfig.renderer; + renderer = rendererType.creator.get(); + } + return renderer; + } + + public static Optional interpCamera() { + final long time = System.currentTimeMillis(); + final long endTime = PortalCubedClient.cameraInterpStartTime + PortalCubedConfig.portalSmoothTime; + if (time >= endTime) { + return Optional.empty(); + } + return Optional.of(IPQuaternion.interpolate( + PortalCubedClient.cameraInterpStart, + IPQuaternion.IDENTITY, + (time - PortalCubedClient.cameraInterpStartTime) / (double)PortalCubedConfig.portalSmoothTime + )); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/PortalCubedKeyBindings.java b/src/main/java/com/fusionflux/portalcubed/client/PortalCubedKeyBindings.java index 73c69907..725d15ae 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/PortalCubedKeyBindings.java +++ b/src/main/java/com/fusionflux/portalcubed/client/PortalCubedKeyBindings.java @@ -15,44 +15,44 @@ @ClientOnly public class PortalCubedKeyBindings { - public static final KeyMapping GRAB = KeyBindingHelper.registerKeyBinding(new KeyMapping( - "key." + PortalCubed.MOD_ID + ".grab", - InputConstants.Type.KEYSYM, - GLFW.GLFW_KEY_G, - "key." + PortalCubed.MOD_ID + ".category" - )); - public static final KeyMapping REMOVE_PORTALS = KeyBindingHelper.registerKeyBinding(new KeyMapping( - "key." + PortalCubed.MOD_ID + ".remove_portals", - InputConstants.Type.KEYSYM, - GLFW.GLFW_KEY_R, - "key." + PortalCubed.MOD_ID + ".category" - )); + public static final KeyMapping GRAB = KeyBindingHelper.registerKeyBinding(new KeyMapping( + "key." + PortalCubed.MOD_ID + ".grab", + InputConstants.Type.KEYSYM, + GLFW.GLFW_KEY_G, + "key." + PortalCubed.MOD_ID + ".category" + )); + public static final KeyMapping REMOVE_PORTALS = KeyBindingHelper.registerKeyBinding(new KeyMapping( + "key." + PortalCubed.MOD_ID + ".remove_portals", + InputConstants.Type.KEYSYM, + GLFW.GLFW_KEY_R, + "key." + PortalCubed.MOD_ID + ".category" + )); - public static void register() { - ClientTickEvents.END.register(client -> { - if (client.player != null && GRAB.consumeClick()) { - PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); - ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); - } - if (client.player != null && REMOVE_PORTALS.consumeClick() && !PortalCubedClient.isPortalHudMode()) { - ClientPlayNetworking.send(PortalCubedServerPackets.REMOVE_PORTALS, PacketByteBufs.create()); - } - }); + public static void register() { + ClientTickEvents.END.register(client -> { + if (client.player != null && GRAB.consumeClick()) { + PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); + ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); + } + if (client.player != null && REMOVE_PORTALS.consumeClick() && !PortalCubedClient.isPortalHudMode()) { + ClientPlayNetworking.send(PortalCubedServerPackets.REMOVE_PORTALS, PacketByteBufs.create()); + } + }); - if (!QuiltLoader.isModLoaded("visiblebarriers")) { - final KeyMapping toggleHiddenBlocksKey = new KeyMapping( - "key." + PortalCubed.MOD_ID + ".toggle_hidden_blocks", - InputConstants.Type.KEYSYM, - GLFW.GLFW_KEY_H, - "key." + PortalCubed.MOD_ID + ".category" - ); - KeyBindingHelper.registerKeyBinding(toggleHiddenBlocksKey); - ClientTickEvents.END.register(client -> { - if (toggleHiddenBlocksKey.consumeClick()) { - PortalCubedClient.toggleHiddenBlocksVisible(); - client.levelRenderer.allChanged(); - } - }); - } - } + if (!QuiltLoader.isModLoaded("visiblebarriers")) { + final KeyMapping toggleHiddenBlocksKey = new KeyMapping( + "key." + PortalCubed.MOD_ID + ".toggle_hidden_blocks", + InputConstants.Type.KEYSYM, + GLFW.GLFW_KEY_H, + "key." + PortalCubed.MOD_ID + ".category" + ); + KeyBindingHelper.registerKeyBinding(toggleHiddenBlocksKey); + ClientTickEvents.END.register(client -> { + if (toggleHiddenBlocksKey.consumeClick()) { + PortalCubedClient.toggleHiddenBlocksVisible(); + client.levelRenderer.allChanged(); + } + }); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/gui/ExpressionFieldWidget.java b/src/main/java/com/fusionflux/portalcubed/client/gui/ExpressionFieldWidget.java index 1b61d6ac..8f54a4b1 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/gui/ExpressionFieldWidget.java +++ b/src/main/java/com/fusionflux/portalcubed/client/gui/ExpressionFieldWidget.java @@ -17,90 +17,90 @@ import java.util.function.Function; public class ExpressionFieldWidget extends EditBox { - @Nullable - private Expression expression; - @Nullable - private String error; - private Function parser = s -> new ExpressionBuilder(s).build(); - private Consumer changedListener2 = s -> {}; + @Nullable + private Expression expression; + @Nullable + private String error; + private Function parser = s -> new ExpressionBuilder(s).build(); + private Consumer changedListener2 = s -> {}; - public ExpressionFieldWidget(Font textRenderer, int x, int y, int width, int height, Component text) { - super(textRenderer, x, y, width, height, text); - super.setResponder(s -> { - changedListener2.accept(s); - onValueChange(s); - }); - super.setFormatter(this::getTextToRender); - setMaxLength(256); - } + public ExpressionFieldWidget(Font textRenderer, int x, int y, int width, int height, Component text) { + super(textRenderer, x, y, width, height, text); + super.setResponder(s -> { + changedListener2.accept(s); + onValueChange(s); + }); + super.setFormatter(this::getTextToRender); + setMaxLength(256); + } - public void setExpression(String expression) { - setValue(expression); - setExpression0(expression); - } + public void setExpression(String expression) { + setValue(expression); + setExpression0(expression); + } - @Nullable - public Expression getExpression() { - return expression; - } + @Nullable + public Expression getExpression() { + return expression; + } - public void setParser(Function parser) { - this.parser = parser; - } + public void setParser(Function parser) { + this.parser = parser; + } - @Override - public void setResponder(Consumer changedListener) { - changedListener2 = changedListener; - } + @Override + public void setResponder(Consumer changedListener) { + changedListener2 = changedListener; + } - private void onValueChange(String text) { - setExpression0(text); - } + private void onValueChange(String text) { + setExpression0(text); + } - @Override - public void setFormatter(BiFunction renderTextProvider) { - throw new UnsupportedOperationException("Cannot set renderTextProvider for ExpressionFieldWidget."); - } + @Override + public void setFormatter(BiFunction renderTextProvider) { + throw new UnsupportedOperationException("Cannot set renderTextProvider for ExpressionFieldWidget."); + } - private FormattedCharSequence getTextToRender(String text, int cursor) { - Style style = Style.EMPTY; - if (error != null) { - style = style.applyFormat(ChatFormatting.RED); - } - return FormattedCharSequence.forward(text, style); - } + private FormattedCharSequence getTextToRender(String text, int cursor) { + Style style = Style.EMPTY; + if (error != null) { + style = style.applyFormat(ChatFormatting.RED); + } + return FormattedCharSequence.forward(text, style); + } - private void setExpression0(String expression) { - if (expression.isEmpty()) { - this.expression = null; - setError(null); - return; - } - try { - this.expression = parser.apply(expression); - final ValidationResult validation = this.expression.validate(false); - if (validation.isValid()) { - setError(null); - } else { - setError(validation.getErrors().get(0)); - } - } catch (RuntimeException e) { - this.expression = null; - setError(cleanError(e)); - } - } + private void setExpression0(String expression) { + if (expression.isEmpty()) { + this.expression = null; + setError(null); + return; + } + try { + this.expression = parser.apply(expression); + final ValidationResult validation = this.expression.validate(false); + if (validation.isValid()) { + setError(null); + } else { + setError(validation.getErrors().get(0)); + } + } catch (RuntimeException e) { + this.expression = null; + setError(cleanError(e)); + } + } - public void setError(String error) { - this.error = error; - if (error != null) { - expression = null; - setSuggestion(" (" + error + ")"); - } else { - setSuggestion(null); - } - } + public void setError(String error) { + this.error = error; + if (error != null) { + expression = null; + setSuggestion(" (" + error + ")"); + } else { + setSuggestion(null); + } + } - public static String cleanError(Throwable t) { - return StringUtils.defaultIfEmpty(t.getLocalizedMessage(), t.getClass().getSimpleName()); - } + public static String cleanError(Throwable t) { + return StringUtils.defaultIfEmpty(t.getLocalizedMessage(), t.getClass().getSimpleName()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/gui/FaithPlateScreen.java b/src/main/java/com/fusionflux/portalcubed/client/gui/FaithPlateScreen.java index 50d62c40..f61b49b2 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/gui/FaithPlateScreen.java +++ b/src/main/java/com/fusionflux/portalcubed/client/gui/FaithPlateScreen.java @@ -20,147 +20,147 @@ public class FaithPlateScreen extends AbstractContainerScreen { - private static final ResourceLocation TEXTURE = id("textures/gui/container/faith_plate.png"); - - private final BlockPos pos; - private final double x; - private final double y; - private final double z; - - public FaithPlateScreen(AbstractContainerMenu screenHandler, Inventory playerInventory, Component text) { - super(screenHandler, playerInventory, text); - pos = getBlockPos(screenHandler); - x = getXVar(screenHandler); - y = getYVar(screenHandler); - z = getZVar(screenHandler); - } - - private static BlockPos getBlockPos(AbstractContainerMenu handler) { - if (handler instanceof FaithPlateScreenHandler) { - return ((FaithPlateScreenHandler) handler).getPos(); - } else { - return BlockPos.ZERO; - } - } - private static double getXVar(AbstractContainerMenu handler) { - if (handler instanceof FaithPlateScreenHandler) { - return ((FaithPlateScreenHandler) handler).getX(); - } else { - return 0; - } - } - private static double getYVar(AbstractContainerMenu handler) { - if (handler instanceof FaithPlateScreenHandler) { - return ((FaithPlateScreenHandler) handler).getY(); - } else { - return 0; - } - } - private static double getZVar(AbstractContainerMenu handler) { - if (handler instanceof FaithPlateScreenHandler) { - return ((FaithPlateScreenHandler) handler).getZ(); - } else { - return 0; - } - } - - @Override - protected void renderBg(GuiGraphics graphics, float delta, int mouseX, int mouseY) { - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); - int x = (width - imageWidth) / 2; - int y = (height - imageHeight) / 2; - graphics.blit(TEXTURE, x, y, 0, 0, imageWidth, imageHeight); - } - - @Override - protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) { - } - - @Override - protected void init() { - super.init(); - var field1 = addRenderableWidget(new EditBox( - font, - (this.width / 2) - 80, // x ( aligned top-left ) - (this.height / 2) - 30, // y - 50, // width - 20, // height - Component.nullToEmpty(String.valueOf(x)) // default text??? not sure - )); - field1.setValue("X: " + x); - var field2 = addRenderableWidget(new EditBox( - font, - (this.width / 2) - 25, // x ( aligned top-left ) - (this.height / 2) - 30, // y - 50, // width - 20, // height - Component.nullToEmpty(String.valueOf(y)) // default text??? not sure - )); - field2.setValue("Y: " + y); - var field3 = addRenderableWidget(new EditBox( - font, - (this.width / 2) + 30, // x ( aligned top-left ) - (this.height / 2) - 30, // y - 50, // width - 20, // height - Component.nullToEmpty(String.valueOf(z)) // default text??? not sure - )); - field3.setValue("Z: " + z); - - int x = this.width / 2; - int y = this.height / 2; - addRenderableWidget(Button.builder(Component.nullToEmpty("Done"), (button) -> { - - FriendlyByteBuf buf = PacketByteBufs.create(); - - buf.writeBlockPos(pos); - - String xString = field1.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); - String yString = field2.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); - String zString = field3.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); - - double sendX = 0; - double sendY = 0; - double sendZ = 0; - - if (!xString.equals("")) { - sendX = Double.parseDouble(xString); - } - if (!yString.equals("")) { - sendY = Double.parseDouble(yString); - } - if (!zString.equals("")) { - sendZ = Double.parseDouble(zString); - } - - if (sendX > 4) { - sendX = 4; - } - if (sendY > 4) { - sendY = 4; - } - if (sendZ > 4) { - sendZ = 4; - } - - buf.writeDouble(sendX); - buf.writeDouble(sendY); - buf.writeDouble(sendZ); - NetworkingSafetyWrapper.sendFromClient("configure_faith_plate", buf); - this.onClose(); - // ClientPlayNetworking.send("a", buf); - }).width(100).pos(x - 50, y).build()); - // Center the title - titleLabelX = (imageWidth - font.width(title)) / 2; - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - renderBackground(graphics); - super.render(graphics, mouseX, mouseY, delta); - renderTooltip(graphics, mouseX, mouseY); - } + private static final ResourceLocation TEXTURE = id("textures/gui/container/faith_plate.png"); + + private final BlockPos pos; + private final double x; + private final double y; + private final double z; + + public FaithPlateScreen(AbstractContainerMenu screenHandler, Inventory playerInventory, Component text) { + super(screenHandler, playerInventory, text); + pos = getBlockPos(screenHandler); + x = getXVar(screenHandler); + y = getYVar(screenHandler); + z = getZVar(screenHandler); + } + + private static BlockPos getBlockPos(AbstractContainerMenu handler) { + if (handler instanceof FaithPlateScreenHandler) { + return ((FaithPlateScreenHandler) handler).getPos(); + } else { + return BlockPos.ZERO; + } + } + private static double getXVar(AbstractContainerMenu handler) { + if (handler instanceof FaithPlateScreenHandler) { + return ((FaithPlateScreenHandler) handler).getX(); + } else { + return 0; + } + } + private static double getYVar(AbstractContainerMenu handler) { + if (handler instanceof FaithPlateScreenHandler) { + return ((FaithPlateScreenHandler) handler).getY(); + } else { + return 0; + } + } + private static double getZVar(AbstractContainerMenu handler) { + if (handler instanceof FaithPlateScreenHandler) { + return ((FaithPlateScreenHandler) handler).getZ(); + } else { + return 0; + } + } + + @Override + protected void renderBg(GuiGraphics graphics, float delta, int mouseX, int mouseY) { + RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + int x = (width - imageWidth) / 2; + int y = (height - imageHeight) / 2; + graphics.blit(TEXTURE, x, y, 0, 0, imageWidth, imageHeight); + } + + @Override + protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) { + } + + @Override + protected void init() { + super.init(); + var field1 = addRenderableWidget(new EditBox( + font, + (this.width / 2) - 80, // x ( aligned top-left ) + (this.height / 2) - 30, // y + 50, // width + 20, // height + Component.nullToEmpty(String.valueOf(x)) // default text??? not sure + )); + field1.setValue("X: " + x); + var field2 = addRenderableWidget(new EditBox( + font, + (this.width / 2) - 25, // x ( aligned top-left ) + (this.height / 2) - 30, // y + 50, // width + 20, // height + Component.nullToEmpty(String.valueOf(y)) // default text??? not sure + )); + field2.setValue("Y: " + y); + var field3 = addRenderableWidget(new EditBox( + font, + (this.width / 2) + 30, // x ( aligned top-left ) + (this.height / 2) - 30, // y + 50, // width + 20, // height + Component.nullToEmpty(String.valueOf(z)) // default text??? not sure + )); + field3.setValue("Z: " + z); + + int x = this.width / 2; + int y = this.height / 2; + addRenderableWidget(Button.builder(Component.nullToEmpty("Done"), (button) -> { + + FriendlyByteBuf buf = PacketByteBufs.create(); + + buf.writeBlockPos(pos); + + String xString = field1.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); + String yString = field2.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); + String zString = field3.getValue().replaceAll("[^\\d.-]", "").replaceFirst("[.]", "d").replaceAll("[.]", "").replaceAll("d", ".").replaceFirst("-", "m").replaceAll("-", "").replaceAll("m", "-"); + + double sendX = 0; + double sendY = 0; + double sendZ = 0; + + if (!xString.equals("")) { + sendX = Double.parseDouble(xString); + } + if (!yString.equals("")) { + sendY = Double.parseDouble(yString); + } + if (!zString.equals("")) { + sendZ = Double.parseDouble(zString); + } + + if (sendX > 4) { + sendX = 4; + } + if (sendY > 4) { + sendY = 4; + } + if (sendZ > 4) { + sendZ = 4; + } + + buf.writeDouble(sendX); + buf.writeDouble(sendY); + buf.writeDouble(sendZ); + NetworkingSafetyWrapper.sendFromClient("configure_faith_plate", buf); + this.onClose(); + // ClientPlayNetworking.send("a", buf); + }).width(100).pos(x - 50, y).build()); + // Center the title + titleLabelX = (imageWidth - font.width(title)) / 2; + } + + @Override + public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderBackground(graphics); + super.render(graphics, mouseX, mouseY, delta); + renderTooltip(graphics, mouseX, mouseY); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/gui/VelocityHelperScreen.java b/src/main/java/com/fusionflux/portalcubed/client/gui/VelocityHelperScreen.java index f68be4a5..a35b9498 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/gui/VelocityHelperScreen.java +++ b/src/main/java/com/fusionflux/portalcubed/client/gui/VelocityHelperScreen.java @@ -31,169 +31,169 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class VelocityHelperScreen extends AbstractContainerScreen { - private static final ResourceLocation TEXTURE = id("textures/gui/velocity_helper.png"); - - private final VelocityHelperBlockEntity entity; - - private EditBox flightDurationWidget; - private ExpressionFieldWidget conditionWidget, icWidget; - private Button doneButton; - - public VelocityHelperScreen(BlockPosScreenHandler handler, Inventory inventory, Component title) { - super(handler, inventory, title); - imageWidth = 248; - imageHeight = 166; - assert Minecraft.getInstance().level != null; - entity = Minecraft.getInstance().level.getBlockEntity(handler.getAt(), PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).orElse(null); - if (entity == null) { - onClose(); - } - } - - @Override - protected void renderBg(GuiGraphics graphics, float delta, int mouseX, int mouseY) { - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.setShaderColor(1, 1, 1, 1); - graphics.blit(TEXTURE, leftPos, topPos, 0, 0, imageWidth, imageHeight); - } - - @Override - protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) { - graphics.drawString(font, title, titleLabelX, titleLabelY, 0x404040, false); - drawTextRightAligned( - graphics, font, - Component.translatable("portalcubed.velocity_helper.flight_duration"), - 139, 23, 0x404040 - ); - drawTextCentered( - graphics, font, - Component.translatable("portalcubed.velocity_helper.condition"), - imageWidth / 2, 39, 0x404040 - ); - drawTextCentered( - graphics, font, - Component.translatable("portalcubed.velocity_helper.interpolation_curve"), - imageWidth / 2, 71, 0x404040 - ); - } - - @Override - public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { - renderBackground(graphics); - super.render(graphics, mouseX, mouseY, delta); - renderTooltip(graphics, mouseX, mouseY); - - final Expression curve = icWidget.getExpression(); - if (curve != null) { - final String flightDurationString = flightDurationWidget.getValue(); - if (!flightDurationString.isEmpty()) { - final int pointCount = Math.min(Integer.parseInt(flightDurationString), 217); - final float spacing = 217f / pointCount; - float last = 0; - float x = this.leftPos + 17 + spacing; - try { - for (int i = 1; i <= pointCount; i++, x += spacing) { - curve.setVariable("x", 1.0 / pointCount * i); - final float calculation = (float)Mth.clamp(curve.evaluate(), 0, 1) * 44; - drawLine(graphics, x - spacing, this.topPos + 157 - last, x, this.topPos + 157 - calculation, 0xffffffff); - last = calculation; - } - } catch (RuntimeException e) { - icWidget.setError(ExpressionFieldWidget.cleanError(e)); - } - } - } - } - - @Override - protected void init() { - super.init(); - flightDurationWidget = createTextField(141, 17, 42, w -> { - w.setFilter(s -> { - if (s.isEmpty()) return true; - try { - return Integer.parseInt(s) > 0; - } catch (NumberFormatException e) { - return false; - } - }); - w.setValue(Integer.toString(entity.getFlightDuration())); - }); - conditionWidget = createExpressionField(37, 49, 174, w -> { - w.setParser(s -> VelocityHelperBlockEntity.parseExpression(s, "x", "y", "z")); - w.setExpression(entity.getConditionString()); - }); - icWidget = createExpressionField(37, 81, 174, w -> { - w.setParser(s -> VelocityHelperBlockEntity.parseExpression(s, "x")); - w.setExpression(entity.getInterpolationCurveString()); - }); - addRenderableWidget( - Button.builder(CommonComponents.GUI_CANCEL, w -> onClose()) - .width(75) - .pos(width / 2 - 90, this.topPos + imageHeight + 5) - .build() - ); - doneButton = addRenderableWidget( - Button.builder(CommonComponents.GUI_DONE, w -> { - VelocityHelperBlock.sendConfigurePacket(menu.getAt(), VelocityHelperBlock.CONFIG_OTHER, buf -> { - buf.writeVarInt(Integer.parseInt(flightDurationWidget.getValue())); - buf.writeUtf(conditionWidget.getValue()); - buf.writeUtf(icWidget.getValue()); - }); - onClose(); - }).width(75) - .pos(width / 2 + 15, this.topPos + imageHeight + 5) - .build() - ); - } - - private EditBox createTextField(int x, int y, int width, Consumer consumer) { - final EditBox widget = new EditBox(font, this.leftPos + x, this.topPos + y, width, 20, Component.empty()); - consumer.accept(widget); - addRenderableWidget(widget); - return widget; - } - - private ExpressionFieldWidget createExpressionField(int x, int y, int width, Consumer consumer) { - final ExpressionFieldWidget widget = new ExpressionFieldWidget(font, this.leftPos + x, this.topPos + y, width, 20, Component.empty()); - consumer.accept(widget); - addRenderableWidget(widget); - return widget; - } - - @Override - protected void containerTick() { - flightDurationWidget.tick(); - conditionWidget.tick(); - icWidget.tick(); - doneButton.active = - !flightDurationWidget.getValue().isEmpty() && - !conditionWidget.getValue().isEmpty() && - !icWidget.getValue().isEmpty(); - } - - public static void drawLine(GuiGraphics graphics, float x0, float y0, float x1, float y1, int color) { - final Matrix4f model = graphics.pose().last().pose(); - final Matrix3f normal = graphics.pose().last().normal(); - final float mag = Math.invsqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); - final float normalX = Math.abs(x1 - x0) * mag; - final float normalY = Math.abs(y1 - y0) * mag; - - RenderSystem.applyModelViewMatrix(); - RenderSystem.setShader(GameRenderer::getRendertypeLinesShader); - BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); - RenderSystem.lineWidth(3f); - bufferBuilder.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL); - bufferBuilder.vertex(model, x0, y0, 0).color(color).normal(normal, normalX, normalY, 0).endVertex(); - bufferBuilder.vertex(model, x1, y1, 0).color(color).normal(normal, normalX, normalY, 0).endVertex(); - Tesselator.getInstance().end(); - } - - public static void drawTextRightAligned(GuiGraphics graphics, Font font, Component text, int x, int y, int color) { - graphics.drawString(font, text, x - font.width(text), y, color, false); - } - - public static void drawTextCentered(GuiGraphics graphics, Font font, Component text, int x, int y, int color) { - graphics.drawString(font, text, x - font.width(text) / 2, y, color, false); - } + private static final ResourceLocation TEXTURE = id("textures/gui/velocity_helper.png"); + + private final VelocityHelperBlockEntity entity; + + private EditBox flightDurationWidget; + private ExpressionFieldWidget conditionWidget, icWidget; + private Button doneButton; + + public VelocityHelperScreen(BlockPosScreenHandler handler, Inventory inventory, Component title) { + super(handler, inventory, title); + imageWidth = 248; + imageHeight = 166; + assert Minecraft.getInstance().level != null; + entity = Minecraft.getInstance().level.getBlockEntity(handler.getAt(), PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).orElse(null); + if (entity == null) { + onClose(); + } + } + + @Override + protected void renderBg(GuiGraphics graphics, float delta, int mouseX, int mouseY) { + RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShaderColor(1, 1, 1, 1); + graphics.blit(TEXTURE, leftPos, topPos, 0, 0, imageWidth, imageHeight); + } + + @Override + protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) { + graphics.drawString(font, title, titleLabelX, titleLabelY, 0x404040, false); + drawTextRightAligned( + graphics, font, + Component.translatable("portalcubed.velocity_helper.flight_duration"), + 139, 23, 0x404040 + ); + drawTextCentered( + graphics, font, + Component.translatable("portalcubed.velocity_helper.condition"), + imageWidth / 2, 39, 0x404040 + ); + drawTextCentered( + graphics, font, + Component.translatable("portalcubed.velocity_helper.interpolation_curve"), + imageWidth / 2, 71, 0x404040 + ); + } + + @Override + public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderBackground(graphics); + super.render(graphics, mouseX, mouseY, delta); + renderTooltip(graphics, mouseX, mouseY); + + final Expression curve = icWidget.getExpression(); + if (curve != null) { + final String flightDurationString = flightDurationWidget.getValue(); + if (!flightDurationString.isEmpty()) { + final int pointCount = Math.min(Integer.parseInt(flightDurationString), 217); + final float spacing = 217f / pointCount; + float last = 0; + float x = this.leftPos + 17 + spacing; + try { + for (int i = 1; i <= pointCount; i++, x += spacing) { + curve.setVariable("x", 1.0 / pointCount * i); + final float calculation = (float)Mth.clamp(curve.evaluate(), 0, 1) * 44; + drawLine(graphics, x - spacing, this.topPos + 157 - last, x, this.topPos + 157 - calculation, 0xffffffff); + last = calculation; + } + } catch (RuntimeException e) { + icWidget.setError(ExpressionFieldWidget.cleanError(e)); + } + } + } + } + + @Override + protected void init() { + super.init(); + flightDurationWidget = createTextField(141, 17, 42, w -> { + w.setFilter(s -> { + if (s.isEmpty()) return true; + try { + return Integer.parseInt(s) > 0; + } catch (NumberFormatException e) { + return false; + } + }); + w.setValue(Integer.toString(entity.getFlightDuration())); + }); + conditionWidget = createExpressionField(37, 49, 174, w -> { + w.setParser(s -> VelocityHelperBlockEntity.parseExpression(s, "x", "y", "z")); + w.setExpression(entity.getConditionString()); + }); + icWidget = createExpressionField(37, 81, 174, w -> { + w.setParser(s -> VelocityHelperBlockEntity.parseExpression(s, "x")); + w.setExpression(entity.getInterpolationCurveString()); + }); + addRenderableWidget( + Button.builder(CommonComponents.GUI_CANCEL, w -> onClose()) + .width(75) + .pos(width / 2 - 90, this.topPos + imageHeight + 5) + .build() + ); + doneButton = addRenderableWidget( + Button.builder(CommonComponents.GUI_DONE, w -> { + VelocityHelperBlock.sendConfigurePacket(menu.getAt(), VelocityHelperBlock.CONFIG_OTHER, buf -> { + buf.writeVarInt(Integer.parseInt(flightDurationWidget.getValue())); + buf.writeUtf(conditionWidget.getValue()); + buf.writeUtf(icWidget.getValue()); + }); + onClose(); + }).width(75) + .pos(width / 2 + 15, this.topPos + imageHeight + 5) + .build() + ); + } + + private EditBox createTextField(int x, int y, int width, Consumer consumer) { + final EditBox widget = new EditBox(font, this.leftPos + x, this.topPos + y, width, 20, Component.empty()); + consumer.accept(widget); + addRenderableWidget(widget); + return widget; + } + + private ExpressionFieldWidget createExpressionField(int x, int y, int width, Consumer consumer) { + final ExpressionFieldWidget widget = new ExpressionFieldWidget(font, this.leftPos + x, this.topPos + y, width, 20, Component.empty()); + consumer.accept(widget); + addRenderableWidget(widget); + return widget; + } + + @Override + protected void containerTick() { + flightDurationWidget.tick(); + conditionWidget.tick(); + icWidget.tick(); + doneButton.active = + !flightDurationWidget.getValue().isEmpty() && + !conditionWidget.getValue().isEmpty() && + !icWidget.getValue().isEmpty(); + } + + public static void drawLine(GuiGraphics graphics, float x0, float y0, float x1, float y1, int color) { + final Matrix4f model = graphics.pose().last().pose(); + final Matrix3f normal = graphics.pose().last().normal(); + final float mag = Math.invsqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); + final float normalX = Math.abs(x1 - x0) * mag; + final float normalY = Math.abs(y1 - y0) * mag; + + RenderSystem.applyModelViewMatrix(); + RenderSystem.setShader(GameRenderer::getRendertypeLinesShader); + BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); + RenderSystem.lineWidth(3f); + bufferBuilder.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL); + bufferBuilder.vertex(model, x0, y0, 0).color(color).normal(normal, normalX, normalY, 0).endVertex(); + bufferBuilder.vertex(model, x1, y1, 0).color(color).normal(normal, normalX, normalY, 0).endVertex(); + Tesselator.getInstance().end(); + } + + public static void drawTextRightAligned(GuiGraphics graphics, Font font, Component text, int x, int y, int color) { + graphics.drawString(font, text, x - font.width(text), y, color, false); + } + + public static void drawTextCentered(GuiGraphics graphics, Font font, Component text, int x, int y, int color) { + graphics.drawString(font, text, x - font.width(text) / 2, y, color, false); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/packet/PortalCubedClientPackets.java b/src/main/java/com/fusionflux/portalcubed/client/packet/PortalCubedClientPackets.java index 6b30e67a..8e3a4f88 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/packet/PortalCubedClientPackets.java +++ b/src/main/java/com/fusionflux/portalcubed/client/packet/PortalCubedClientPackets.java @@ -30,145 +30,145 @@ public class PortalCubedClientPackets { - public static final ResourceLocation FIZZLE_PACKET = id("fizzle"); - public static final ResourceLocation HAND_SHAKE_PACKET = id("hand_shake"); - public static final ResourceLocation GEL_OVERLAY_PACKET = id("gel_overlay"); - public static final ResourceLocation ROCKET_TURRET_UPDATE_PACKET = id("rocket_turret_update"); - public static final ResourceLocation ENABLE_CFG = id("enable_cfg"); - public static final ResourceLocation ENABLE_PORTAL_HUD = id("enable_portal_hud"); - public static final ResourceLocation REFRESH_POS = id("refresh_pos"); - public static final ResourceLocation SERVER_ANIMATE = id("server_animate"); - public static final ResourceLocation SET_CUSTOM_FOG = id("set_custom_fog"); - public static final ResourceLocation SET_CAMERA_INTERPOLATE = id("set_roll"); + public static final ResourceLocation FIZZLE_PACKET = id("fizzle"); + public static final ResourceLocation HAND_SHAKE_PACKET = id("hand_shake"); + public static final ResourceLocation GEL_OVERLAY_PACKET = id("gel_overlay"); + public static final ResourceLocation ROCKET_TURRET_UPDATE_PACKET = id("rocket_turret_update"); + public static final ResourceLocation ENABLE_CFG = id("enable_cfg"); + public static final ResourceLocation ENABLE_PORTAL_HUD = id("enable_portal_hud"); + public static final ResourceLocation REFRESH_POS = id("refresh_pos"); + public static final ResourceLocation SERVER_ANIMATE = id("server_animate"); + public static final ResourceLocation SET_CUSTOM_FOG = id("set_custom_fog"); + public static final ResourceLocation SET_CAMERA_INTERPOLATE = id("set_roll"); - @ClientOnly - public static void registerPackets() { - ClientPlayNetworking.registerGlobalReceiver(FIZZLE_PACKET, PortalCubedClientPackets::onFizzle); - ClientPlayNetworking.registerGlobalReceiver(HAND_SHAKE_PACKET, PortalCubedClientPackets::onHandShake); - ClientPlayNetworking.registerGlobalReceiver(GEL_OVERLAY_PACKET, PortalCubedClientPackets::onGelOverlay); - ClientPlayNetworking.registerGlobalReceiver(ROCKET_TURRET_UPDATE_PACKET, PortalCubedClientPackets::onRocketTurretUpdate); - ClientPlayNetworking.registerGlobalReceiver(ENABLE_CFG, PortalCubedClientPackets::onEnableCfg); - ClientPlayNetworking.registerGlobalReceiver(ENABLE_PORTAL_HUD, PortalCubedClientPackets::onEnablePortalHud); - ClientPlayNetworking.registerGlobalReceiver(REFRESH_POS, PortalCubedClientPackets::onRefreshPos); - ClientPlayNetworking.registerGlobalReceiver(SERVER_ANIMATE, PortalCubedClientPackets::onServerAnimate); - ClientPlayNetworking.registerGlobalReceiver(SET_CUSTOM_FOG, PortalCubedClientPackets::onSetCustomFog); - ClientPlayNetworking.registerGlobalReceiver(SET_CAMERA_INTERPOLATE, PortalCubedClientPackets::onSetCameraInterpolate); - } + @ClientOnly + public static void registerPackets() { + ClientPlayNetworking.registerGlobalReceiver(FIZZLE_PACKET, PortalCubedClientPackets::onFizzle); + ClientPlayNetworking.registerGlobalReceiver(HAND_SHAKE_PACKET, PortalCubedClientPackets::onHandShake); + ClientPlayNetworking.registerGlobalReceiver(GEL_OVERLAY_PACKET, PortalCubedClientPackets::onGelOverlay); + ClientPlayNetworking.registerGlobalReceiver(ROCKET_TURRET_UPDATE_PACKET, PortalCubedClientPackets::onRocketTurretUpdate); + ClientPlayNetworking.registerGlobalReceiver(ENABLE_CFG, PortalCubedClientPackets::onEnableCfg); + ClientPlayNetworking.registerGlobalReceiver(ENABLE_PORTAL_HUD, PortalCubedClientPackets::onEnablePortalHud); + ClientPlayNetworking.registerGlobalReceiver(REFRESH_POS, PortalCubedClientPackets::onRefreshPos); + ClientPlayNetworking.registerGlobalReceiver(SERVER_ANIMATE, PortalCubedClientPackets::onServerAnimate); + ClientPlayNetworking.registerGlobalReceiver(SET_CUSTOM_FOG, PortalCubedClientPackets::onSetCustomFog); + ClientPlayNetworking.registerGlobalReceiver(SET_CAMERA_INTERPOLATE, PortalCubedClientPackets::onSetCameraInterpolate); + } - @ClientOnly - public static void onFizzle(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - final int entityId = buf.readVarInt(); - client.execute(() -> { - assert client.level != null; - final Entity entity = client.level.getEntity(entityId); - if (entity instanceof Fizzleable fizzleable) { - fizzleable.startFizzlingProgress(); - } - assert client.player != null; - if (entity instanceof CorePhysicsEntity prop && client.player.getUUID().equals(prop.getHolderUUID().orElse(null))) { - PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); - ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); - } - }); - } + @ClientOnly + public static void onFizzle(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + final int entityId = buf.readVarInt(); + client.execute(() -> { + assert client.level != null; + final Entity entity = client.level.getEntity(entityId); + if (entity instanceof Fizzleable fizzleable) { + fizzleable.startFizzlingProgress(); + } + assert client.player != null; + if (entity instanceof CorePhysicsEntity prop && client.player.getUUID().equals(prop.getHolderUUID().orElse(null))) { + PortalCubedComponents.HOLDER_COMPONENT.get(client.player).stopHolding(); + ClientPlayNetworking.send(PortalCubedServerPackets.GRAB_KEY_PRESSED, PacketByteBufs.create()); + } + }); + } - @ClientOnly - public static void onHandShake(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - PortalCubedClient.shakeStart = Util.getMillis(); - } + @ClientOnly + public static void onHandShake(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + PortalCubedClient.shakeStart = Util.getMillis(); + } - @ClientOnly - public static void onGelOverlay(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - final ResourceLocation blockId = buf.readResourceLocation(); - PortalCubedClient.gelOverlayTimer = 0; - PortalCubedClient.gelOverlayTexture = new ResourceLocation( - blockId.getNamespace(), "textures/block/" + blockId.getPath() + ".png" - ); - } + @ClientOnly + public static void onGelOverlay(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + final ResourceLocation blockId = buf.readResourceLocation(); + PortalCubedClient.gelOverlayTimer = 0; + PortalCubedClient.gelOverlayTexture = new ResourceLocation( + blockId.getNamespace(), "textures/block/" + blockId.getPath() + ".png" + ); + } - @ClientOnly - @SuppressWarnings("unchecked") - public static void onRocketTurretUpdate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - final BlockPos pos = buf.readBlockPos(); - final int mode = buf.readByte(); - final Object arg = switch (mode) { - case RocketTurretBlockEntity.UPDATE_ANGLE -> new Tuple<>(buf.readFloat(), buf.readFloat()); - case RocketTurretBlockEntity.UPDATE_LOCKED_TICKS -> buf.readVarInt(); - default -> { - PortalCubed.LOGGER.error("Malformed rocket_turret_update packet. Unknown mode {}.", mode); - yield null; - } - }; - if (arg == null) return; - client.execute(() -> handler.getLevel() - .getBlockEntity(pos, PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY) - .ifPresentOrElse( - entity -> { - switch (mode) { - case RocketTurretBlockEntity.UPDATE_ANGLE -> entity.setAngle((Tuple)arg); - case RocketTurretBlockEntity.UPDATE_LOCKED_TICKS -> entity.setLockedTicks((int)arg); - } - }, - () -> PortalCubed.LOGGER.warn("Received rocket_turret_update for unloaded rocket turret at {}.", pos) - ) - ); - } + @ClientOnly + @SuppressWarnings("unchecked") + public static void onRocketTurretUpdate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + final BlockPos pos = buf.readBlockPos(); + final int mode = buf.readByte(); + final Object arg = switch (mode) { + case RocketTurretBlockEntity.UPDATE_ANGLE -> new Tuple<>(buf.readFloat(), buf.readFloat()); + case RocketTurretBlockEntity.UPDATE_LOCKED_TICKS -> buf.readVarInt(); + default -> { + PortalCubed.LOGGER.error("Malformed rocket_turret_update packet. Unknown mode {}.", mode); + yield null; + } + }; + if (arg == null) return; + client.execute(() -> handler.getLevel() + .getBlockEntity(pos, PortalCubedBlocks.ROCKET_TURRET_BLOCK_ENTITY) + .ifPresentOrElse( + entity -> { + switch (mode) { + case RocketTurretBlockEntity.UPDATE_ANGLE -> entity.setAngle((Tuple)arg); + case RocketTurretBlockEntity.UPDATE_LOCKED_TICKS -> entity.setLockedTicks((int)arg); + } + }, + () -> PortalCubed.LOGGER.warn("Received rocket_turret_update for unloaded rocket turret at {}.", pos) + ) + ); + } - @ClientOnly - public static void onEnableCfg(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - PortalCubedClient.allowCfg = buf.readBoolean(); - } + @ClientOnly + public static void onEnableCfg(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + PortalCubedClient.allowCfg = buf.readBoolean(); + } - @ClientOnly - public static void onEnablePortalHud(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - PortalCubedClient.setPortalHudMode(buf.readBoolean()); - } + @ClientOnly + public static void onEnablePortalHud(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + PortalCubedClient.setPortalHudMode(buf.readBoolean()); + } - @ClientOnly - public static void onRefreshPos(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - final int entityId = buf.readVarInt(); - final double x = buf.readDouble(); - final double y = buf.readDouble(); - final double z = buf.readDouble(); - final float yaw = buf.readFloat(); - final float pitch = buf.readFloat(); - client.execute(() -> { - assert client.level != null; - final Entity entity = client.level.getEntity(entityId); - if (entity != null) { - entity.moveTo(x, y, z, yaw, pitch); - } - }); - } + @ClientOnly + public static void onRefreshPos(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + final int entityId = buf.readVarInt(); + final double x = buf.readDouble(); + final double y = buf.readDouble(); + final double z = buf.readDouble(); + final float yaw = buf.readFloat(); + final float pitch = buf.readFloat(); + client.execute(() -> { + assert client.level != null; + final Entity entity = client.level.getEntity(entityId); + if (entity != null) { + entity.moveTo(x, y, z, yaw, pitch); + } + }); + } - @ClientOnly - public static void onServerAnimate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - final BlockPos pos = buf.readBlockPos(); - final String animation = buf.readUtf(); - client.execute(() -> { - assert client.level != null; - final BlockEntity blockEntity = client.level.getBlockEntity(pos); - AnimationState state = null; - if (blockEntity instanceof ServerAnimatable serverAnimatable) { - state = serverAnimatable.getAnimation(animation); - } - if (state != null) { - // state can only ever be non-null if blockEntity instanceof ServerAnimatable - state.start(((ServerAnimatable)blockEntity).getAge()); - } else { - PortalCubed.LOGGER.warn("Unknown animation from {}: {} for {}", SERVER_ANIMATE, animation, blockEntity); - } - }); - } + @ClientOnly + public static void onServerAnimate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + final BlockPos pos = buf.readBlockPos(); + final String animation = buf.readUtf(); + client.execute(() -> { + assert client.level != null; + final BlockEntity blockEntity = client.level.getBlockEntity(pos); + AnimationState state = null; + if (blockEntity instanceof ServerAnimatable serverAnimatable) { + state = serverAnimatable.getAnimation(animation); + } + if (state != null) { + // state can only ever be non-null if blockEntity instanceof ServerAnimatable + state.start(((ServerAnimatable)blockEntity).getAge()); + } else { + PortalCubed.LOGGER.warn("Unknown animation from {}: {} for {}", SERVER_ANIMATE, animation, blockEntity); + } + }); + } - @ClientOnly - public static void onSetCustomFog(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - PortalCubedClient.customFog = FogSettings.decodeOptional(buf); - } + @ClientOnly + public static void onSetCustomFog(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + PortalCubedClient.customFog = FogSettings.decodeOptional(buf); + } - @ClientOnly - public static void onSetCameraInterpolate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { - PortalCubedClient.cameraInterpStart = new IPQuaternion(buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readDouble()); - PortalCubedClient.cameraInterpStartTime = System.currentTimeMillis(); - } + @ClientOnly + public static void onSetCameraInterpolate(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) { + PortalCubedClient.cameraInterpStart = new IPQuaternion(buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readDouble()); + PortalCubedClient.cameraInterpStartTime = System.currentTimeMillis(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/particle/DecalParticle.java b/src/main/java/com/fusionflux/portalcubed/client/particle/DecalParticle.java index 92c07978..b2407e3d 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/particle/DecalParticle.java +++ b/src/main/java/com/fusionflux/portalcubed/client/particle/DecalParticle.java @@ -29,142 +29,142 @@ @ClientOnly public class DecalParticle extends Particle { - public static final ParticleRenderType PARTICLE_SHEET_MULTIPLY = new ParticleRenderType() { - @Override - @SuppressWarnings("deprecation") - public void begin(BufferBuilder bufferBuilder, TextureManager textureManager) { - RenderSystem.depthMask(true); - RenderSystem.setShaderTexture(0, TextureAtlas.LOCATION_PARTICLES); - RenderSystem.enableBlend(); - RenderSystem.blendFunc(GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.SRC_COLOR); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.PARTICLE); - } - - @Override - public void end(Tesselator tessellator) { - tessellator.end(); - } - - public String toString() { - return "PARTICLE_SHEET_MULTIPLY"; - } - }; - - private final TextureAtlasSprite sprite; - private final Quaternionf rotation; - private final Vector3f pixelOffset; - private final boolean multiply; - - public DecalParticle( - ClientLevel world, - double x, double y, double z, - TextureAtlasSprite sprite, Direction direction, - boolean multiply - ) { - super(world, x, y, z); - this.sprite = sprite; - rotation = direction.getRotation(); - pixelOffset = getPixelOffset(direction); - this.multiply = multiply; - lifetime = 1400; - } - - @Override - public void render(VertexConsumer vertexConsumer, Camera camera, float tickDelta) { - final Vec3 cameraPos = camera.getPosition(); - final float x = (float)(Mth.lerp(tickDelta, xo, this.x) - cameraPos.x()); - final float y = (float)(Mth.lerp(tickDelta, yo, this.y) - cameraPos.y()); - final float z = (float)(Mth.lerp(tickDelta, zo, this.z) - cameraPos.z()); - - final Vector3f[] vertices = { - new Vector3f(-0.5f, 0f, -0.5f), - new Vector3f(-0.5f, 0f, 0.5f), - new Vector3f(0.5f, 0f, 0.5f), - new Vector3f(0.5f, 0f, -0.5f) - }; - - for (final Vector3f vertex : vertices) { - vertex.rotate(rotation).add(x, y, z).add(pixelOffset); - } - - alpha = 1f; - if (age + 100 >= lifetime) { - final float past100 = (age + tickDelta) - lifetime + 100; - alpha = 1f - Mth.clamp(past100 / 100f, 0f, 1f); - } - - final float minU = sprite.getU0(); - final float maxU = sprite.getU1(); - final float minV = sprite.getV0(); - final float maxV = sprite.getV1(); - final int brightness = getLightColor(tickDelta); - vertexConsumer.vertex(vertices[0].x(), vertices[0].y(), vertices[0].z()) - .uv(maxU, maxV) - .color(rCol, gCol, bCol, alpha) - .uv2(brightness) - .endVertex(); - vertexConsumer.vertex(vertices[1].x(), vertices[1].y(), vertices[1].z()) - .uv(maxU, minV) - .color(rCol, gCol, bCol, alpha) - .uv2(brightness) - .endVertex(); - vertexConsumer.vertex(vertices[2].x(), vertices[2].y(), vertices[2].z()) - .uv(minU, minV) - .color(rCol, gCol, bCol, alpha) - .uv2(brightness) - .endVertex(); - vertexConsumer.vertex(vertices[3].x(), vertices[3].y(), vertices[3].z()) - .uv(minU, maxV) - .color(rCol, gCol, bCol, alpha) - .uv2(brightness) - .endVertex(); - } - - @NotNull - @Override - public ParticleRenderType getRenderType() { - return multiply ? PARTICLE_SHEET_MULTIPLY : ParticleRenderType.PARTICLE_SHEET_TRANSLUCENT; - } - - private static Vector3f getPixelOffset(Direction direction) { - final float HALF_PIXEL = 0.5f / 16; - if (direction == Direction.UP || direction == Direction.DOWN) { - return new Vector3f(-HALF_PIXEL, 0, -HALF_PIXEL); - } - return direction.getClockWise().step().mul(HALF_PIXEL).add(0, HALF_PIXEL, 0); - } - - @ClientOnly - public static class Provider implements ParticleProvider { - private final FabricSpriteProvider spriteProvider; - - private List cacheKey; - private final Map spriteCache = new HashMap<>(); - - public Provider(FabricSpriteProvider spriteProvider) { - this.spriteProvider = spriteProvider; - } - - @Override - public Particle createParticle(DecalParticleOption parameters, ClientLevel world, double x, double y, double z, double velocityX, double velocityY, double velocityZ) { - final TextureAtlasSprite sprite = getSpriteCache().get(parameters.getTexture()); - if (sprite == null) { - PortalCubed.LOGGER.warn("Unknown decal particle texture {}", parameters.getTexture()); - return null; - } - return new DecalParticle(world, x, y, z, sprite, parameters.getDirection(), parameters.isMultiply()); - } - - private Map getSpriteCache() { - final List sprites = spriteProvider.getSprites(); - if (sprites != cacheKey) { - cacheKey = sprites; - spriteCache.clear(); - for (final TextureAtlasSprite sprite : sprites) { - spriteCache.put(sprite.contents().name(), sprite); - } - } - return spriteCache; - } - } + public static final ParticleRenderType PARTICLE_SHEET_MULTIPLY = new ParticleRenderType() { + @Override + @SuppressWarnings("deprecation") + public void begin(BufferBuilder bufferBuilder, TextureManager textureManager) { + RenderSystem.depthMask(true); + RenderSystem.setShaderTexture(0, TextureAtlas.LOCATION_PARTICLES); + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.SRC_COLOR); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.PARTICLE); + } + + @Override + public void end(Tesselator tessellator) { + tessellator.end(); + } + + public String toString() { + return "PARTICLE_SHEET_MULTIPLY"; + } + }; + + private final TextureAtlasSprite sprite; + private final Quaternionf rotation; + private final Vector3f pixelOffset; + private final boolean multiply; + + public DecalParticle( + ClientLevel world, + double x, double y, double z, + TextureAtlasSprite sprite, Direction direction, + boolean multiply + ) { + super(world, x, y, z); + this.sprite = sprite; + rotation = direction.getRotation(); + pixelOffset = getPixelOffset(direction); + this.multiply = multiply; + lifetime = 1400; + } + + @Override + public void render(VertexConsumer vertexConsumer, Camera camera, float tickDelta) { + final Vec3 cameraPos = camera.getPosition(); + final float x = (float)(Mth.lerp(tickDelta, xo, this.x) - cameraPos.x()); + final float y = (float)(Mth.lerp(tickDelta, yo, this.y) - cameraPos.y()); + final float z = (float)(Mth.lerp(tickDelta, zo, this.z) - cameraPos.z()); + + final Vector3f[] vertices = { + new Vector3f(-0.5f, 0f, -0.5f), + new Vector3f(-0.5f, 0f, 0.5f), + new Vector3f(0.5f, 0f, 0.5f), + new Vector3f(0.5f, 0f, -0.5f) + }; + + for (final Vector3f vertex : vertices) { + vertex.rotate(rotation).add(x, y, z).add(pixelOffset); + } + + alpha = 1f; + if (age + 100 >= lifetime) { + final float past100 = (age + tickDelta) - lifetime + 100; + alpha = 1f - Mth.clamp(past100 / 100f, 0f, 1f); + } + + final float minU = sprite.getU0(); + final float maxU = sprite.getU1(); + final float minV = sprite.getV0(); + final float maxV = sprite.getV1(); + final int brightness = getLightColor(tickDelta); + vertexConsumer.vertex(vertices[0].x(), vertices[0].y(), vertices[0].z()) + .uv(maxU, maxV) + .color(rCol, gCol, bCol, alpha) + .uv2(brightness) + .endVertex(); + vertexConsumer.vertex(vertices[1].x(), vertices[1].y(), vertices[1].z()) + .uv(maxU, minV) + .color(rCol, gCol, bCol, alpha) + .uv2(brightness) + .endVertex(); + vertexConsumer.vertex(vertices[2].x(), vertices[2].y(), vertices[2].z()) + .uv(minU, minV) + .color(rCol, gCol, bCol, alpha) + .uv2(brightness) + .endVertex(); + vertexConsumer.vertex(vertices[3].x(), vertices[3].y(), vertices[3].z()) + .uv(minU, maxV) + .color(rCol, gCol, bCol, alpha) + .uv2(brightness) + .endVertex(); + } + + @NotNull + @Override + public ParticleRenderType getRenderType() { + return multiply ? PARTICLE_SHEET_MULTIPLY : ParticleRenderType.PARTICLE_SHEET_TRANSLUCENT; + } + + private static Vector3f getPixelOffset(Direction direction) { + final float HALF_PIXEL = 0.5f / 16; + if (direction == Direction.UP || direction == Direction.DOWN) { + return new Vector3f(-HALF_PIXEL, 0, -HALF_PIXEL); + } + return direction.getClockWise().step().mul(HALF_PIXEL).add(0, HALF_PIXEL, 0); + } + + @ClientOnly + public static class Provider implements ParticleProvider { + private final FabricSpriteProvider spriteProvider; + + private List cacheKey; + private final Map spriteCache = new HashMap<>(); + + public Provider(FabricSpriteProvider spriteProvider) { + this.spriteProvider = spriteProvider; + } + + @Override + public Particle createParticle(DecalParticleOption parameters, ClientLevel world, double x, double y, double z, double velocityX, double velocityY, double velocityZ) { + final TextureAtlasSprite sprite = getSpriteCache().get(parameters.getTexture()); + if (sprite == null) { + PortalCubed.LOGGER.warn("Unknown decal particle texture {}", parameters.getTexture()); + return null; + } + return new DecalParticle(world, x, y, z, sprite, parameters.getDirection(), parameters.isMultiply()); + } + + private Map getSpriteCache() { + final List sprites = spriteProvider.getSprites(); + if (sprites != cacheKey) { + cacheKey = sprites; + spriteCache.clear(); + for (final TextureAtlasSprite sprite : sprites) { + spriteCache.put(sprite.contents().name(), sprite); + } + } + return spriteCache; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/EntityEmissiveRendering.java b/src/main/java/com/fusionflux/portalcubed/client/render/EntityEmissiveRendering.java index 5fdf48c1..d249c0ea 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/EntityEmissiveRendering.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/EntityEmissiveRendering.java @@ -16,37 +16,37 @@ public final class EntityEmissiveRendering { - public static > void renderEmissive(PoseStack matrices, MultiBufferSource vertexConsumers, T entity, M model, Function emissiveTextureGetter) { - final ResourceLocation texture = emissiveTextureGetter.apply(entity); - if (texture == null) return; - var brightness = 1f; - if (entity instanceof Fizzleable fizzleable) { - brightness -= Math.min(fizzleable.getFizzleProgress(), 1f); - } - final var vertexConsumer = vertexConsumers.getBuffer(RenderType.eyes(emissiveTextureGetter.apply(entity))); - model.renderToBuffer(matrices, vertexConsumer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, brightness, brightness, brightness, 1f); - } - - public static > EmissiveFeatureRenderer featureRenderer(RenderLayerParent featureRendererContext, Function emissiveTextureGetter) { - return new EmissiveFeatureRenderer<>(featureRendererContext, emissiveTextureGetter); - } - - private static class EmissiveFeatureRenderer> extends RenderLayer { - - private final Function emissiveTextureGetter; - - private EmissiveFeatureRenderer(RenderLayerParent featureRendererContext, Function emissiveTextureGetter) { - super(featureRendererContext); - this.emissiveTextureGetter = emissiveTextureGetter; - } - - @Override - public void render(PoseStack matrices, MultiBufferSource vertexConsumers, int light, T entity, - float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, - float headPitch) { - EntityEmissiveRendering.renderEmissive(matrices, vertexConsumers, entity, getParentModel(), emissiveTextureGetter); - } - - } + public static > void renderEmissive(PoseStack matrices, MultiBufferSource vertexConsumers, T entity, M model, Function emissiveTextureGetter) { + final ResourceLocation texture = emissiveTextureGetter.apply(entity); + if (texture == null) return; + var brightness = 1f; + if (entity instanceof Fizzleable fizzleable) { + brightness -= Math.min(fizzleable.getFizzleProgress(), 1f); + } + final var vertexConsumer = vertexConsumers.getBuffer(RenderType.eyes(emissiveTextureGetter.apply(entity))); + model.renderToBuffer(matrices, vertexConsumer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, brightness, brightness, brightness, 1f); + } + + public static > EmissiveFeatureRenderer featureRenderer(RenderLayerParent featureRendererContext, Function emissiveTextureGetter) { + return new EmissiveFeatureRenderer<>(featureRendererContext, emissiveTextureGetter); + } + + private static class EmissiveFeatureRenderer> extends RenderLayer { + + private final Function emissiveTextureGetter; + + private EmissiveFeatureRenderer(RenderLayerParent featureRendererContext, Function emissiveTextureGetter) { + super(featureRendererContext); + this.emissiveTextureGetter = emissiveTextureGetter; + } + + @Override + public void render(PoseStack matrices, MultiBufferSource vertexConsumers, int light, T entity, + float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, + float headPitch) { + EntityEmissiveRendering.renderEmissive(matrices, vertexConsumers, entity, getParentModel(), emissiveTextureGetter); + } + + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/LateRenderedEntitySortingIterator.java b/src/main/java/com/fusionflux/portalcubed/client/render/LateRenderedEntitySortingIterator.java index 5461eec8..4a7967b0 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/LateRenderedEntitySortingIterator.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/LateRenderedEntitySortingIterator.java @@ -10,40 +10,40 @@ public class LateRenderedEntitySortingIterator extends AbstractIterator { - private final Iterator wrapped; - private List lateRendered = null; - private Iterator lateRenderedIterator = null; + private final Iterator wrapped; + private List lateRendered = null; + private Iterator lateRenderedIterator = null; - public LateRenderedEntitySortingIterator(Iterator wrapped) { - this.wrapped = wrapped; - } + public LateRenderedEntitySortingIterator(Iterator wrapped) { + this.wrapped = wrapped; + } - @Override - protected Entity computeNext() { - if (wrapped.hasNext()) { - Entity next = wrapped.next(); - if (next instanceof LateRenderedEntity) { - if (lateRendered == null) // avoid allocating a list when none are present - lateRendered = new ArrayList<>(); - lateRendered.add(next); - return computeNext(); - } else { - return next; - } - } else if (lateRendered != null) { - List late = lateRendered; - // only go down this branch once - lateRendered = null; - if (late.size() == 1) { - return late.get(0); // avoid allocating another iterator when only 1 left - } else { - lateRenderedIterator = late.iterator(); - return computeNext(); - } - } else if (lateRenderedIterator != null && lateRenderedIterator.hasNext()) { - return lateRenderedIterator.next(); - } else { - return endOfData(); - } - } + @Override + protected Entity computeNext() { + if (wrapped.hasNext()) { + Entity next = wrapped.next(); + if (next instanceof LateRenderedEntity) { + if (lateRendered == null) // avoid allocating a list when none are present + lateRendered = new ArrayList<>(); + lateRendered.add(next); + return computeNext(); + } else { + return next; + } + } else if (lateRendered != null) { + List late = lateRendered; + // only go down this branch once + lateRendered = null; + if (late.size() == 1) { + return late.get(0); // avoid allocating another iterator when only 1 left + } else { + lateRenderedIterator = late.iterator(); + return computeNext(); + } + } else if (lateRenderedIterator != null && lateRenderedIterator.hasNext()) { + return lateRenderedIterator.next(); + } else { + return endOfData(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/PortalHud.java b/src/main/java/com/fusionflux/portalcubed/client/render/PortalHud.java index df901bd1..122926f5 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/PortalHud.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/PortalHud.java @@ -22,69 +22,69 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalHud { - private static final ResourceLocation ROUND_TEXTURE = id("textures/gui/active_portal_indicator.png"); - private static final ResourceLocation SQUARE_TEXTURE = id("textures/gui/active_portal_indicator_square.png"); + private static final ResourceLocation ROUND_TEXTURE = id("textures/gui/active_portal_indicator.png"); + private static final ResourceLocation SQUARE_TEXTURE = id("textures/gui/active_portal_indicator_square.png"); - public static void renderPortals(@SuppressWarnings("unused") GuiGraphics graphics, @SuppressWarnings("unused") float tickDelta) { - renderPortalSide(false, -9, -9, 16); - renderPortalSide(true, 0, -5, 0); - } + public static void renderPortals(@SuppressWarnings("unused") GuiGraphics graphics, @SuppressWarnings("unused") float tickDelta) { + renderPortalSide(false, -9, -9, 16); + renderPortalSide(true, 0, -5, 0); + } - private static void renderPortalSide(boolean rightSide, int xOffset, int yOffset, int uOffset) { - final Minecraft minecraft = Minecraft.getInstance(); - //noinspection DataFlowIssue - if ( - !minecraft.options.getCameraType().isFirstPerson() || - minecraft.gameMode.getPlayerMode() == GameType.SPECTATOR - ) return; - RenderSystem.enableBlend(); - RenderSystem.setShader(GameRenderer::getPositionTexColorShader); - RenderSystem.setShaderColor(1f, 1f, 1f, 1f); - if (PortalCubedConfig.enableRoundPortals) { - RenderSystem.setShaderTexture(0, ROUND_TEXTURE); - } else { - RenderSystem.setShaderTexture(0, SQUARE_TEXTURE); - } - assert minecraft.player != null; + private static void renderPortalSide(boolean rightSide, int xOffset, int yOffset, int uOffset) { + final Minecraft minecraft = Minecraft.getInstance(); + //noinspection DataFlowIssue + if ( + !minecraft.options.getCameraType().isFirstPerson() || + minecraft.gameMode.getPlayerMode() == GameType.SPECTATOR + ) return; + RenderSystem.enableBlend(); + RenderSystem.setShader(GameRenderer::getPositionTexColorShader); + RenderSystem.setShaderColor(1f, 1f, 1f, 1f); + if (PortalCubedConfig.enableRoundPortals) { + RenderSystem.setShaderTexture(0, ROUND_TEXTURE); + } else { + RenderSystem.setShaderTexture(0, SQUARE_TEXTURE); + } + assert minecraft.player != null; - if (minecraft.player.isHolding(s -> s.getItem() instanceof PortalGun)) { - final CorePhysicsEntity heldEntity = PortalCubedComponents.HOLDER_COMPONENT.get(minecraft.player).entityBeingHeld(); - if (heldEntity != null && !heldEntity.getType().is(PortalCubedEntities.P1_ENTITY)) return; + if (minecraft.player.isHolding(s -> s.getItem() instanceof PortalGun)) { + final CorePhysicsEntity heldEntity = PortalCubedComponents.HOLDER_COMPONENT.get(minecraft.player).entityBeingHeld(); + if (heldEntity != null && !heldEntity.getType().is(PortalCubedEntities.P1_ENTITY)) return; - ItemStack stack = minecraft.player.getItemBySlot(EquipmentSlot.MAINHAND); + ItemStack stack = minecraft.player.getItemBySlot(EquipmentSlot.MAINHAND); - if (!(stack.getItem() instanceof PortalGun)) { - stack = minecraft.player.getItemBySlot(EquipmentSlot.OFFHAND); - } - final PortalGun portalGun = (PortalGun)stack.getItem(); + if (!(stack.getItem() instanceof PortalGun)) { + stack = minecraft.player.getItemBySlot(EquipmentSlot.OFFHAND); + } + final PortalGun portalGun = (PortalGun)stack.getItem(); - int color = heldEntity == null - ? portalGun.getColorForHudHalf(stack, rightSide) - : 0xe4c9b1; + int color = heldEntity == null + ? portalGun.getColorForHudHalf(stack, rightSide) + : 0xe4c9b1; - float r = ((color & 0xFF0000) >>> 16) / 255f; - float g = ((color & 0xFF00) >>> 8) / 255f; - float b = (color & 0xFF) / 255f; - assert minecraft.level != null; - boolean portalActive = heldEntity == null && portalGun.isSideActive(minecraft.level, stack, rightSide); + float r = ((color & 0xFF0000) >>> 16) / 255f; + float g = ((color & 0xFF00) >>> 8) / 255f; + float b = (color & 0xFF) / 255f; + assert minecraft.level != null; + boolean portalActive = heldEntity == null && portalGun.isSideActive(minecraft.level, stack, rightSide); - final Window window = minecraft.getWindow(); - if (!portalActive) { - texture(window.getGuiScaledWidth() / 2 + xOffset, window.getGuiScaledHeight() / 2 + yOffset, -100, 8, 16, uOffset / 256f, 0 / 256f, 8 / 256f, 16 / 256f, r, g, b, 1); - } else { - texture(window.getGuiScaledWidth() / 2 + xOffset, window.getGuiScaledHeight() / 2 + yOffset, -100, 8, 16, (uOffset + 8) / 256f, 0 / 256f, 8 / 256f, 16 / 256f, r, g, b, 1); - } - } - } + final Window window = minecraft.getWindow(); + if (!portalActive) { + texture(window.getGuiScaledWidth() / 2 + xOffset, window.getGuiScaledHeight() / 2 + yOffset, -100, 8, 16, uOffset / 256f, 0 / 256f, 8 / 256f, 16 / 256f, r, g, b, 1); + } else { + texture(window.getGuiScaledWidth() / 2 + xOffset, window.getGuiScaledHeight() / 2 + yOffset, -100, 8, 16, (uOffset + 8) / 256f, 0 / 256f, 8 / 256f, 16 / 256f, r, g, b, 1); + } + } + } - private static void texture(int x, int y, int z, int width, int height, float u, float v, float uw, float vh, float r, float g, float b, float a) { - Tesselator tessellator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tessellator.getBuilder(); - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); - bufferBuilder.vertex(x, y + height, z).uv(u, v + vh).color(r, g, b, a).endVertex(); - bufferBuilder.vertex(x + width, y + height, z).uv(u + uw, v + vh).color(r, g, b, a).endVertex(); - bufferBuilder.vertex(x + width, y, z).uv(u + uw, v).color(r, g, b, a).endVertex(); - bufferBuilder.vertex(x, y, z).uv(u, v).color(r, g, b, a).endVertex(); - tessellator.end(); - } + private static void texture(int x, int y, int z, int width, int height, float u, float v, float uw, float vh, float r, float g, float b, float a) { + Tesselator tessellator = Tesselator.getInstance(); + BufferBuilder bufferBuilder = tessellator.getBuilder(); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); + bufferBuilder.vertex(x, y + height, z).uv(u, v + vh).color(r, g, b, a).endVertex(); + bufferBuilder.vertex(x + width, y + height, z).uv(u + uw, v + vh).color(r, g, b, a).endVertex(); + bufferBuilder.vertex(x + width, y, z).uv(u + uw, v).color(r, g, b, a).endVertex(); + bufferBuilder.vertex(x, y, z).uv(u, v).color(r, g, b, a).endVertex(); + tessellator.end(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/CullingCache.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/CullingCache.java index 6a2d399f..89516bdf 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/CullingCache.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/CullingCache.java @@ -9,36 +9,36 @@ public final class CullingCache { - private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); + private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); - private BlockPos centerPos; - private BlockState state; + private BlockPos centerPos; + private BlockState state; - private int completionFlags = 0; - private int values = 0; + private int completionFlags = 0; + private int values = 0; - public void prepare(BlockPos centerPos, BlockState state) { - this.centerPos = centerPos; - this.state = state; + public void prepare(BlockPos centerPos, BlockState state) { + this.centerPos = centerPos; + this.state = state; - this.completionFlags = 0; - this.values = 0; - } + this.completionFlags = 0; + this.values = 0; + } - public boolean shouldCull(QuadView quad, BlockAndTintGetter blockView) { - Direction cullFace = quad.cullFace(); - if (cullFace == null) return false; - int mask = 1 << cullFace.ordinal(); + public boolean shouldCull(QuadView quad, BlockAndTintGetter blockView) { + Direction cullFace = quad.cullFace(); + if (cullFace == null) return false; + int mask = 1 << cullFace.ordinal(); - if ((completionFlags & mask) == 0) { - completionFlags |= mask; + if ((completionFlags & mask) == 0) { + completionFlags |= mask; - boolean shouldCull = !Block.shouldRenderFace(state, blockView, centerPos, cullFace, pos.setWithOffset(centerPos, cullFace)); - if (shouldCull) values |= mask; - return shouldCull; - } else { - return (values & mask) == 0; - } - } + boolean shouldCull = !Block.shouldRenderFace(state, blockView, centerPos, cullFace, pos.setWithOffset(centerPos, cullFace)); + if (shouldCull) values |= mask; + return shouldCull; + } else { + return (values & mask) == 0; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveBakedModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveBakedModel.java index f6720441..8e324301 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveBakedModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveBakedModel.java @@ -30,76 +30,76 @@ public final class EmissiveBakedModel extends ForwardingBakedModel { - private static final Map> WRAPPERS = new Object2ObjectOpenHashMap<>(); - - public static void register(ResourceLocation modelId) { - WRAPPERS.put(modelId, EmissiveBakedModel::new); - } - - public static Optional wrap(ResourceLocation modelId, BakedModel model) { - if (!RenderMaterials.ARE_SUPPORTED) - return Optional.empty(); - final Function wrapper = WRAPPERS.get(new ResourceLocation(modelId.getNamespace(), modelId.getPath())); - if (wrapper != null) return Optional.of(wrapper.apply(model)); - return Optional.empty(); - } - - private static final Map TO_EMISSIVE = new ConcurrentHashMap<>(); - - private final QuadTransform emissiveTransform; - - EmissiveBakedModel(BakedModel model) { - this.wrapped = model; - this.emissiveTransform = quad -> { - TextureAtlasSprite sprite = getSpriteFinder().find(quad); - if (EmissiveSpriteRegistry.isEmissive(sprite.contents().name())) { - RenderMaterial material = quad.material(); - quad.material(getEmissiveMaterial(material)); - } - return true; - }; - } - - @Override - public boolean isVanillaAdapter() { - return false; - } - - @Override - public void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { - context.pushTransform(emissiveTransform); - super.emitBlockQuads(blockView, state, pos, randomSupplier, context); - context.popTransform(); - } - - @Override - public void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { - context.pushTransform(emissiveTransform); - super.emitItemQuads(stack, randomSupplier, context); - context.popTransform(); - } - - @Override - public List getQuads(BlockState blockState, Direction face, RandomSource rand) { - throw new UnsupportedOperationException("isVanillaAdapter is false! call emitBlockQuads/emitItemQuads!"); - } - - public static RenderMaterial getEmissiveMaterial(RenderMaterial base) { - return TO_EMISSIVE.computeIfAbsent(base, EmissiveBakedModel::makeEmissiveMaterial); - } - - private static RenderMaterial makeEmissiveMaterial(RenderMaterial base) { - return RenderMaterials.FINDER.copyFrom(base) - .emissive(true) - .disableDiffuse(true) - .ambientOcclusion(TriState.FALSE) - .find(); - } - - private static SpriteFinder getSpriteFinder() { - TextureAtlas blockAtlas = Minecraft.getInstance() - .getModelManager() - .getAtlas(InventoryMenu.BLOCK_ATLAS); - return SpriteFinder.get(blockAtlas); - } + private static final Map> WRAPPERS = new Object2ObjectOpenHashMap<>(); + + public static void register(ResourceLocation modelId) { + WRAPPERS.put(modelId, EmissiveBakedModel::new); + } + + public static Optional wrap(ResourceLocation modelId, BakedModel model) { + if (!RenderMaterials.ARE_SUPPORTED) + return Optional.empty(); + final Function wrapper = WRAPPERS.get(new ResourceLocation(modelId.getNamespace(), modelId.getPath())); + if (wrapper != null) return Optional.of(wrapper.apply(model)); + return Optional.empty(); + } + + private static final Map TO_EMISSIVE = new ConcurrentHashMap<>(); + + private final QuadTransform emissiveTransform; + + EmissiveBakedModel(BakedModel model) { + this.wrapped = model; + this.emissiveTransform = quad -> { + TextureAtlasSprite sprite = getSpriteFinder().find(quad); + if (EmissiveSpriteRegistry.isEmissive(sprite.contents().name())) { + RenderMaterial material = quad.material(); + quad.material(getEmissiveMaterial(material)); + } + return true; + }; + } + + @Override + public boolean isVanillaAdapter() { + return false; + } + + @Override + public void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { + context.pushTransform(emissiveTransform); + super.emitBlockQuads(blockView, state, pos, randomSupplier, context); + context.popTransform(); + } + + @Override + public void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { + context.pushTransform(emissiveTransform); + super.emitItemQuads(stack, randomSupplier, context); + context.popTransform(); + } + + @Override + public List getQuads(BlockState blockState, Direction face, RandomSource rand) { + throw new UnsupportedOperationException("isVanillaAdapter is false! call emitBlockQuads/emitItemQuads!"); + } + + public static RenderMaterial getEmissiveMaterial(RenderMaterial base) { + return TO_EMISSIVE.computeIfAbsent(base, EmissiveBakedModel::makeEmissiveMaterial); + } + + private static RenderMaterial makeEmissiveMaterial(RenderMaterial base) { + return RenderMaterials.FINDER.copyFrom(base) + .emissive(true) + .disableDiffuse(true) + .ambientOcclusion(TriState.FALSE) + .find(); + } + + private static SpriteFinder getSpriteFinder() { + TextureAtlas blockAtlas = Minecraft.getInstance() + .getModelManager() + .getAtlas(InventoryMenu.BLOCK_ATLAS); + return SpriteFinder.get(blockAtlas); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveSpriteRegistry.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveSpriteRegistry.java index ee278e64..e2815a30 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveSpriteRegistry.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/EmissiveSpriteRegistry.java @@ -7,19 +7,19 @@ public final class EmissiveSpriteRegistry { - private static final List SPRITES = new ObjectArrayList<>(); + private static final List SPRITES = new ObjectArrayList<>(); - public static boolean isEmissive(ResourceLocation spriteId) { - return SPRITES.contains(spriteId); - } + public static boolean isEmissive(ResourceLocation spriteId) { + return SPRITES.contains(spriteId); + } - public static void register(ResourceLocation modelId, ResourceLocation spriteId) { - EmissiveBakedModel.register(modelId); - register(spriteId); - } + public static void register(ResourceLocation modelId, ResourceLocation spriteId) { + EmissiveBakedModel.register(modelId); + register(spriteId); + } - public static void register(ResourceLocation spriteId) { - SPRITES.add(spriteId); - } + public static void register(ResourceLocation spriteId) { + SPRITES.add(spriteId); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/MultiRenderTypeSimpleBakedModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/MultiRenderTypeSimpleBakedModel.java index 4f923b50..decaddc3 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/MultiRenderTypeSimpleBakedModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/MultiRenderTypeSimpleBakedModel.java @@ -26,70 +26,70 @@ import net.minecraft.world.level.block.state.BlockState; public class MultiRenderTypeSimpleBakedModel extends ForwardingBakedModel { - public static final Map> SUPPORTED_TYPES = Map.of( - "default", () -> RenderMaterials.DEFAULT_MATERIAL, - "solid", () -> RenderMaterials.SOLID_MATERIAL, - "cutout", () -> RenderMaterials.CUTOUT_MATERIAL, - "translucent", () -> RenderMaterials.TRANSLUCENT_MATERIAL - ); - public static final String SUPPORTED_TYPE_LIST = String.join(", ", SUPPORTED_TYPES.keySet()); - - protected List> quads = new ArrayList<>(); - - public MultiRenderTypeSimpleBakedModel(SimpleBakedModel model) { - this.wrapped = model; - - List unculled = ((SimpleBakedModelAccessor) model).getUnculledFaces(); - unculled.forEach(quad -> addQuad(quad, null)); - - // side -> list of quads *not* culled - Map> culled = ((SimpleBakedModelAccessor) model).getCulledFaces(); - culled.forEach((cullFace, quads) -> quads.forEach(quad -> addQuad(quad, cullFace))); - } - - private void addQuad(BakedQuad quad, @Nullable Direction cullFace) { - String renderType = ((BakedQuadExt) quad).portalcubed$getRenderType(); - if (renderType == null) - renderType = "default"; - RenderMaterial material = parseType(renderType); - this.quads.add(Triple.of(quad, material, cullFace)); - } - - public void forEachQuad(TriConsumer consumer) { - quads.forEach(triple -> consumer.accept(triple.getLeft(), triple.getMiddle(), triple.getRight())); - } - - private TriConsumer emitTo(QuadEmitter emitter) { - return (quad, material, cullFace) -> { - emitter.fromVanilla(quad, material, cullFace); - emitter.emit(); - }; - } - - @Override - public void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { - forEachQuad(emitTo(context.getEmitter())); - } - - @Override - public void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { - forEachQuad(emitTo(context.getEmitter())); - } - - @Override - public List getQuads(BlockState blockState, Direction face, RandomSource rand) { - throw new UnsupportedOperationException("isVanillaAdapter is false! call emitBlockQuads/emitItemQuads!"); - } - - @Override - public boolean isVanillaAdapter() { - return false; - } - - public static RenderMaterial parseType(String name) throws JsonParseException { - Supplier type = SUPPORTED_TYPES.get(name); - if (type != null) - return type.get(); - throw new JsonParseException(name + " is not a supported RenderType. must be one of: " + SUPPORTED_TYPE_LIST); - } + public static final Map> SUPPORTED_TYPES = Map.of( + "default", () -> RenderMaterials.DEFAULT_MATERIAL, + "solid", () -> RenderMaterials.SOLID_MATERIAL, + "cutout", () -> RenderMaterials.CUTOUT_MATERIAL, + "translucent", () -> RenderMaterials.TRANSLUCENT_MATERIAL + ); + public static final String SUPPORTED_TYPE_LIST = String.join(", ", SUPPORTED_TYPES.keySet()); + + protected List> quads = new ArrayList<>(); + + public MultiRenderTypeSimpleBakedModel(SimpleBakedModel model) { + this.wrapped = model; + + List unculled = ((SimpleBakedModelAccessor) model).getUnculledFaces(); + unculled.forEach(quad -> addQuad(quad, null)); + + // side -> list of quads *not* culled + Map> culled = ((SimpleBakedModelAccessor) model).getCulledFaces(); + culled.forEach((cullFace, quads) -> quads.forEach(quad -> addQuad(quad, cullFace))); + } + + private void addQuad(BakedQuad quad, @Nullable Direction cullFace) { + String renderType = ((BakedQuadExt) quad).portalcubed$getRenderType(); + if (renderType == null) + renderType = "default"; + RenderMaterial material = parseType(renderType); + this.quads.add(Triple.of(quad, material, cullFace)); + } + + public void forEachQuad(TriConsumer consumer) { + quads.forEach(triple -> consumer.accept(triple.getLeft(), triple.getMiddle(), triple.getRight())); + } + + private TriConsumer emitTo(QuadEmitter emitter) { + return (quad, material, cullFace) -> { + emitter.fromVanilla(quad, material, cullFace); + emitter.emit(); + }; + } + + @Override + public void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { + forEachQuad(emitTo(context.getEmitter())); + } + + @Override + public void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { + forEachQuad(emitTo(context.getEmitter())); + } + + @Override + public List getQuads(BlockState blockState, Direction face, RandomSource rand) { + throw new UnsupportedOperationException("isVanillaAdapter is false! call emitBlockQuads/emitItemQuads!"); + } + + @Override + public boolean isVanillaAdapter() { + return false; + } + + public static RenderMaterial parseType(String name) throws JsonParseException { + Supplier type = SUPPORTED_TYPES.get(name); + if (type != null) + return type.get(); + throw new JsonParseException(name + " is not a supported RenderType. must be one of: " + SUPPORTED_TYPE_LIST); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/RenderMaterials.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/RenderMaterials.java index f05d0bf3..a264bcb3 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/RenderMaterials.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/RenderMaterials.java @@ -8,29 +8,29 @@ import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; public class RenderMaterials { - public static final boolean ARE_SUPPORTED; - public static final MaterialFinder FINDER; - public static final RenderMaterial DEFAULT_MATERIAL; - public static final RenderMaterial SOLID_MATERIAL; - public static final RenderMaterial CUTOUT_MATERIAL; - public static final RenderMaterial CUTOUT_MIPPED_MATERIAL; - public static final RenderMaterial TRANSLUCENT_MATERIAL; + public static final boolean ARE_SUPPORTED; + public static final MaterialFinder FINDER; + public static final RenderMaterial DEFAULT_MATERIAL; + public static final RenderMaterial SOLID_MATERIAL; + public static final RenderMaterial CUTOUT_MATERIAL; + public static final RenderMaterial CUTOUT_MIPPED_MATERIAL; + public static final RenderMaterial TRANSLUCENT_MATERIAL; - static { - Renderer renderer = RendererAccess.INSTANCE.getRenderer(); - ARE_SUPPORTED = renderer != null; - if (ARE_SUPPORTED) { - FINDER = renderer.materialFinder(); - DEFAULT_MATERIAL = FINDER.find(); - SOLID_MATERIAL = FINDER.blendMode(BlendMode.SOLID).find(); - CUTOUT_MATERIAL = FINDER.blendMode(BlendMode.CUTOUT).find(); - CUTOUT_MIPPED_MATERIAL = FINDER.blendMode(BlendMode.CUTOUT_MIPPED).find(); - TRANSLUCENT_MATERIAL = FINDER.blendMode(BlendMode.TRANSLUCENT).find(); - } else { - PortalCubed.LOGGER.error("No renderer present, rendering will be wrong. If you have Sodium, install Indium!"); - FINDER = null; - DEFAULT_MATERIAL = SOLID_MATERIAL = CUTOUT_MATERIAL = CUTOUT_MIPPED_MATERIAL = TRANSLUCENT_MATERIAL = null; - } - } + static { + Renderer renderer = RendererAccess.INSTANCE.getRenderer(); + ARE_SUPPORTED = renderer != null; + if (ARE_SUPPORTED) { + FINDER = renderer.materialFinder(); + DEFAULT_MATERIAL = FINDER.find(); + SOLID_MATERIAL = FINDER.blendMode(BlendMode.SOLID).find(); + CUTOUT_MATERIAL = FINDER.blendMode(BlendMode.CUTOUT).find(); + CUTOUT_MIPPED_MATERIAL = FINDER.blendMode(BlendMode.CUTOUT_MIPPED).find(); + TRANSLUCENT_MATERIAL = FINDER.blendMode(BlendMode.TRANSLUCENT).find(); + } else { + PortalCubed.LOGGER.error("No renderer present, rendering will be wrong. If you have Sodium, install Indium!"); + FINDER = null; + DEFAULT_MATERIAL = SOLID_MATERIAL = CUTOUT_MATERIAL = CUTOUT_MIPPED_MATERIAL = TRANSLUCENT_MATERIAL = null; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateModel.java index 59c6ffa4..12ae3546 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateModel.java @@ -9,71 +9,71 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BetaFaithPlateModel extends FaithPlateModel { - public static final ResourceLocation TEXTURE = id("textures/block/faith_plate.png"); - public static final ResourceLocation TEXTURE_E = id("textures/block/faith_plate_e.png"); + public static final ResourceLocation TEXTURE = id("textures/block/faith_plate.png"); + public static final ResourceLocation TEXTURE_E = id("textures/block/faith_plate_e.png"); - public static final ResourceLocation ANIMATION_FORWARD = id("beta_faith_plate/forward"); - public static final ResourceLocation ANIMATION_UPWARD = id("beta_faith_plate/upward"); + public static final ResourceLocation ANIMATION_FORWARD = id("beta_faith_plate/forward"); + public static final ResourceLocation ANIMATION_UPWARD = id("beta_faith_plate/upward"); - public BetaFaithPlateModel(ModelPart root) { - super(root); - } + public BetaFaithPlateModel(ModelPart root) { + super(root); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create(), PartPose.offset(0.0F, 15.3696F, -2.787F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create(), PartPose.offset(0.0F, 15.3696F, -2.787F)); - bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(42, 5).addBox(-0.5F, -2.5F, -3.5F, 2.0F, 2.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -1.4946F, 5.037F, 0.3927F, 0.0F, 0.0F)); + bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(42, 5).addBox(-0.5F, -2.5F, -3.5F, 2.0F, 2.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -1.4946F, 5.037F, 0.3927F, 0.0F, 0.0F)); - bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 15).addBox(-2.5F, -2.5F, -2.5F, 5.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.6196F, 0.037F, 0.7854F, 0.0F, 0.0F)); + bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 15).addBox(-2.5F, -2.5F, -2.5F, 5.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.6196F, 0.037F, 0.7854F, 0.0F, 0.0F)); - PartDefinition bone2 = bone.addOrReplaceChild("bone2", CubeListBuilder.create(), PartPose.offset(0.0F, -4.6712F, 7.4931F)); + PartDefinition bone2 = bone.addOrReplaceChild("bone2", CubeListBuilder.create(), PartPose.offset(0.0F, -4.6712F, 7.4931F)); - bone2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(44, 7).addBox(-0.5F, -2.5F, -1.5F, 2.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -0.5484F, -4.4561F, -0.3927F, 0.0F, 0.0F)); + bone2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(44, 7).addBox(-0.5F, -2.5F, -1.5F, 2.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -0.5484F, -4.4561F, -0.3927F, 0.0F, 0.0F)); - bone2.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 0).addBox(-0.5F, -0.5F, -0.5F, 3.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 0.0516F, -1.4561F, 0.7854F, 0.0F, 0.0F)); + bone2.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 0).addBox(-0.5F, -0.5F, -0.5F, 3.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 0.0516F, -1.4561F, 0.7854F, 0.0F, 0.0F)); - bone2.addOrReplaceChild("bone3", CubeListBuilder.create().texOffs(0, 0).addBox(-7.0167F, -2.3333F, -7.0F, 14.0F, 1.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(30, 18).addBox(-1.1167F, -1.3333F, -1.5F, 0.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)) - .texOffs(30, 18).addBox(1.1333F, -1.3333F, -1.5F, 0.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0167F, -2.3651F, -4.7061F)); + bone2.addOrReplaceChild("bone3", CubeListBuilder.create().texOffs(0, 0).addBox(-7.0167F, -2.3333F, -7.0F, 14.0F, 1.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(30, 18).addBox(-1.1167F, -1.3333F, -1.5F, 0.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)) + .texOffs(30, 18).addBox(1.1333F, -1.3333F, -1.5F, 0.0F, 3.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0167F, -2.3651F, -4.7061F)); - PartDefinition base = modelPartData.addOrReplaceChild("base", CubeListBuilder.create().texOffs(22, 15).addBox(1.0F, 11.5F, -15.0F, 14.0F, 0.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(36, 4).addBox(15.0F, 0.5F, -15.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(30, 32).addBox(14.99F, -0.51F, -16.01F, 1.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) - .texOffs(0, 26).addBox(0.99F, -0.51F, -1.01F, 14.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(12, 31).addBox(-0.01F, -0.51F, -16.01F, 1.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) - .texOffs(0, 28).addBox(0.99F, -0.51F, -16.01F, 14.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offset(-8.0F, 7.5F, 8.0F)); + PartDefinition base = modelPartData.addOrReplaceChild("base", CubeListBuilder.create().texOffs(22, 15).addBox(1.0F, 11.5F, -15.0F, 14.0F, 0.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(36, 4).addBox(15.0F, 0.5F, -15.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(30, 32).addBox(14.99F, -0.51F, -16.01F, 1.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) + .texOffs(0, 26).addBox(0.99F, -0.51F, -1.01F, 14.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(12, 31).addBox(-0.01F, -0.51F, -16.01F, 1.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) + .texOffs(0, 28).addBox(0.99F, -0.51F, -16.01F, 14.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offset(-8.0F, 7.5F, 8.0F)); - base.addOrReplaceChild("cubeinverted_r1", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, -1.5708F, 0.0F)); + base.addOrReplaceChild("cubeinverted_r1", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, -1.5708F, 0.0F)); - base.addOrReplaceChild("cubeinverted_r2", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, 3.1416F, 0.0F)); + base.addOrReplaceChild("cubeinverted_r2", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, 3.1416F, 0.0F)); - base.addOrReplaceChild("cubeinverted_r3", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, 1.5708F, 0.0F)); + base.addOrReplaceChild("cubeinverted_r3", CubeListBuilder.create().texOffs(36, 4).addBox(7.0F, -16.0F, -7.0F, 0.0F, 11.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(8.0F, 16.5F, -8.0F, 0.0F, 1.5708F, 0.0F)); - modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(21, 16).addBox(-2.65F, -10.75F, -4.75F, 0.0F, 5.0F, 4.0F, new CubeDeformation(0.0F)) - .texOffs(21, 16).addBox(2.65F, -10.75F, -4.75F, 0.0F, 5.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } + modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(21, 16).addBox(-2.65F, -10.75F, -4.75F, 0.0F, 5.0F, 4.0F, new CubeDeformation(0.0F)) + .texOffs(21, 16).addBox(2.65F, -10.75F, -4.75F, 0.0F, 5.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - protected ResourceLocation getForwardAnimation() { - return ANIMATION_FORWARD; - } + @Override + protected ResourceLocation getForwardAnimation() { + return ANIMATION_FORWARD; + } - @Override - protected ResourceLocation getUpwardAnimation() { - return ANIMATION_UPWARD; - } + @Override + protected ResourceLocation getUpwardAnimation() { + return ANIMATION_UPWARD; + } - @Override - public ResourceLocation getTexture(FaithPlateBlockEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTexture(FaithPlateBlockEntity entity) { + return TEXTURE; + } - @Override - public ResourceLocation getEmissiveTexture(FaithPlateBlockEntity entity) { - return TEXTURE_E; - } + @Override + public ResourceLocation getEmissiveTexture(FaithPlateBlockEntity entity) { + return TEXTURE_E; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateRenderer.java index c3d62ebc..ceea7ca5 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/BetaFaithPlateRenderer.java @@ -7,14 +7,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BetaFaithPlateRenderer extends EntityLikeBlockEntityRenderer { - public static final ModelLayerLocation BETA_FAITH_PLATE_LAYER = new ModelLayerLocation(id("beta_faith_plate"), "main"); + public static final ModelLayerLocation BETA_FAITH_PLATE_LAYER = new ModelLayerLocation(id("beta_faith_plate"), "main"); - public BetaFaithPlateRenderer(BlockEntityRendererProvider.Context ctx) { - super(ctx, BetaFaithPlateModel::new); - } + public BetaFaithPlateRenderer(BlockEntityRendererProvider.Context ctx) { + super(ctx, BetaFaithPlateModel::new); + } - @Override - protected ModelLayerLocation getModelLayer() { - return BETA_FAITH_PLATE_LAYER; - } + @Override + protected ModelLayerLocation getModelLayer() { + return BETA_FAITH_PLATE_LAYER; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityModel.java index 8d79a099..1ff535fd 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityModel.java @@ -9,13 +9,13 @@ import java.util.function.Function; public abstract class EntityLikeBlockEntityModel extends HierarchicalModel> { - protected EntityLikeBlockEntityModel(Function renderLayer) { - super(renderLayer); - } + protected EntityLikeBlockEntityModel(Function renderLayer) { + super(renderLayer); + } - public abstract ResourceLocation getTexture(T entity); + public abstract ResourceLocation getTexture(T entity); - public ResourceLocation getEmissiveTexture(T entity) { - return null; - } + public ResourceLocation getEmissiveTexture(T entity) { + return null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityRenderer.java index c99a91ba..d85745fe 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/EntityLikeBlockEntityRenderer.java @@ -22,47 +22,47 @@ import java.util.function.Function; public abstract class EntityLikeBlockEntityRenderer> implements BlockEntityRenderer { - private final EntityModelSet modelLoader; - private final Map, M>> wrapperModelPairs = new WeakHashMap<>(); - private final Function modelFactory; + private final EntityModelSet modelLoader; + private final Map, M>> wrapperModelPairs = new WeakHashMap<>(); + private final Function modelFactory; - protected EntityLikeBlockEntityRenderer(BlockEntityRendererProvider.Context ctx, Function modelFactory) { - modelLoader = ctx.getModelSet(); - this.modelFactory = modelFactory; - } + protected EntityLikeBlockEntityRenderer(BlockEntityRendererProvider.Context ctx, Function modelFactory) { + modelLoader = ctx.getModelSet(); + this.modelFactory = modelFactory; + } - private Pair, M> createWrapperModelPair(T entity) { - return Pair.of(new BlockEntityWrapperEntity<>(entity), modelFactory.apply(modelLoader.bakeLayer(getModelLayer()))); - } + private Pair, M> createWrapperModelPair(T entity) { + return Pair.of(new BlockEntityWrapperEntity<>(entity), modelFactory.apply(modelLoader.bakeLayer(getModelLayer()))); + } - @Override - public void render(T entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { - matrices.pushPose(); + @Override + public void render(T entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { + matrices.pushPose(); - matrices.mulPose(Axis.YP.rotationDegrees(180)); - matrices.scale(-1, -1, 1); - matrices.translate(0.5, -1.501, -0.5); + matrices.mulPose(Axis.YP.rotationDegrees(180)); + matrices.scale(-1, -1, 1); + matrices.translate(0.5, -1.501, -0.5); - final var wrapperModelPair = wrapperModelPairs.computeIfAbsent(entity, this::createWrapperModelPair); - final BlockEntityWrapperEntity wrapper = wrapperModelPair.key(); - final M model = wrapperModelPair.value(); + final var wrapperModelPair = wrapperModelPairs.computeIfAbsent(entity, this::createWrapperModelPair); + final BlockEntityWrapperEntity wrapper = wrapperModelPair.key(); + final M model = wrapperModelPair.value(); - final float yaw = Mth.rotLerp(tickDelta, entity.prevYaw, entity.getYaw()); - final float pitch = Mth.rotLerp(tickDelta, entity.prevPitch, entity.getPitch()); + final float yaw = Mth.rotLerp(tickDelta, entity.prevYaw, entity.getYaw()); + final float pitch = Mth.rotLerp(tickDelta, entity.prevPitch, entity.getPitch()); - model.prepareMobModel(wrapper, 0, 0, tickDelta); - model.setupAnim(wrapper, 0, 0, entity.getAge() + tickDelta, yaw, pitch); + model.prepareMobModel(wrapper, 0, 0, tickDelta); + model.setupAnim(wrapper, 0, 0, entity.getAge() + tickDelta, yaw, pitch); - final RenderType renderLayer = model.renderType(model.getTexture(entity)); - if (renderLayer != null) { - final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(renderLayer); - final int overlay2 = OverlayTexture.pack(OverlayTexture.u(0), OverlayTexture.v(false)); - model.renderToBuffer(matrices, vertexConsumer, light, overlay2, 1, 1, 1, 1); - EntityEmissiveRendering.renderEmissive(matrices, vertexConsumers, wrapper, model, e -> model.getEmissiveTexture(e.getBlockEntity())); - } + final RenderType renderLayer = model.renderType(model.getTexture(entity)); + if (renderLayer != null) { + final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(renderLayer); + final int overlay2 = OverlayTexture.pack(OverlayTexture.u(0), OverlayTexture.v(false)); + model.renderToBuffer(matrices, vertexConsumer, light, overlay2, 1, 1, 1, 1); + EntityEmissiveRendering.renderEmissive(matrices, vertexConsumers, wrapper, model, e -> model.getEmissiveTexture(e.getBlockEntity())); + } - matrices.popPose(); - } + matrices.popPose(); + } - protected abstract ModelLayerLocation getModelLayer(); + protected abstract ModelLayerLocation getModelLayer(); } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterBlockEntityRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterBlockEntityRenderer.java index 9be248d7..b6181f62 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterBlockEntityRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterBlockEntityRenderer.java @@ -22,64 +22,64 @@ import net.minecraft.world.phys.Vec3; public class ExcursionFunnelEmitterBlockEntityRenderer implements BlockEntityRenderer { - public static final List> REQUIRED_PROPERTIES = List.of( - TwoByTwoFacingMultiblockBlock.QUADRANT, - TwoByTwoFacingMultiblockBlock.FACING, - ExcursionFunnelEmitterBlock.MODE - ); + public static final List> REQUIRED_PROPERTIES = List.of( + TwoByTwoFacingMultiblockBlock.QUADRANT, + TwoByTwoFacingMultiblockBlock.FACING, + ExcursionFunnelEmitterBlock.MODE + ); - protected final ExcursionFunnelEmitterCenterModel forwardCenterModel, reversedCenterModel; + protected final ExcursionFunnelEmitterCenterModel forwardCenterModel, reversedCenterModel; - public ExcursionFunnelEmitterBlockEntityRenderer(Context ctx) { - this.forwardCenterModel = ExcursionFunnelEmitterCenterModel.forward(ctx); - this.reversedCenterModel = ExcursionFunnelEmitterCenterModel.reversed(ctx); - } + public ExcursionFunnelEmitterBlockEntityRenderer(Context ctx) { + this.forwardCenterModel = ExcursionFunnelEmitterCenterModel.forward(ctx); + this.reversedCenterModel = ExcursionFunnelEmitterCenterModel.reversed(ctx); + } - @Override - public void render(ExcursionFunnelEmitterBlockEntity be, float partialTicks, - PoseStack poseStack, MultiBufferSource buffers, int light, int overlay) { - BlockState state = be.getBlockState(); - Mode mode = state.getValue(ExcursionFunnelEmitterBlock.MODE); - Direction facing = state.getValue(TwoByTwoFacingMultiblockBlock.FACING); - ExcursionFunnelEmitterCenterModel centerModel = mode.isReversed ? reversedCenterModel : forwardCenterModel; + @Override + public void render(ExcursionFunnelEmitterBlockEntity be, float partialTicks, + PoseStack poseStack, MultiBufferSource buffers, int light, int overlay) { + BlockState state = be.getBlockState(); + Mode mode = state.getValue(ExcursionFunnelEmitterBlock.MODE); + Direction facing = state.getValue(TwoByTwoFacingMultiblockBlock.FACING); + ExcursionFunnelEmitterCenterModel centerModel = mode.isReversed ? reversedCenterModel : forwardCenterModel; - float tickTime = getTickTime(be.getLevel(), partialTicks, mode); - float rotation = tickTime / (mode.isReversed ? 6 : -6); + float tickTime = getTickTime(be.getLevel(), partialTicks, mode); + float rotation = tickTime / (mode.isReversed ? 6 : -6); - poseStack.pushPose(); + poseStack.pushPose(); - poseStack.translate(0.5, 0.5, 0.5); - poseStack.mulPose(facing.getRotation()); - poseStack.mulPose(Axis.XP.rotationDegrees(180)); - poseStack.translate(-0.5, -1.03, -0.5); - if (facing.getAxis().isVertical()) - poseStack.translate(1, 0, 1); + poseStack.translate(0.5, 0.5, 0.5); + poseStack.mulPose(facing.getRotation()); + poseStack.mulPose(Axis.XP.rotationDegrees(180)); + poseStack.translate(-0.5, -1.03, -0.5); + if (facing.getAxis().isVertical()) + poseStack.translate(1, 0, 1); - centerModel.rotate(rotation); - VertexConsumer consumer = buffers.getBuffer(centerModel.getRenderType()); - centerModel.renderToBuffer(poseStack, consumer, light, overlay, 1, 1, 1, 1); + centerModel.rotate(rotation); + VertexConsumer consumer = buffers.getBuffer(centerModel.getRenderType()); + centerModel.renderToBuffer(poseStack, consumer, light, overlay, 1, 1, 1, 1); - poseStack.popPose(); - } + poseStack.popPose(); + } - protected float getTickTime(@Nullable Level level, float partialTicks, Mode mode) { - if (level == null || !mode.isOn) - return 0; - long gameTime = level.getLevelData().getGameTime() % 10_000; // keep it small - return gameTime + partialTicks; - } + protected float getTickTime(@Nullable Level level, float partialTicks, Mode mode) { + if (level == null || !mode.isOn) + return 0; + long gameTime = level.getLevelData().getGameTime() % 10_000; // keep it small + return gameTime + partialTicks; + } - @Override - public boolean shouldRender(ExcursionFunnelEmitterBlockEntity be, Vec3 cameraPos) { - if (!be.hasLevel()) - return false; - BlockState state = be.getBlockState(); - for (Property property : REQUIRED_PROPERTIES) { - if (!state.hasProperty(property)) - return false; - } - if (state.getValue(TwoByTwoFacingMultiblockBlock.QUADRANT) != 1) - return false; - return BlockEntityRenderer.super.shouldRender(be, cameraPos); - } + @Override + public boolean shouldRender(ExcursionFunnelEmitterBlockEntity be, Vec3 cameraPos) { + if (!be.hasLevel()) + return false; + BlockState state = be.getBlockState(); + for (Property property : REQUIRED_PROPERTIES) { + if (!state.hasProperty(property)) + return false; + } + if (state.getValue(TwoByTwoFacingMultiblockBlock.QUADRANT) != 1) + return false; + return BlockEntityRenderer.super.shouldRender(be, cameraPos); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterCenterModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterCenterModel.java index 59910b37..a3ce1805 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterCenterModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/ExcursionFunnelEmitterCenterModel.java @@ -13,71 +13,71 @@ import net.minecraft.resources.ResourceLocation; public class ExcursionFunnelEmitterCenterModel extends Model { - public static final ResourceLocation TEXTURE = PortalCubed.id("textures/block/excursion_funnel_emitter_center.png"); - public static final ResourceLocation TEXTURE_REVERSED = PortalCubed.id("textures/block/excursion_funnel_emitter_center_reversed.png"); - public static final ModelLayerLocation LAYER = new ModelLayerLocation(TEXTURE, "main"); - public static final ModelLayerLocation LAYER_REVERSED = new ModelLayerLocation(TEXTURE_REVERSED, "main"); + public static final ResourceLocation TEXTURE = PortalCubed.id("textures/block/excursion_funnel_emitter_center.png"); + public static final ResourceLocation TEXTURE_REVERSED = PortalCubed.id("textures/block/excursion_funnel_emitter_center_reversed.png"); + public static final ModelLayerLocation LAYER = new ModelLayerLocation(TEXTURE, "main"); + public static final ModelLayerLocation LAYER_REVERSED = new ModelLayerLocation(TEXTURE_REVERSED, "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart you_spin_me_right_round; - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart you_spin_me_right_round; + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public final ResourceLocation texture; + public final ResourceLocation texture; - public ExcursionFunnelEmitterCenterModel(ModelPart root, ResourceLocation texture) { - super(RenderType::entityCutout); - this.you_spin_me_right_round = root.getChild("you_spin_me_right_round"); - this.bb_main = root.getChild("bb_main"); - this.texture = texture; - } + public ExcursionFunnelEmitterCenterModel(ModelPart root, ResourceLocation texture) { + super(RenderType::entityCutout); + this.you_spin_me_right_round = root.getChild("you_spin_me_right_round"); + this.bb_main = root.getChild("bb_main"); + this.texture = texture; + } - public RenderType getRenderType() { - return super.renderType(texture); - } + public RenderType getRenderType() { + return super.renderType(texture); + } - public static ExcursionFunnelEmitterCenterModel forward(Context ctx) { - return new ExcursionFunnelEmitterCenterModel(ctx.bakeLayer(LAYER), TEXTURE); - } + public static ExcursionFunnelEmitterCenterModel forward(Context ctx) { + return new ExcursionFunnelEmitterCenterModel(ctx.bakeLayer(LAYER), TEXTURE); + } - public static ExcursionFunnelEmitterCenterModel reversed(Context ctx) { - return new ExcursionFunnelEmitterCenterModel(ctx.bakeLayer(LAYER_REVERSED), TEXTURE_REVERSED); - } + public static ExcursionFunnelEmitterCenterModel reversed(Context ctx) { + return new ExcursionFunnelEmitterCenterModel(ctx.bakeLayer(LAYER_REVERSED), TEXTURE_REVERSED); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition createBodyLayer() { - MeshDefinition meshdefinition = new MeshDefinition(); - PartDefinition partdefinition = meshdefinition.getRoot(); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition createBodyLayer() { + MeshDefinition meshdefinition = new MeshDefinition(); + PartDefinition partdefinition = meshdefinition.getRoot(); - PartDefinition you_spin_me_right_round = partdefinition.addOrReplaceChild("you_spin_me_right_round", CubeListBuilder.create(), PartPose.offset(0.0F, 20.75F, 0.0F)); + PartDefinition you_spin_me_right_round = partdefinition.addOrReplaceChild("you_spin_me_right_round", CubeListBuilder.create(), PartPose.offset(0.0F, 20.75F, 0.0F)); - you_spin_me_right_round.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).mirror().addBox(0.75F, 0.0F, -3.5F, 8.0F, 0.0F, 13.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -3.1416F, 0.0F)); + you_spin_me_right_round.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).mirror().addBox(0.75F, 0.0F, -3.5F, 8.0F, 0.0F, 13.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -3.1416F, 0.0F)); - PartDefinition bb_main = partdefinition.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 27).addBox(0.0F, -2.7875F, 1.4257F, 7.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(0, 26).addBox(0.0F, -2.7875F, -1.4027F, 7.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + PartDefinition bb_main = partdefinition.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 27).addBox(0.0F, -2.7875F, 1.4257F, 7.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(0, 26).addBox(0.0F, -2.7875F, -1.4027F, 7.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(5, 18).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(5, 18).addBox(-2.5F, -1.0F, 2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0429F, -0.8375F, 0.0125F, 0.0F, 2.3562F, 0.0F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(5, 18).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(5, 18).addBox(-2.5F, -1.0F, 2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0429F, -0.8375F, 0.0125F, 0.0F, 2.3562F, 0.0F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(10, 18).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(0, 18).addBox(-2.5F, -1.0F, 2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(0, 13).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 0.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0429F, -0.8375F, 0.0125F, 0.0F, 0.7854F, 0.0F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(10, 18).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(0, 18).addBox(-2.5F, -1.0F, 2.5F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(0, 13).addBox(-2.5F, -1.0F, -2.5F, 5.0F, 0.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0429F, -0.8375F, 0.0125F, 0.0F, 0.7854F, 0.0F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 20).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)) - .texOffs(0, 6).addBox(-1.0F, -1.0F, -1.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(7.0F, -1.7875F, 0.0125F, 0.0F, 0.7854F, 0.0F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 20).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)) + .texOffs(0, 6).addBox(-1.0F, -1.0F, -1.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(7.0F, -1.7875F, 0.0125F, 0.0F, 0.7854F, 0.0F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 0).addBox(-1.0F, -1.0F, -1.0F, 2.0F, 4.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.7875F, 0.0125F, 0.0F, 0.7854F, 0.0F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 0).addBox(-1.0F, -1.0F, -1.0F, 2.0F, 4.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.7875F, 0.0125F, 0.0F, 0.7854F, 0.0F)); - return LayerDefinition.create(meshdefinition, 32, 32); - } + return LayerDefinition.create(meshdefinition, 32, 32); + } - public void rotate(float degrees) { - you_spin_me_right_round.setRotation(0, degrees, 0); - } + public void rotate(float degrees) { + you_spin_me_right_round.setRotation(0, degrees, 0); + } - @Override - public void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - you_spin_me_right_round.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); - bb_main.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); - } + @Override + public void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + you_spin_me_right_round.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); + bb_main.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateModel.java index 7f82aecb..71d5d021 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateModel.java @@ -13,90 +13,90 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class FaithPlateModel extends EntityLikeBlockEntityModel { - public static final ResourceLocation TEXTURE = id("textures/block/faith_plate.png"); - public static final ResourceLocation TEXTURE_E = id("textures/block/faith_plate_e.png"); - - public static final ResourceLocation ANIMATION_FORWARD = id("faith_plate/forward"); - public static final ResourceLocation ANIMATION_UPWARD = id("faith_plate/upward"); - - private final ModelPart root; - private final JsonAnimator animator = new JsonAnimator(this); - - public FaithPlateModel(ModelPart root) { - super(RenderType::entityTranslucent); - this.root = root; - } - - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition group = modelPartData.addOrReplaceChild("group", CubeListBuilder.create(), PartPose.offset(-8.0F, 2.0F, 11.5F)); - - group.addOrReplaceChild("bone3", CubeListBuilder.create().texOffs(20, 49).addBox(-4.0F, -0.5F, -16.0F, 8.0F, 1.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(2, 42).addBox(0.0F, 0.5F, -11.0F, 0.0F, 4.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(8.0F, 4.5F, -2.5F)); - - PartDefinition bone2 = group.addOrReplaceChild("bone2", CubeListBuilder.create(), PartPose.offset(8.0F, 7.2675F, -6.8446F)); - - bone2.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(14, 49).mirror().addBox(-2.0F, -3.0F, -3.0F, 4.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 1.0F, -2.0F, 0.7854F, 0.0F, 0.0F)); - - PartDefinition bone = group.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(50, 50).addBox(-2.25F, -1.5F, -1.3333F, 0.0F, 3.0F, 7.0F, new CubeDeformation(0.0F)) - .texOffs(50, 53).addBox(2.25F, -1.5F, -1.3333F, 0.0F, 3.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offset(8.0F, 8.25F, -15.4167F)); - - bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(16, 61).addBox(-4.0F, -0.5F, -0.5F, 8.0F, 1.0F, 1.0F, new CubeDeformation(-0.01F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.1667F, 0.7854F, 0.0F, 0.0F)); - - PartDefinition base = modelPartData.addOrReplaceChild("base", CubeListBuilder.create().texOffs(36, 6).addBox(-4.0F, -16.0F, -7.0F, 0.0F, 7.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(22, 29).addBox(4.0F, -17.0F, -8.0F, 4.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) - .texOffs(0, 28).addBox(-4.0F, -17.0F, -8.0F, 8.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(0, 30).addBox(-8.0F, -17.0F, -8.0F, 4.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) - .texOffs(0, 26).addBox(-4.0F, -17.0F, 7.0F, 8.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - - base.addOrReplaceChild("cubeinverted_r1", CubeListBuilder.create().texOffs(36, 6).addBox(-4.0F, -16.0F, -7.0F, 0.0F, 7.0F, 14.0F, new CubeDeformation(0.0F)) - .texOffs(28, 15).addBox(-4.0F, -9.0F, -7.0F, 8.0F, 0.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 3.1416F, 0.0F)); - - base.addOrReplaceChild("cubeinverted_r2", CubeListBuilder.create().texOffs(42, 14).addBox(0.0F, -3.5F, -4.0F, 0.0F, 7.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -12.5F, 7.0F, 0.0F, 1.5708F, 0.0F)); - - base.addOrReplaceChild("cubeinverted_r3", CubeListBuilder.create().texOffs(42, 14).addBox(-7.0F, -16.0F, -4.0F, 0.0F, 7.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -1.5708F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } - - @Override - public ModelPart root() { - return root; - } - - @Override - public void setupAnim(BlockEntityWrapperEntity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { - root().getAllParts().forEach(ModelPart::resetPose); - root.setRotation((float)Math.toRadians(headPitch), (float)Math.toRadians(headYaw), 0); - if (entity.getBlockEntity().pitch == 90f) { - final float radians = (float)Math.toRadians(entity.getBlockEntity().yaw); - root.setPos(-(float)Math.sin(radians) * 16f, 16f, -(float)Math.cos(radians) * 16f); - } else if (entity.getBlockEntity().pitch == -180f) { - root.setPos(0f, 32f, 0f); - } - final FaithPlateBlockEntity faithPlate = entity.getBlockEntity(); - final boolean upward = - faithPlate.getBlockState().getValue(FaithPlateBlock.FACING).getAxis().isVertical() && - faithPlate.getVelX() == 0 && faithPlate.getVelZ() == 0 && faithPlate.getVelY() != 0; - animator.animate(faithPlate.flingState, upward ? getUpwardAnimation() : getForwardAnimation(), animationProgress); - } - - protected ResourceLocation getForwardAnimation() { - return ANIMATION_FORWARD; - } - - protected ResourceLocation getUpwardAnimation() { - return ANIMATION_UPWARD; - } - - @Override - public ResourceLocation getTexture(FaithPlateBlockEntity entity) { - return TEXTURE; - } - - @Override - public ResourceLocation getEmissiveTexture(FaithPlateBlockEntity entity) { - return TEXTURE_E; - } + public static final ResourceLocation TEXTURE = id("textures/block/faith_plate.png"); + public static final ResourceLocation TEXTURE_E = id("textures/block/faith_plate_e.png"); + + public static final ResourceLocation ANIMATION_FORWARD = id("faith_plate/forward"); + public static final ResourceLocation ANIMATION_UPWARD = id("faith_plate/upward"); + + private final ModelPart root; + private final JsonAnimator animator = new JsonAnimator(this); + + public FaithPlateModel(ModelPart root) { + super(RenderType::entityTranslucent); + this.root = root; + } + + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition group = modelPartData.addOrReplaceChild("group", CubeListBuilder.create(), PartPose.offset(-8.0F, 2.0F, 11.5F)); + + group.addOrReplaceChild("bone3", CubeListBuilder.create().texOffs(20, 49).addBox(-4.0F, -0.5F, -16.0F, 8.0F, 1.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(2, 42).addBox(0.0F, 0.5F, -11.0F, 0.0F, 4.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(8.0F, 4.5F, -2.5F)); + + PartDefinition bone2 = group.addOrReplaceChild("bone2", CubeListBuilder.create(), PartPose.offset(8.0F, 7.2675F, -6.8446F)); + + bone2.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(14, 49).mirror().addBox(-2.0F, -3.0F, -3.0F, 4.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 1.0F, -2.0F, 0.7854F, 0.0F, 0.0F)); + + PartDefinition bone = group.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(50, 50).addBox(-2.25F, -1.5F, -1.3333F, 0.0F, 3.0F, 7.0F, new CubeDeformation(0.0F)) + .texOffs(50, 53).addBox(2.25F, -1.5F, -1.3333F, 0.0F, 3.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offset(8.0F, 8.25F, -15.4167F)); + + bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(16, 61).addBox(-4.0F, -0.5F, -0.5F, 8.0F, 1.0F, 1.0F, new CubeDeformation(-0.01F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.1667F, 0.7854F, 0.0F, 0.0F)); + + PartDefinition base = modelPartData.addOrReplaceChild("base", CubeListBuilder.create().texOffs(36, 6).addBox(-4.0F, -16.0F, -7.0F, 0.0F, 7.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(22, 29).addBox(4.0F, -17.0F, -8.0F, 4.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) + .texOffs(0, 28).addBox(-4.0F, -17.0F, -8.0F, 8.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(0, 30).addBox(-8.0F, -17.0F, -8.0F, 4.0F, 1.0F, 16.0F, new CubeDeformation(0.0F)) + .texOffs(0, 26).addBox(-4.0F, -17.0F, 7.0F, 8.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + + base.addOrReplaceChild("cubeinverted_r1", CubeListBuilder.create().texOffs(36, 6).addBox(-4.0F, -16.0F, -7.0F, 0.0F, 7.0F, 14.0F, new CubeDeformation(0.0F)) + .texOffs(28, 15).addBox(-4.0F, -9.0F, -7.0F, 8.0F, 0.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 3.1416F, 0.0F)); + + base.addOrReplaceChild("cubeinverted_r2", CubeListBuilder.create().texOffs(42, 14).addBox(0.0F, -3.5F, -4.0F, 0.0F, 7.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -12.5F, 7.0F, 0.0F, 1.5708F, 0.0F)); + + base.addOrReplaceChild("cubeinverted_r3", CubeListBuilder.create().texOffs(42, 14).addBox(-7.0F, -16.0F, -4.0F, 0.0F, 7.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -1.5708F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } + + @Override + public ModelPart root() { + return root; + } + + @Override + public void setupAnim(BlockEntityWrapperEntity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { + root().getAllParts().forEach(ModelPart::resetPose); + root.setRotation((float)Math.toRadians(headPitch), (float)Math.toRadians(headYaw), 0); + if (entity.getBlockEntity().pitch == 90f) { + final float radians = (float)Math.toRadians(entity.getBlockEntity().yaw); + root.setPos(-(float)Math.sin(radians) * 16f, 16f, -(float)Math.cos(radians) * 16f); + } else if (entity.getBlockEntity().pitch == -180f) { + root.setPos(0f, 32f, 0f); + } + final FaithPlateBlockEntity faithPlate = entity.getBlockEntity(); + final boolean upward = + faithPlate.getBlockState().getValue(FaithPlateBlock.FACING).getAxis().isVertical() && + faithPlate.getVelX() == 0 && faithPlate.getVelZ() == 0 && faithPlate.getVelY() != 0; + animator.animate(faithPlate.flingState, upward ? getUpwardAnimation() : getForwardAnimation(), animationProgress); + } + + protected ResourceLocation getForwardAnimation() { + return ANIMATION_FORWARD; + } + + protected ResourceLocation getUpwardAnimation() { + return ANIMATION_UPWARD; + } + + @Override + public ResourceLocation getTexture(FaithPlateBlockEntity entity) { + return TEXTURE; + } + + @Override + public ResourceLocation getEmissiveTexture(FaithPlateBlockEntity entity) { + return TEXTURE_E; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateRenderer.java index 44e80701..9058ae20 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/FaithPlateRenderer.java @@ -7,14 +7,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class FaithPlateRenderer extends EntityLikeBlockEntityRenderer { - public static final ModelLayerLocation FAITH_PLATE_LAYER = new ModelLayerLocation(id("faith_plate"), "main"); + public static final ModelLayerLocation FAITH_PLATE_LAYER = new ModelLayerLocation(id("faith_plate"), "main"); - public FaithPlateRenderer(BlockEntityRendererProvider.Context ctx) { - super(ctx, FaithPlateModel::new); - } + public FaithPlateRenderer(BlockEntityRendererProvider.Context ctx) { + super(ctx, FaithPlateModel::new); + } - @Override - protected ModelLayerLocation getModelLayer() { - return FAITH_PLATE_LAYER; - } + @Override + protected ModelLayerLocation getModelLayer() { + return FAITH_PLATE_LAYER; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/LaserEmitterRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/LaserEmitterRenderer.java index b40cf327..33905941 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/LaserEmitterRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/LaserEmitterRenderer.java @@ -13,74 +13,74 @@ import org.joml.Vector3f; public class LaserEmitterRenderer implements BlockEntityRenderer { - public LaserEmitterRenderer(BlockEntityRendererProvider.Context ctx) { - } + public LaserEmitterRenderer(BlockEntityRendererProvider.Context ctx) { + } - @Override - public boolean shouldRenderOffScreen(LaserEmitterBlockEntity blockEntity) { - return blockEntity.getMultiSegments() != null; - } + @Override + public boolean shouldRenderOffScreen(LaserEmitterBlockEntity blockEntity) { + return blockEntity.getMultiSegments() != null; + } - @Override - public int getViewDistance() { - return PortalCubedConfig.maxBridgeLength + 1; - } + @Override + public int getViewDistance() { + return PortalCubedConfig.maxBridgeLength + 1; + } - @Override - public void render(LaserEmitterBlockEntity entity, float tickDelta, @NotNull PoseStack matrices, @NotNull MultiBufferSource vertexConsumers, int light, int overlay) { - if (entity.getMultiSegments() == null) return; - final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lightning()); - final PoseStack.Pose matrix = matrices.last(); - for (final var segments : entity.getMultiSegments()) { - for (final var aimDestInfo : segments.rays()) { - final Vector3f start = aimDestInfo.start().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); - final Vector3f end = aimDestInfo.end().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); - drawSegments(vertexConsumer, matrix, start, end, 0.1f, 0f, 0f, 0.05f, 0.0f); - drawSegments(vertexConsumer, matrix, start, end, 1f, 0f, 0f, 0.02f, 0.01f); - drawSegments(vertexConsumer, matrix, start, end, 1f, 0.5f, 0.5f, 0.01f, 0.02f); - } - } - } + @Override + public void render(LaserEmitterBlockEntity entity, float tickDelta, @NotNull PoseStack matrices, @NotNull MultiBufferSource vertexConsumers, int light, int overlay) { + if (entity.getMultiSegments() == null) return; + final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lightning()); + final PoseStack.Pose matrix = matrices.last(); + for (final var segments : entity.getMultiSegments()) { + for (final var aimDestInfo : segments.rays()) { + final Vector3f start = aimDestInfo.start().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); + final Vector3f end = aimDestInfo.end().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); + drawSegments(vertexConsumer, matrix, start, end, 0.1f, 0f, 0f, 0.05f, 0.0f); + drawSegments(vertexConsumer, matrix, start, end, 1f, 0f, 0f, 0.02f, 0.01f); + drawSegments(vertexConsumer, matrix, start, end, 1f, 0.5f, 0.5f, 0.01f, 0.02f); + } + } + } - private void drawSegments(VertexConsumer vertexConsumer, PoseStack.Pose matrix, Vector3f start, Vector3f end, float r, float g, float b, float size, float offset) { - drawSegment(vertexConsumer, matrix, start, end, r, g, b, size, 0.0f, 0f, 0f, offset, 0f); - drawSegment(vertexConsumer, matrix, start, end, r, g, b, 0f, size, 0f, offset, 0f, offset); - drawSegment(vertexConsumer, matrix, start, end, r, g, b, 0f, 0.0f, size, 0f, offset, 0f); - } + private void drawSegments(VertexConsumer vertexConsumer, PoseStack.Pose matrix, Vector3f start, Vector3f end, float r, float g, float b, float size, float offset) { + drawSegment(vertexConsumer, matrix, start, end, r, g, b, size, 0.0f, 0f, 0f, offset, 0f); + drawSegment(vertexConsumer, matrix, start, end, r, g, b, 0f, size, 0f, offset, 0f, offset); + drawSegment(vertexConsumer, matrix, start, end, r, g, b, 0f, 0.0f, size, 0f, offset, 0f); + } - private void drawSegment(VertexConsumer vertexConsumer, PoseStack.Pose matrix, Vector3f start, Vector3f end, float r, float g, float b, float xSize1, float ySize1, float zSize1, float xSize2, float ySize2, float zSize2) { - vertexConsumer - .vertex(matrix.pose(), start.x() - xSize1 + xSize2, start.y() - ySize1 + ySize2, start.z() - zSize1 + zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), start.x() + xSize1 + xSize2, start.y() + ySize1 + ySize2, start.z() + zSize1 + zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), end.x() + xSize1 + xSize2, end.y() + ySize1 + ySize2, end.z() + zSize1 + zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), end.x() - xSize1 + xSize2, end.y() - ySize1 + ySize2, end.z() - zSize1 + zSize2) - .color(r, g, b, 1f) - .endVertex(); + private void drawSegment(VertexConsumer vertexConsumer, PoseStack.Pose matrix, Vector3f start, Vector3f end, float r, float g, float b, float xSize1, float ySize1, float zSize1, float xSize2, float ySize2, float zSize2) { + vertexConsumer + .vertex(matrix.pose(), start.x() - xSize1 + xSize2, start.y() - ySize1 + ySize2, start.z() - zSize1 + zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), start.x() + xSize1 + xSize2, start.y() + ySize1 + ySize2, start.z() + zSize1 + zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), end.x() + xSize1 + xSize2, end.y() + ySize1 + ySize2, end.z() + zSize1 + zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), end.x() - xSize1 + xSize2, end.y() - ySize1 + ySize2, end.z() - zSize1 + zSize2) + .color(r, g, b, 1f) + .endVertex(); - vertexConsumer - .vertex(matrix.pose(), start.x() - xSize1 - xSize2, start.y() - ySize1 - ySize2, start.z() - zSize1 - zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), end.x() - xSize1 - xSize2, end.y() - ySize1 - ySize2, end.z() - zSize1 - zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), end.x() + xSize1 - xSize2, end.y() + ySize1 - ySize2, end.z() + zSize1 - zSize2) - .color(r, g, b, 1f) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), start.x() + xSize1 - xSize2, start.y() + ySize1 - ySize2, start.z() + zSize1 - zSize2) - .color(r, g, b, 1f) - .endVertex(); - } + vertexConsumer + .vertex(matrix.pose(), start.x() - xSize1 - xSize2, start.y() - ySize1 - ySize2, start.z() - zSize1 - zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), end.x() - xSize1 - xSize2, end.y() - ySize1 - ySize2, end.z() - zSize1 - zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), end.x() + xSize1 - xSize2, end.y() + ySize1 - ySize2, end.z() + zSize1 - zSize2) + .color(r, g, b, 1f) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), start.x() + xSize1 - xSize2, start.y() + ySize1 - ySize2, start.z() + zSize1 - zSize2) + .color(r, g, b, 1f) + .endVertex(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/QuadrantModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/QuadrantModel.java index a58d14ff..05101d93 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/QuadrantModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/QuadrantModel.java @@ -12,55 +12,55 @@ import java.util.function.Supplier; public class QuadrantModel extends ForwardingBakedModel { - public static final Bounds[] BOUNDS = { - new Bounds(0, 2, 0, 2), - new Bounds(-2, 0, 0, 2), - new Bounds(-2, 0, -2, 0), - new Bounds(0, 2, -2, 0) - }; + public static final Bounds[] BOUNDS = { + new Bounds(0, 2, 0, 2), + new Bounds(-2, 0, 0, 2), + new Bounds(-2, 0, -2, 0), + new Bounds(0, 2, -2, 0) + }; - public final int quadrant; + public final int quadrant; - public final Bounds bounds; + public final Bounds bounds; - public QuadrantModel(BakedModel wrapped, int quadrant) { - this.wrapped = wrapped; - this.quadrant = quadrant; - this.bounds = BOUNDS[quadrant - 1]; - } + public QuadrantModel(BakedModel wrapped, int quadrant) { + this.wrapped = wrapped; + this.quadrant = quadrant; + this.bounds = BOUNDS[quadrant - 1]; + } - @Override - public boolean isVanillaAdapter() { - return false; - } + @Override + public boolean isVanillaAdapter() { + return false; + } - @Override - public void emitBlockQuads(BlockAndTintGetter level, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { - context.pushTransform(this::cropQuad); - context.bakedModelConsumer().accept(wrapped); - context.popTransform(); - } + @Override + public void emitBlockQuads(BlockAndTintGetter level, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { + context.pushTransform(this::cropQuad); + context.bakedModelConsumer().accept(wrapped); + context.popTransform(); + } - private boolean cropQuad(MutableQuadView quad) { - for (int i = 0; i < 4; i++) { - float x = quad.posByIndex(i, 0); - if (!bounds.containsX(x)) - return false; - float z = quad.posByIndex(i, 2); - if (!bounds.containsZ(z)) - return false; - float y = quad.posByIndex(i, 1); - } - return true; - } + private boolean cropQuad(MutableQuadView quad) { + for (int i = 0; i < 4; i++) { + float x = quad.posByIndex(i, 0); + if (!bounds.containsX(x)) + return false; + float z = quad.posByIndex(i, 2); + if (!bounds.containsZ(z)) + return false; + float y = quad.posByIndex(i, 1); + } + return true; + } - public record Bounds(float xMin, float xMax, float zMin, float zMax) { - public boolean containsX(float x) { - return x > xMin && x < xMax; - } + public record Bounds(float xMin, float xMax, float zMin, float zMax) { + public boolean containsX(float x) { + return x > xMin && x < xMax; + } - public boolean containsZ(float z) { - return z > zMin && z < zMax; - } - } + public boolean containsZ(float z) { + return z > zMin && z < zMax; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretModel.java index 6959eb7e..07cf3053 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretModel.java @@ -14,132 +14,132 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RocketTurretModel extends EntityLikeBlockEntityModel { - public static final ResourceLocation TEXTURE_ACTIVE = id("textures/block/rocket_turret_active.png"); - public static final ResourceLocation TEXTURE_ACTIVE_E = id("textures/block/rocket_turret_active_e.png"); - public static final ResourceLocation TEXTURE_INACTIVE = id("textures/block/rocket_turret_inactive.png"); + public static final ResourceLocation TEXTURE_ACTIVE = id("textures/block/rocket_turret_active.png"); + public static final ResourceLocation TEXTURE_ACTIVE_E = id("textures/block/rocket_turret_active_e.png"); + public static final ResourceLocation TEXTURE_INACTIVE = id("textures/block/rocket_turret_inactive.png"); - public static final ResourceLocation TEXTURE_LOCK_ON = id("textures/block/rocket_turret_lock_on.png"); - public static final ResourceLocation TEXTURE_LOCK_ON_E = id("textures/block/rocket_turret_lock_on_e.png"); + public static final ResourceLocation TEXTURE_LOCK_ON = id("textures/block/rocket_turret_lock_on.png"); + public static final ResourceLocation TEXTURE_LOCK_ON_E = id("textures/block/rocket_turret_lock_on_e.png"); - public static final ResourceLocation TEXTURE_FIRING = id("textures/block/rocket_turret_firing.png"); - public static final ResourceLocation TEXTURE_FIRING_E = id("textures/block/rocket_turret_firing_e.png"); + public static final ResourceLocation TEXTURE_FIRING = id("textures/block/rocket_turret_firing.png"); + public static final ResourceLocation TEXTURE_FIRING_E = id("textures/block/rocket_turret_firing_e.png"); - public static final ResourceLocation ANIMATION_ACTIVATE = id("rocket_turret/activate"); - public static final ResourceLocation ANIMATION_DEACTIVATE = id("rocket_turret/deactivate"); - public static final ResourceLocation ANIMATION_SHOOT = id("rocket_turret/shoot"); + public static final ResourceLocation ANIMATION_ACTIVATE = id("rocket_turret/activate"); + public static final ResourceLocation ANIMATION_DEACTIVATE = id("rocket_turret/deactivate"); + public static final ResourceLocation ANIMATION_SHOOT = id("rocket_turret/shoot"); - private final ModelPart root, turret, chassis, neck; - private final JsonAnimator animator = new JsonAnimator(this); + private final ModelPart root, turret, chassis, neck; + private final JsonAnimator animator = new JsonAnimator(this); - public RocketTurretModel(ModelPart root) { - super(RenderType::entityCutoutNoCull); - this.root = root; - turret = root.getChild("turret"); - chassis = turret.getChild("chassis"); - neck = chassis.getChild("segment_1").getChild("segment_2").getChild("segment_3").getChild("neck"); - } + public RocketTurretModel(ModelPart root) { + super(RenderType::entityCutoutNoCull); + this.root = root; + turret = root.getChild("turret"); + chassis = turret.getChild("chassis"); + neck = chassis.getChild("segment_1").getChild("segment_2").getChild("segment_3").getChild("neck"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition turret = modelPartData.addOrReplaceChild("turret", CubeListBuilder.create().texOffs(0, 29).addBox(-4.0F, -17.0F, -4.0F, 8.0F, 1.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 25.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition turret = modelPartData.addOrReplaceChild("turret", CubeListBuilder.create().texOffs(0, 29).addBox(-4.0F, -17.0F, -4.0F, 8.0F, 1.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 25.0F, 0.0F)); - PartDefinition chassis = turret.addOrReplaceChild("chassis", CubeListBuilder.create().texOffs(26, 32).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 3.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, -17.0F, 0.0F)); + PartDefinition chassis = turret.addOrReplaceChild("chassis", CubeListBuilder.create().texOffs(26, 32).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 3.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, -17.0F, 0.0F)); - chassis.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -1.0F, -1.0F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -1.5F, 1.5F, -0.7854F, 0.0F, 0.0F)); + chassis.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -1.0F, -1.0F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -1.5F, 1.5F, -0.7854F, 0.0F, 0.0F)); - PartDefinition segment_1 = chassis.addOrReplaceChild("segment_1", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, -1.0429F, 1.9571F, 0.3491F, 0.0F, 0.0F)); + PartDefinition segment_1 = chassis.addOrReplaceChild("segment_1", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, -1.0429F, 1.9571F, 0.3491F, 0.0F, 0.0F)); - segment_1.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 46).addBox(-2.5F, -1.5F, -2.0F, 5.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9874F, 2.841F, 0.7854F, 0.0F, 0.0F)); + segment_1.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 46).addBox(-2.5F, -1.5F, -2.0F, 5.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9874F, 2.841F, 0.7854F, 0.0F, 0.0F)); - segment_1.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 38).addBox(-2.5F, -2.0F, -2.0F, 5.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.5126F, -0.341F, 0.7854F, 0.0F, 0.0F)); + segment_1.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 38).addBox(-2.5F, -2.0F, -2.0F, 5.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.5126F, -0.341F, 0.7854F, 0.0F, 0.0F)); - PartDefinition segment_2 = segment_1.addOrReplaceChild("segment_2", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, -3.6137F, 3.4751F, 0.1309F, 0.0F, 0.0F)); + PartDefinition segment_2 = segment_1.addOrReplaceChild("segment_2", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, -3.6137F, 3.4751F, 0.1309F, 0.0F, 0.0F)); - segment_2.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -0.8826F, -1.0891F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.4742F, 3.3266F, -1.1781F, 0.0F, 0.0F)); + segment_2.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -0.8826F, -1.0891F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.4742F, 3.3266F, -1.1781F, 0.0F, 0.0F)); - segment_2.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(14, 42).addBox(-3.0F, 0.75F, -2.0F, 6.0F, 1.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -1.4951F, 1.4872F, 0.0436F, 0.0F, 0.0F)); + segment_2.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(14, 42).addBox(-3.0F, 0.75F, -2.0F, 6.0F, 1.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -1.4951F, 1.4872F, 0.0436F, 0.0F, 0.0F)); - PartDefinition segment_3 = segment_2.addOrReplaceChild("segment_3", CubeListBuilder.create(), PartPose.offset(0.0083F, -0.4755F, 3.1777F)); + PartDefinition segment_3 = segment_2.addOrReplaceChild("segment_3", CubeListBuilder.create(), PartPose.offset(0.0083F, -0.4755F, 3.1777F)); - segment_3.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -0.7298F, -1.2949F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.0083F, -3.1352F, 1.5022F, -2.7925F, 0.0F, 0.0F)); + segment_3.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(42, 21).addBox(-3.5F, -0.7298F, -1.2949F, 7.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.0083F, -3.1352F, 1.5022F, -2.7925F, 0.0F, 0.0F)); - segment_3.addOrReplaceChild("cube_r7", CubeListBuilder.create().texOffs(30, 42).addBox(-3.0F, -0.354F, 0.02F, 6.0F, 1.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.0083F, 0.0013F, 0.1489F, 1.1781F, 0.0F, 0.0F)); + segment_3.addOrReplaceChild("cube_r7", CubeListBuilder.create().texOffs(30, 42).addBox(-3.0F, -0.354F, 0.02F, 6.0F, 1.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.0083F, 0.0013F, 0.1489F, 1.1781F, 0.0F, 0.0F)); - PartDefinition neck = segment_3.addOrReplaceChild("neck", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0167F, -3.6138F, 1.5099F, -0.5105F, 0.0F, 0.0F)); + PartDefinition neck = segment_3.addOrReplaceChild("neck", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0167F, -3.6138F, 1.5099F, -0.5105F, 0.0F, 0.0F)); - neck.addOrReplaceChild("cube_r8", CubeListBuilder.create().texOffs(8, 16).addBox(-0.5F, -2.5728F, -0.4052F, 1.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.8232F, -2.5263F, -1.8326F, 0.0F, 0.0F)); + neck.addOrReplaceChild("cube_r8", CubeListBuilder.create().texOffs(8, 16).addBox(-0.5F, -2.5728F, -0.4052F, 1.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -0.8232F, -2.5263F, -1.8326F, 0.0F, 0.0F)); - PartDefinition head = neck.addOrReplaceChild("head", CubeListBuilder.create().texOffs(12, 52).addBox(-2.25F, -3.0F, -3.0F, 5.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)) - .texOffs(16, 0).addBox(-3.75F, -3.5F, -3.5F, 7.0F, 7.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offset(0.25F, -0.7007F, -5.6938F)); + PartDefinition head = neck.addOrReplaceChild("head", CubeListBuilder.create().texOffs(12, 52).addBox(-2.25F, -3.0F, -3.0F, 5.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)) + .texOffs(16, 0).addBox(-3.75F, -3.5F, -3.5F, 7.0F, 7.0F, 7.0F, new CubeDeformation(0.0F)), PartPose.offset(0.25F, -0.7007F, -5.6938F)); - PartDefinition hatch = head.addOrReplaceChild("hatch", CubeListBuilder.create().texOffs(37, 7).addBox(0.0F, -2.75F, -3.75F, 2.0F, 7.0F, 7.0F, new CubeDeformation(0.0F)) - .texOffs(44, 41).addBox(-3.0694F, -2.2721F, -2.7033F, 5.0F, 6.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(5.25F, -0.75F, 0.25F)); + PartDefinition hatch = head.addOrReplaceChild("hatch", CubeListBuilder.create().texOffs(37, 7).addBox(0.0F, -2.75F, -3.75F, 2.0F, 7.0F, 7.0F, new CubeDeformation(0.0F)) + .texOffs(44, 41).addBox(-3.0694F, -2.2721F, -2.7033F, 5.0F, 6.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(5.25F, -0.75F, 0.25F)); - hatch.addOrReplaceChild("missile_r1", CubeListBuilder.create().texOffs(38, 54).mirror().addBox(5.5374F, -8.5667F, -3.0513F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(38, 54).mirror().addBox(8.2947F, -9.9106F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(38, 54).mirror().addBox(6.527F, -8.1428F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(38, 54).mirror().addBox(7.2338F, -7.436F, -2.9903F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(38, 54).mirror().addBox(7.6577F, -6.4464F, -2.9597F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-12.25F, 1.0F, -0.25F, 0.0F, 0.0F, 0.7854F)); + hatch.addOrReplaceChild("missile_r1", CubeListBuilder.create().texOffs(38, 54).mirror().addBox(5.5374F, -8.5667F, -3.0513F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(38, 54).mirror().addBox(8.2947F, -9.9106F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(38, 54).mirror().addBox(6.527F, -8.1428F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(38, 54).mirror().addBox(7.2338F, -7.436F, -2.9903F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(38, 54).mirror().addBox(7.6577F, -6.4464F, -2.9597F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-12.25F, 1.0F, -0.25F, 0.0F, 0.0F, 0.7854F)); - hatch.addOrReplaceChild("missile_r2", CubeListBuilder.create().texOffs(38, 54).addBox(-1.4639F, -3.4932F, -3.0513F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) - .texOffs(38, 54).addBox(-0.12F, -0.7359F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) - .texOffs(38, 54).addBox(-1.8878F, -2.5036F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) - .texOffs(38, 54).addBox(-2.5946F, -1.7968F, -2.9903F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) - .texOffs(38, 54).addBox(-3.5842F, -1.3729F, -2.9597F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(1.2F, 1.0F, -0.25F, 0.0F, 0.0F, -0.7854F)); + hatch.addOrReplaceChild("missile_r2", CubeListBuilder.create().texOffs(38, 54).addBox(-1.4639F, -3.4932F, -3.0513F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) + .texOffs(38, 54).addBox(-0.12F, -0.7359F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) + .texOffs(38, 54).addBox(-1.8878F, -2.5036F, -3.0208F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) + .texOffs(38, 54).addBox(-2.5946F, -1.7968F, -2.9903F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)) + .texOffs(38, 54).addBox(-3.5842F, -1.3729F, -2.9597F, 1.0F, 0.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(1.2F, 1.0F, -0.25F, 0.0F, 0.0F, -0.7854F)); - PartDefinition gun = hatch.addOrReplaceChild("gun", CubeListBuilder.create(), PartPose.offset(0.95F, 1.4845F, 0.265F)); + PartDefinition gun = hatch.addOrReplaceChild("gun", CubeListBuilder.create(), PartPose.offset(0.95F, 1.4845F, 0.265F)); - gun.addOrReplaceChild("gun_r1", CubeListBuilder.create().texOffs(43, 25).addBox(-1.0F, -1.0F, -2.5F, 2.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, -1.5708F)); + gun.addOrReplaceChild("gun_r1", CubeListBuilder.create().texOffs(43, 25).addBox(-1.0F, -1.0F, -2.5F, 2.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, -1.5708F)); - PartDefinition barrel = gun.addOrReplaceChild("barrel", CubeListBuilder.create(), PartPose.offset(0.0F, 0.1952F, -4.9748F)); + PartDefinition barrel = gun.addOrReplaceChild("barrel", CubeListBuilder.create(), PartPose.offset(0.0F, 0.1952F, -4.9748F)); - barrel.addOrReplaceChild("barrel_r1", CubeListBuilder.create().texOffs(52, 27).addBox(-1.1574F, -0.1961F, -6.9597F, 1.0F, 1.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.25F, -0.6797F, 4.4597F, 0.0F, 0.0F, -0.7854F)); - return LayerDefinition.create(modelData, 64, 64); - } + barrel.addOrReplaceChild("barrel_r1", CubeListBuilder.create().texOffs(52, 27).addBox(-1.1574F, -0.1961F, -6.9597F, 1.0F, 1.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.25F, -0.6797F, 4.4597F, 0.0F, 0.0F, -0.7854F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public ModelPart root() { - return root; - } + @Override + public ModelPart root() { + return root; + } - @Override - public void setupAnim(BlockEntityWrapperEntity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { - root().getAllParts().forEach(ModelPart::resetPose); - chassis.setRotation(0, (float)Math.toRadians(headYaw - 90), 0); - neck.setRotation((float)Math.toRadians(headPitch - 30), (float)Math.toRadians(-0.5105f), 0); - animator.animate(entity.getBlockEntity().activatingAnimation, ANIMATION_ACTIVATE, animationProgress); - animator.animate(entity.getBlockEntity().deactivatingAnimation, ANIMATION_DEACTIVATE, animationProgress); - animator.animate(entity.getBlockEntity().shootAnimation, ANIMATION_SHOOT, animationProgress); - } + @Override + public void setupAnim(BlockEntityWrapperEntity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { + root().getAllParts().forEach(ModelPart::resetPose); + chassis.setRotation(0, (float)Math.toRadians(headYaw - 90), 0); + neck.setRotation((float)Math.toRadians(headPitch - 30), (float)Math.toRadians(-0.5105f), 0); + animator.animate(entity.getBlockEntity().activatingAnimation, ANIMATION_ACTIVATE, animationProgress); + animator.animate(entity.getBlockEntity().deactivatingAnimation, ANIMATION_DEACTIVATE, animationProgress); + animator.animate(entity.getBlockEntity().shootAnimation, ANIMATION_SHOOT, animationProgress); + } - @Override - public void renderToBuffer(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) { - turret.render(matrices, vertices, light, overlay, red, green, blue, alpha); - } + @Override + public void renderToBuffer(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) { + turret.render(matrices, vertices, light, overlay, red, green, blue, alpha); + } - @Override - public ResourceLocation getTexture(RocketTurretBlockEntity entity) { - if (entity.deactivatingAnimation.isStarted() && entity.deactivatingAnimation.getAccumulatedTime() >= 2000) { - return TEXTURE_INACTIVE; - } - return switch (entity.getState()) { - case SEARCHING -> TEXTURE_ACTIVE; - case LOCKED -> TEXTURE_LOCK_ON; - case FIRING -> TEXTURE_FIRING; - }; - } + @Override + public ResourceLocation getTexture(RocketTurretBlockEntity entity) { + if (entity.deactivatingAnimation.isStarted() && entity.deactivatingAnimation.getAccumulatedTime() >= 2000) { + return TEXTURE_INACTIVE; + } + return switch (entity.getState()) { + case SEARCHING -> TEXTURE_ACTIVE; + case LOCKED -> TEXTURE_LOCK_ON; + case FIRING -> TEXTURE_FIRING; + }; + } - @Override - public ResourceLocation getEmissiveTexture(RocketTurretBlockEntity entity) { - if (entity.deactivatingAnimation.isStarted() && entity.deactivatingAnimation.getAccumulatedTime() >= 2000) { - return null; - } - return switch (entity.getState()) { - case SEARCHING -> TEXTURE_ACTIVE_E; - case LOCKED -> TEXTURE_LOCK_ON_E; - case FIRING -> TEXTURE_FIRING_E; - }; - } + @Override + public ResourceLocation getEmissiveTexture(RocketTurretBlockEntity entity) { + if (entity.deactivatingAnimation.isStarted() && entity.deactivatingAnimation.getAccumulatedTime() >= 2000) { + return null; + } + return switch (entity.getState()) { + case SEARCHING -> TEXTURE_ACTIVE_E; + case LOCKED -> TEXTURE_LOCK_ON_E; + case FIRING -> TEXTURE_FIRING_E; + }; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretRenderer.java index 8f9ae17c..96412ce5 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/RocketTurretRenderer.java @@ -13,48 +13,48 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RocketTurretRenderer extends EntityLikeBlockEntityRenderer { - public static final ModelLayerLocation ROCKET_TURRET_LAYER = new ModelLayerLocation(id("rocket_turret"), "main"); - - public RocketTurretRenderer(BlockEntityRendererProvider.Context ctx) { - super(ctx, RocketTurretModel::new); - } - - @Override - public boolean shouldRenderOffScreen(RocketTurretBlockEntity blockEntity) { - return blockEntity.aimDests != null; - } - - @Override - public int getViewDistance() { - return 128; // So that the whole laser can be seen. See the raycast in RocketTurretBlockEntity.java. - } - - @Override - public void render(RocketTurretBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { - super.render(entity, tickDelta, matrices, vertexConsumers, light, overlay); - if (entity.aimDests == null) return; - - final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lines()); - final PoseStack.Pose matrix = matrices.last(); - for (final var aimDestInfo : entity.aimDests) { - final Vector3f origin = aimDestInfo.getA().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); - final Vector3f offset = aimDestInfo.getB().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); - final Vector3f normal = new Vector3f(offset).sub(origin).normalize(); - vertexConsumer - .vertex(matrix.pose(), origin.x(), origin.y(), origin.z()) - .color(130 / 255f, 200 / 255f, 230 / 255f, 0.25f) - .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), offset.x(), offset.y(), offset.z()) - .color(130 / 255f, 200 / 255f, 230 / 255f, 0.25f) - .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) - .endVertex(); - } - } - - @Override - protected ModelLayerLocation getModelLayer() { - return ROCKET_TURRET_LAYER; - } + public static final ModelLayerLocation ROCKET_TURRET_LAYER = new ModelLayerLocation(id("rocket_turret"), "main"); + + public RocketTurretRenderer(BlockEntityRendererProvider.Context ctx) { + super(ctx, RocketTurretModel::new); + } + + @Override + public boolean shouldRenderOffScreen(RocketTurretBlockEntity blockEntity) { + return blockEntity.aimDests != null; + } + + @Override + public int getViewDistance() { + return 128; // So that the whole laser can be seen. See the raycast in RocketTurretBlockEntity.java. + } + + @Override + public void render(RocketTurretBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { + super.render(entity, tickDelta, matrices, vertexConsumers, light, overlay); + if (entity.aimDests == null) return; + + final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lines()); + final PoseStack.Pose matrix = matrices.last(); + for (final var aimDestInfo : entity.aimDests) { + final Vector3f origin = aimDestInfo.getA().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); + final Vector3f offset = aimDestInfo.getB().subtract(Vec3.atLowerCornerOf(entity.getBlockPos())).toVector3f(); + final Vector3f normal = new Vector3f(offset).sub(origin).normalize(); + vertexConsumer + .vertex(matrix.pose(), origin.x(), origin.y(), origin.z()) + .color(130 / 255f, 200 / 255f, 230 / 255f, 0.25f) + .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), offset.x(), offset.y(), offset.z()) + .color(130 / 255f, 200 / 255f, 230 / 255f, 0.25f) + .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) + .endVertex(); + } + } + + @Override + protected ModelLayerLocation getModelLayer() { + return ROCKET_TURRET_LAYER; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/VelocityHelperRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/VelocityHelperRenderer.java index 6dd43fb2..8015e54d 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/VelocityHelperRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/block/entity/VelocityHelperRenderer.java @@ -13,32 +13,32 @@ import org.joml.Vector3f; public class VelocityHelperRenderer implements BlockEntityRenderer { - public VelocityHelperRenderer(BlockEntityRendererProvider.Context ctx) { - } + public VelocityHelperRenderer(BlockEntityRendererProvider.Context ctx) { + } - @Override - public boolean shouldRenderOffScreen(VelocityHelperBlockEntity blockEntity) { - return true; - } + @Override + public boolean shouldRenderOffScreen(VelocityHelperBlockEntity blockEntity) { + return true; + } - @Override - public void render(VelocityHelperBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { - if (!PortalCubedClient.hiddenBlocksVisible()) return; - if (entity.getDestination() != null) { - final BlockPos offset = entity.getDestination().subtract(entity.getBlockPos()); - final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lines()); - final PoseStack.Pose matrix = matrices.last(); - final Vector3f normal = Vec3.atLowerCornerOf(offset).normalize().toVector3f(); - vertexConsumer - .vertex(matrix.pose(), 0.5f, 0.5f, 0.5f) - .color(0.0f, 0.5f, 1.0f, 1.0f) - .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) - .endVertex(); - vertexConsumer - .vertex(matrix.pose(), offset.getX() + 0.5f, offset.getY() + 0.5f, offset.getZ() + 0.5f) - .color(1.0f, 0.5f, 0.0f, 1.0f) - .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) - .endVertex(); - } - } + @Override + public void render(VelocityHelperBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { + if (!PortalCubedClient.hiddenBlocksVisible()) return; + if (entity.getDestination() != null) { + final BlockPos offset = entity.getDestination().subtract(entity.getBlockPos()); + final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderType.lines()); + final PoseStack.Pose matrix = matrices.last(); + final Vector3f normal = Vec3.atLowerCornerOf(offset).normalize().toVector3f(); + vertexConsumer + .vertex(matrix.pose(), 0.5f, 0.5f, 0.5f) + .color(0.0f, 0.5f, 1.0f, 1.0f) + .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) + .endVertex(); + vertexConsumer + .vertex(matrix.pose(), offset.getX() + 0.5f, offset.getY() + 0.5f, offset.getZ() + 0.5f) + .color(1.0f, 0.5f, 0.0f, 1.0f) + .normal(matrix.normal(), normal.x(), normal.y(), normal.z()) + .endVertex(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/AdventureCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/AdventureCoreRenderer.java index b61d58e5..98442b12 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/AdventureCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/AdventureCoreRenderer.java @@ -11,17 +11,17 @@ public class AdventureCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); - public AdventureCoreRenderer(EntityRendererProvider.Context context) { - super(context, new AdventureCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(AdventureCoreModel.ADVENTURE_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public AdventureCoreRenderer(EntityRendererProvider.Context context) { + super(context, new AdventureCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(AdventureCoreModel.ADVENTURE_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(AdventureCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(AdventureCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/AngerCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/AngerCoreRenderer.java index 5a3246eb..37007a08 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/AngerCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/AngerCoreRenderer.java @@ -10,17 +10,17 @@ public class AngerCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); - public AngerCoreRenderer(EntityRendererProvider.Context context) { - super(context, new AngerCoreModel(context.bakeLayer(AngerCoreModel.ANGER_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public AngerCoreRenderer(EntityRendererProvider.Context context) { + super(context, new AngerCoreModel(context.bakeLayer(AngerCoreModel.ANGER_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(AngerCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(AngerCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/BeansRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/BeansRenderer.java index 3a2169ed..bd195761 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/BeansRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/BeansRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BeansRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/beans.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/beans.png"); - public BeansRenderer(EntityRendererProvider.Context context) { - super(context, new BeansModel(Minecraft.getInstance().getEntityModels().bakeLayer(BeansModel.BEANS_LAYER)), 0.5f); - } + public BeansRenderer(EntityRendererProvider.Context context) { + super(context, new BeansModel(Minecraft.getInstance().getEntityModels().bakeLayer(BeansModel.BEANS_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(BeansEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(BeansEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CakeCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CakeCoreRenderer.java index affc4687..8458580c 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CakeCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CakeCoreRenderer.java @@ -11,17 +11,17 @@ public class CakeCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); - public CakeCoreRenderer(EntityRendererProvider.Context context) { - super(context, new CakeCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(CakeCoreModel.CAKE_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public CakeCoreRenderer(EntityRendererProvider.Context context) { + super(context, new CakeCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(CakeCoreModel.CAKE_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(CakeCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(CakeCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ChairRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ChairRenderer.java index 3210b328..0d1e2786 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ChairRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ChairRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class ChairRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/chair.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/chair.png"); - public ChairRenderer(EntityRendererProvider.Context context) { - super(context, new ChairModel(Minecraft.getInstance().getEntityModels().bakeLayer(ChairModel.CHAIR_LAYER)), 0.5f); - } + public ChairRenderer(EntityRendererProvider.Context context) { + super(context, new ChairModel(Minecraft.getInstance().getEntityModels().bakeLayer(ChairModel.CHAIR_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(ChairEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(ChairEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CompanionCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CompanionCubeRenderer.java index 6874a593..5244ebfe 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CompanionCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CompanionCubeRenderer.java @@ -10,30 +10,30 @@ public class CompanionCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/companion_cube.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/companion_cube_e.png"); - - private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/companion_cube_lit.png"); - private static final ResourceLocation EMISSIVE_ACTIVE_TEXTURE = id("textures/entity/companion_cube_lit_e.png"); - - public CompanionCubeRenderer(EntityRendererProvider.Context context) { - super(context, new CompanionCubeModel(context.bakeLayer(CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> { - if (entity.isOnButton()) { - return EMISSIVE_ACTIVE_TEXTURE; - } - - return EMISSIVE_TEXTURE; - })); - } - - @Override - public ResourceLocation getTextureLocation(CompanionCubeEntity entity) { - if (entity.isOnButton()) { - return ACTIVE_TEXTURE; - } - - return TEXTURE; - } + private static final ResourceLocation TEXTURE = id("textures/entity/companion_cube.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/companion_cube_e.png"); + + private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/companion_cube_lit.png"); + private static final ResourceLocation EMISSIVE_ACTIVE_TEXTURE = id("textures/entity/companion_cube_lit_e.png"); + + public CompanionCubeRenderer(EntityRendererProvider.Context context) { + super(context, new CompanionCubeModel(context.bakeLayer(CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> { + if (entity.isOnButton()) { + return EMISSIVE_ACTIVE_TEXTURE; + } + + return EMISSIVE_TEXTURE; + })); + } + + @Override + public ResourceLocation getTextureLocation(CompanionCubeEntity entity) { + if (entity.isOnButton()) { + return ACTIVE_TEXTURE; + } + + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ComputerRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ComputerRenderer.java index 3d4b8682..b2182092 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ComputerRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ComputerRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class ComputerRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/computer.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/computer.png"); - public ComputerRenderer(EntityRendererProvider.Context context) { - super(context, new ComputerModel(Minecraft.getInstance().getEntityModels().bakeLayer(ComputerModel.COMPUTER_LAYER)), 0.5f); - } + public ComputerRenderer(EntityRendererProvider.Context context) { + super(context, new ComputerModel(Minecraft.getInstance().getEntityModels().bakeLayer(ComputerModel.COMPUTER_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(ComputerEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(ComputerEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CoreFrameRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CoreFrameRenderer.java index 21e93851..ff35103d 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CoreFrameRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CoreFrameRenderer.java @@ -9,15 +9,15 @@ public class CoreFrameRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/core_frame.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/core_frame.png"); - public CoreFrameRenderer(EntityRendererProvider.Context context) { - super(context, new CoreFrameModel(context.bakeLayer(CoreFrameModel.CORE_FRAME_LAYER)), 0.5f); - } + public CoreFrameRenderer(EntityRendererProvider.Context context) { + super(context, new CoreFrameModel(context.bakeLayer(CoreFrameModel.CORE_FRAME_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(CoreFrameEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(CoreFrameEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CorePhysicsRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CorePhysicsRenderer.java index 8af84dd3..2f2afe67 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CorePhysicsRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CorePhysicsRenderer.java @@ -8,17 +8,17 @@ import net.minecraft.client.renderer.entity.MobRenderer; public abstract class CorePhysicsRenderer> extends MobRenderer { - public CorePhysicsRenderer(EntityRendererProvider.Context context, M entityModel, float f) { - super(context, entityModel, f); - } + public CorePhysicsRenderer(EntityRendererProvider.Context context, M entityModel, float f) { + super(context, entityModel, f); + } - @Override - protected boolean shouldShowName(T entity) { - return entity.isCustomNameVisible() && super.shouldShowName(entity); - } + @Override + protected boolean shouldShowName(T entity) { + return entity.isCustomNameVisible() && super.shouldShowName(entity); + } - @Override - protected void setupRotations(T entity, PoseStack matrices, float animationProgress, float bodyYaw, float tickDelta) { - RayonIntegration.INSTANCE.multiplyMatrices(matrices, entity, tickDelta); - } + @Override + protected void setupRotations(T entity, PoseStack matrices, float animationProgress, float bodyYaw, float tickDelta) { + RayonIntegration.INSTANCE.multiplyMatrices(matrices, entity, tickDelta); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CuriosityCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CuriosityCoreRenderer.java index e27851e5..fd054737 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/CuriosityCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/CuriosityCoreRenderer.java @@ -11,17 +11,17 @@ public class CuriosityCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); - public CuriosityCoreRenderer(EntityRendererProvider.Context context) { - super(context, new CuriosityCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(CuriosityCoreModel.CURIOSITY_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public CuriosityCoreRenderer(EntityRendererProvider.Context context) { + super(context, new CuriosityCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(CuriosityCoreModel.CURIOSITY_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(CuriosityCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(CuriosityCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/EnergyPelletRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/EnergyPelletRenderer.java index 9c994cac..22ed9d3f 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/EnergyPelletRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/EnergyPelletRenderer.java @@ -8,18 +8,18 @@ import net.minecraft.util.Mth; public class EnergyPelletRenderer extends ThrownItemRenderer { - public static Float pelletAlpha = null; + public static Float pelletAlpha = null; - public EnergyPelletRenderer(EntityRendererProvider.Context ctx) { - super(ctx, 1f, true); - } + public EnergyPelletRenderer(EntityRendererProvider.Context ctx) { + super(ctx, 1f, true); + } - @Override - public void render(EnergyPellet entity, float yaw, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { - if (entity.getStartingLife() > 0) { - pelletAlpha = Mth.clamp(Mth.lerp((float)entity.getLife() / entity.getStartingLife(), 0.25f, 1f), 0f, 1f); - } - super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); - pelletAlpha = null; - } + @Override + public void render(EnergyPellet entity, float yaw, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { + if (entity.getStartingLife() > 0) { + pelletAlpha = Mth.clamp(Mth.lerp((float)entity.getLife() / entity.getStartingLife(), 0.25f, 1f), 0f, 1f); + } + super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); + pelletAlpha = null; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ExcursionFunnelRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ExcursionFunnelRenderer.java index 2fe68884..1be40891 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/ExcursionFunnelRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/ExcursionFunnelRenderer.java @@ -13,26 +13,26 @@ import org.jetbrains.annotations.NotNull; public class ExcursionFunnelRenderer extends EntityRenderer { - public ExcursionFunnelRenderer(Context context) { - super(context); - } + public ExcursionFunnelRenderer(Context context) { + super(context); + } - @Override - public void render(ExcursionFunnelEntity entity, float entityYaw, float partialTick, PoseStack poseStack, MultiBufferSource buffer, int packedLight) { - if (entity.model == null) - entity.model = new ExcursionFunnelModel(entity); - ExcursionFunnelModel model = entity.model; - VertexConsumer consumer = buffer.getBuffer(model.renderType(getTextureLocation(entity))); + @Override + public void render(ExcursionFunnelEntity entity, float entityYaw, float partialTick, PoseStack poseStack, MultiBufferSource buffer, int packedLight) { + if (entity.model == null) + entity.model = new ExcursionFunnelModel(entity); + ExcursionFunnelModel model = entity.model; + VertexConsumer consumer = buffer.getBuffer(model.renderType(getTextureLocation(entity))); - poseStack.pushPose(); - poseStack.mulPose(entity.getFacing().getRotation()); - model.renderToBuffer(poseStack, consumer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, 1, 1, 1, 1); - poseStack.popPose(); - } + poseStack.pushPose(); + poseStack.mulPose(entity.getFacing().getRotation()); + model.renderToBuffer(poseStack, consumer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, 1, 1, 1, 1); + poseStack.popPose(); + } - @Override - @NotNull - public ResourceLocation getTextureLocation(ExcursionFunnelEntity entity) { - return entity.isReversed() ? ExcursionFunnelModel.REVERSED_TEXTURE : ExcursionFunnelModel.TEXTURE; - } + @Override + @NotNull + public ResourceLocation getTextureLocation(ExcursionFunnelEntity entity) { + return entity.isReversed() ? ExcursionFunnelModel.REVERSED_TEXTURE : ExcursionFunnelModel.TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/FactCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/FactCoreRenderer.java index 2436368d..8cd11747 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/FactCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/FactCoreRenderer.java @@ -11,17 +11,17 @@ public class FactCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); - public FactCoreRenderer(EntityRendererProvider.Context context) { - super(context, new FactCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(FactCoreModel.FACT_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public FactCoreRenderer(EntityRendererProvider.Context context) { + super(context, new FactCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(FactCoreModel.FACT_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(FactCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(FactCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/GelBlobRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/GelBlobRenderer.java index b8420f8c..e9fed840 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/GelBlobRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/GelBlobRenderer.java @@ -19,55 +19,55 @@ import java.util.EnumSet; public class GelBlobRenderer extends EntityRenderer { - private final ModelPart.Cube cube; + private final ModelPart.Cube cube; - public GelBlobRenderer(EntityRendererProvider.Context context) { - super(context); - cube = new ModelPart.Cube( - 0, 0, // U, V - -8, 0, -8, // X, Y, Z - 16, 16, 16, // XS, YS, ZS - 0, 0, 0, // Extra XS, Extra YS, Extra ZS - false, // Mirror - 1, 1, // U width, V height - EnumSet.allOf(Direction.class) - ); - } + public GelBlobRenderer(EntityRendererProvider.Context context) { + super(context); + cube = new ModelPart.Cube( + 0, 0, // U, V + -8, 0, -8, // X, Y, Z + 16, 16, 16, // XS, YS, ZS + 0, 0, 0, // Extra XS, Extra YS, Extra ZS + false, // Mirror + 1, 1, // U width, V height + EnumSet.allOf(Direction.class) + ); + } - // Math from https://github.com/Tectato/Vectorientation/blob/2bfe2fc2d2c36f8af3550df09d1b5d7938869a70/src/main/java/vectorientation/mixin/FallingBlockRendererMixin.java - @Override - public void render(GelBlobEntity entity, float yaw, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { - final VertexConsumer consumer = vertexConsumers.getBuffer(RenderType.entitySolid(getTextureLocation(entity))); - matrices.pushPose(); + // Math from https://github.com/Tectato/Vectorientation/blob/2bfe2fc2d2c36f8af3550df09d1b5d7938869a70/src/main/java/vectorientation/mixin/FallingBlockRendererMixin.java + @Override + public void render(GelBlobEntity entity, float yaw, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { + final VertexConsumer consumer = vertexConsumers.getBuffer(RenderType.entitySolid(getTextureLocation(entity))); + matrices.pushPose(); - final Vector3f vel = entity.getDeltaMovement().toVector3f(); - final float y = (vel.y() - 0.04f * tickDelta) * 0.98f; - float speed = (float)Math.sqrt(vel.x() * vel.x() + y * y + vel.z() * vel.z()); - vel.normalize(); - final float angle = (float)Math.acos(Mth.clamp(y, -1, 1)); - vel.set(-1 * vel.z(), 0, vel.x()); - vel.normalize(); - final Quaternionf rot = new Quaternionf().setAngleAxis(-angle, vel.x, vel.y, vel.z); - matrices.translate(0, 0.5, 0); - matrices.mulPose(rot); - speed += 0.75f; - matrices.scale(1 / speed, speed, 1 / speed); - matrices.translate(0, -0.5, 0); + final Vector3f vel = entity.getDeltaMovement().toVector3f(); + final float y = (vel.y() - 0.04f * tickDelta) * 0.98f; + float speed = (float)Math.sqrt(vel.x() * vel.x() + y * y + vel.z() * vel.z()); + vel.normalize(); + final float angle = (float)Math.acos(Mth.clamp(y, -1, 1)); + vel.set(-1 * vel.z(), 0, vel.x()); + vel.normalize(); + final Quaternionf rot = new Quaternionf().setAngleAxis(-angle, vel.x, vel.y, vel.z); + matrices.translate(0, 0.5, 0); + matrices.mulPose(rot); + speed += 0.75f; + matrices.scale(1 / speed, speed, 1 / speed); + matrices.translate(0, -0.5, 0); - final float scale = entity.getScale(); - matrices.scale(scale, scale, scale); + final float scale = entity.getScale(); + matrices.scale(scale, scale, scale); - cube.compile( - matrices.last(), consumer, - light, OverlayTexture.NO_OVERLAY, 1, 1, 1, 1 - ); - matrices.popPose(); - super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); - } + cube.compile( + matrices.last(), consumer, + light, OverlayTexture.NO_OVERLAY, 1, 1, 1, 1 + ); + matrices.popPose(); + super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); + } - @NotNull - @Override - public ResourceLocation getTextureLocation(GelBlobEntity entity) { - return entity.getTexture(); - } + @NotNull + @Override + public ResourceLocation getTextureLocation(GelBlobEntity entity) { + return entity.getTexture(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/HoopyRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/HoopyRenderer.java index 2ddd1bc0..9393d7f2 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/HoopyRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/HoopyRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class HoopyRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/hoopy.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/hoopy.png"); - public HoopyRenderer(EntityRendererProvider.Context context) { - super(context, new HoopyModel(Minecraft.getInstance().getEntityModels().bakeLayer(HoopyModel.HOOPY_LAYER)), 0.5f); - } + public HoopyRenderer(EntityRendererProvider.Context context) { + super(context, new HoopyModel(Minecraft.getInstance().getEntityModels().bakeLayer(HoopyModel.HOOPY_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(HoopyEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(HoopyEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/JugRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/JugRenderer.java index 366ce838..8ad09ed4 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/JugRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/JugRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class JugRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/water_jug.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/water_jug.png"); - public JugRenderer(EntityRendererProvider.Context context) { - super(context, new JugModel(Minecraft.getInstance().getEntityModels().bakeLayer(JugModel.JUG_LAYER)), 0.5f); - } + public JugRenderer(EntityRendererProvider.Context context) { + super(context, new JugModel(Minecraft.getInstance().getEntityModels().bakeLayer(JugModel.JUG_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(JugEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(JugEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/LilPineappleRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/LilPineappleRenderer.java index 14f7d095..e9efc6ea 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/LilPineappleRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/LilPineappleRenderer.java @@ -12,56 +12,56 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class LilPineappleRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/lil_pineapple.png"); - private static final ResourceLocation PROUD_TEXTURE = id("textures/entity/lil_prideapple_proud.png"); - private static final ResourceLocation ACE_TEXTURE = id("textures/entity/lil_prideapple_ace.png"); - private static final ResourceLocation AGENDER_TEXTURE = id("textures/entity/lil_prideapple_agender.png"); - private static final ResourceLocation ARO_TEXTURE = id("textures/entity/lil_prideapple_aro.png"); - private static final ResourceLocation BI_TEXTURE = id("textures/entity/lil_prideapple_bi.png"); - private static final ResourceLocation GENDERFLUID_TEXTURE = id("textures/entity/lil_prideapple_genderfluid.png"); - private static final ResourceLocation LESBIAN_TEXTURE = id("textures/entity/lil_prideapple_lesbian.png"); - private static final ResourceLocation NONBINARY_TEXTURE = id("textures/entity/lil_prideapple_nonbinary.png"); - private static final ResourceLocation PAN_TEXTURE = id("textures/entity/lil_prideapple_pan.png"); - private static final ResourceLocation TRANS_TEXTURE = id("textures/entity/lil_prideapple_trans.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/lil_pineapple.png"); + private static final ResourceLocation PROUD_TEXTURE = id("textures/entity/lil_prideapple_proud.png"); + private static final ResourceLocation ACE_TEXTURE = id("textures/entity/lil_prideapple_ace.png"); + private static final ResourceLocation AGENDER_TEXTURE = id("textures/entity/lil_prideapple_agender.png"); + private static final ResourceLocation ARO_TEXTURE = id("textures/entity/lil_prideapple_aro.png"); + private static final ResourceLocation BI_TEXTURE = id("textures/entity/lil_prideapple_bi.png"); + private static final ResourceLocation GENDERFLUID_TEXTURE = id("textures/entity/lil_prideapple_genderfluid.png"); + private static final ResourceLocation LESBIAN_TEXTURE = id("textures/entity/lil_prideapple_lesbian.png"); + private static final ResourceLocation NONBINARY_TEXTURE = id("textures/entity/lil_prideapple_nonbinary.png"); + private static final ResourceLocation PAN_TEXTURE = id("textures/entity/lil_prideapple_pan.png"); + private static final ResourceLocation TRANS_TEXTURE = id("textures/entity/lil_prideapple_trans.png"); - public LilPineappleRenderer(EntityRendererProvider.Context context) { - super(context, new LilPineappleModel(Minecraft.getInstance().getEntityModels().bakeLayer(LilPineappleModel.LIL_PINEAPPLE)), 0.5f); - } + public LilPineappleRenderer(EntityRendererProvider.Context context) { + super(context, new LilPineappleModel(Minecraft.getInstance().getEntityModels().bakeLayer(LilPineappleModel.LIL_PINEAPPLE)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(LilPineappleEntity entity) { - if (entity.getCustomName() != null) { - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "proud")) { - return PROUD_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "ace")) { - return ACE_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "aro")) { - return ARO_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "agender")) { - return AGENDER_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "bi")) { - return BI_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "genderfluid")) { - return GENDERFLUID_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "lesbian")) { - return LESBIAN_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "nonbinary")) { - return NONBINARY_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "pan")) { - return PAN_TEXTURE; - } - if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "trans")) { - return TRANS_TEXTURE; - } - } - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(LilPineappleEntity entity) { + if (entity.getCustomName() != null) { + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "proud")) { + return PROUD_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "ace")) { + return ACE_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "aro")) { + return ARO_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "agender")) { + return AGENDER_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "bi")) { + return BI_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "genderfluid")) { + return GENDERFLUID_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "lesbian")) { + return LESBIAN_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "nonbinary")) { + return NONBINARY_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "pan")) { + return PAN_TEXTURE; + } + if (Objects.equals(entity.getCustomName().getString().toLowerCase(Locale.ROOT), "trans")) { + return TRANS_TEXTURE; + } + } + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/MoralityCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/MoralityCoreRenderer.java index bd0a9e86..76403db0 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/MoralityCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/MoralityCoreRenderer.java @@ -11,17 +11,17 @@ public class MoralityCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_1_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_1_cores_e.png"); - public MoralityCoreRenderer(EntityRendererProvider.Context context) { - super(context, new MoralityCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(MoralityCoreModel.MORTALITY_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public MoralityCoreRenderer(EntityRendererProvider.Context context) { + super(context, new MoralityCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(MoralityCoreModel.MORTALITY_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(MoralityCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(MoralityCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/MugRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/MugRenderer.java index c9bd499a..30eab71e 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/MugRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/MugRenderer.java @@ -9,26 +9,26 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class MugRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE0 = id("textures/entity/mug_red.png"); - private static final ResourceLocation BASE_TEXTURE1 = id("textures/entity/mug_white.png"); - private static final ResourceLocation BASE_TEXTURE2 = id("textures/entity/mug_blue.png"); - private static final ResourceLocation BASE_TEXTURE3 = id("textures/entity/mug_yellow.png"); + private static final ResourceLocation BASE_TEXTURE0 = id("textures/entity/mug_red.png"); + private static final ResourceLocation BASE_TEXTURE1 = id("textures/entity/mug_white.png"); + private static final ResourceLocation BASE_TEXTURE2 = id("textures/entity/mug_blue.png"); + private static final ResourceLocation BASE_TEXTURE3 = id("textures/entity/mug_yellow.png"); - public MugRenderer(EntityRendererProvider.Context context) { - super(context, new MugModel(Minecraft.getInstance().getEntityModels().bakeLayer(MugModel.MUG_LAYER)), 0.5f); - } + public MugRenderer(EntityRendererProvider.Context context) { + super(context, new MugModel(Minecraft.getInstance().getEntityModels().bakeLayer(MugModel.MUG_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(MugEntity entity) { - if (entity.getMugType() == 20) { - entity.genMugType(); - } - if (entity.getMugType() == 0) - return BASE_TEXTURE0; - if (entity.getMugType() == 1) - return BASE_TEXTURE1; - if (entity.getMugType() == 2) - return BASE_TEXTURE2; - return BASE_TEXTURE3; - } + @Override + public ResourceLocation getTextureLocation(MugEntity entity) { + if (entity.getMugType() == 20) { + entity.genMugType(); + } + if (entity.getMugType() == 0) + return BASE_TEXTURE0; + if (entity.getMugType() == 1) + return BASE_TEXTURE1; + if (entity.getMugType() == 2) + return BASE_TEXTURE2; + return BASE_TEXTURE3; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/OldApRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/OldApRenderer.java index c2c0edf5..7af2a9ba 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/OldApRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/OldApRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class OldApRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/old_ap_cube.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/old_ap_cube.png"); - public OldApRenderer(EntityRendererProvider.Context context) { - super(context, new OldApModel(Minecraft.getInstance().getEntityModels().bakeLayer(OldApModel.OLD_AP_CUBE_MAIN_LAYER)), 0.5f); - } + public OldApRenderer(EntityRendererProvider.Context context) { + super(context, new OldApModel(Minecraft.getInstance().getEntityModels().bakeLayer(OldApModel.OLD_AP_CUBE_MAIN_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(OldApCubeEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(OldApCubeEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1CompanionCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1CompanionCubeRenderer.java index 903d438b..403461cc 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1CompanionCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1CompanionCubeRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class Portal1CompanionCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/portal_1_companion_cube.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/portal_1_companion_cube.png"); - public Portal1CompanionCubeRenderer(EntityRendererProvider.Context context) { - super(context, new Portal1CompanionCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(Portal1CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); - } + public Portal1CompanionCubeRenderer(EntityRendererProvider.Context context) { + super(context, new Portal1CompanionCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(Portal1CompanionCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(Portal1CompanionCubeEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(Portal1CompanionCubeEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1StorageCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1StorageCubeRenderer.java index a5aa92cc..631a6cda 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1StorageCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/Portal1StorageCubeRenderer.java @@ -9,14 +9,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class Portal1StorageCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/portal_1_storage_cube.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/portal_1_storage_cube.png"); - public Portal1StorageCubeRenderer(EntityRendererProvider.Context context) { - super(context, new Portal1StorageCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(Portal1StorageCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); - } + public Portal1StorageCubeRenderer(EntityRendererProvider.Context context) { + super(context, new Portal1StorageCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(Portal1StorageCubeModel.COMPANION_CUBE_MAIN_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(Portal1StorageCubeEntity entity) { - return BASE_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(Portal1StorageCubeEntity entity) { + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/PortalRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/PortalRenderer.java index c8be2238..e1cb1179 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/PortalRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/PortalRenderer.java @@ -33,158 +33,158 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalRenderer extends EntityRenderer { - private static final ResourceLocation SQUARE_TEXTURE = id("textures/entity/portal_square_outline_closed.png"); - private static final ResourceLocation ROUND_TEXTURE = id("textures/entity/portal_oval_outline_closed.png"); - private static final ResourceLocation SQUARE_TEXTURE_TRACER = id("textures/entity/portal_tracer_square.png"); - private static final ResourceLocation ROUND_TEXTURE_TRACER = id("textures/entity/portal_tracer_oval.png"); - protected final PortalModel model = new PortalModel(Minecraft.getInstance().getEntityModels().bakeLayer(PortalModel.MAIN_LAYER)); - - public static PortalRenderPhase renderPhase = PortalRenderPhase.ENTITY; - - public PortalRenderer(EntityRendererProvider.Context dispatcher) { - super(dispatcher); - } - - @Override - public void render(@NotNull Portal entity, float yaw, float tickDelta, @NotNull PoseStack matrices, @NotNull MultiBufferSource vertexConsumers, int light) { - super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); - matrices.pushPose(); - Quaternionf rotation = entity.getRotation().get(tickDelta); - matrices.mulPose(rotation); - matrices.mulPose(Axis.YP.rotationDegrees(180)); - - int color = entity.getColor() * -1; - if (color == -16383998) { - color = 1908001; - } - if (color == 16383998) { - color = -1908001; - } - int r = (color & 0xFF0000) >> 16; - int g = (color & 0xFF00) >> 8; - int b = color & 0xFF; - - final float progress = (entity.tickCount + tickDelta) / 2.5f; - if (progress <= 1) { - matrices.scale(progress, progress, progress); - } - - renderPortal(matrices, vertexConsumers, entity, light, r, g, b, tickDelta); - - matrices.popPose(); - - if (PortalCubedConfig.crossPortalEntityRendering) { - renderOtherEntities(entity, matrices, tickDelta, vertexConsumers, light); - } - - if (Minecraft.getInstance().getEntityRenderDispatcher().shouldRenderHitBoxes() && !entity.isInvisible() && !Minecraft.getInstance().showOnlyReducedInfo()) { - renderAxes(entity, matrices, vertexConsumers.getBuffer(RenderType.lines())); - LevelRenderer.renderLineBox( - matrices, - vertexConsumers.getBuffer(RenderType.lines()), - GeneralUtil.capAABBAt( - entity.getOriginPos().subtract(2, 2, 2), - entity.getOriginPos().add(2, 2, 2), - entity.getFacingDirection(), - entity.getOriginPos() - ).move(-entity.getX(), -entity.getY(), -entity.getZ()), - 1f, 1f, 0f, 1f - ); - LevelRenderer.renderVoxelShape( - matrices, - vertexConsumers.getBuffer(RenderType.lines()), - entity.getCrossPortalCollisionShapeOther(entity), - -entity.getX(), -entity.getY(), -entity.getZ(), - 1f, 0.55f, 0f, 1f, - true - ); - } - } - - public void renderPortal( - PoseStack poseStack, - MultiBufferSource vertexConsumers, - Portal entity, - int light, - int r, - int g, - int b, - float tickDelta - ) { - final PortalRendererImpl renderer = PortalCubedClient.getRenderer(); - final boolean renderContents = renderPhase == renderer.targetPhase() && renderer.enabled(entity); - if (renderContents) { - renderer.preRender(entity, tickDelta, poseStack, vertexConsumers); - } - model.renderToBuffer(poseStack, vertexConsumers.getBuffer(RenderType.entityTranslucentEmissive(getTextureLocation(entity))), light, OverlayTexture.NO_OVERLAY, r, g, b, 1F); - if (renderContents) { - renderer.postRender(entity, tickDelta, poseStack, vertexConsumers); - } - } - - private void renderOtherEntities(Portal entity, PoseStack poseStack, float tickDelta, MultiBufferSource buffer, int packedLight) { - if (renderPhase != PortalRenderPhase.ENTITY || !entity.getActive()) return; - final UUID otherUuid = entity.getLinkedPortalUUID().orElse(null); - if (otherUuid == null || !(((LevelExt)entity.level()).getEntityByUuid(otherUuid) instanceof Portal otherPortal)) return; - final double oplx = Mth.lerp(tickDelta, otherPortal.xOld, otherPortal.getX()); - final double oply = Mth.lerp(tickDelta, otherPortal.yOld, otherPortal.getY()); - final double oplz = Mth.lerp(tickDelta, otherPortal.zOld, otherPortal.getZ()); - final List otherEntities = otherPortal.level().getEntities(otherPortal, otherPortal.getBoundingBox().deflate(0.01), e -> !e.isInvisible()); - final EntityRenderDispatcher dispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); - final boolean renderHitboxes = dispatcher.shouldRenderHitBoxes(); - dispatcher.setRenderHitBoxes(false); - for (final Entity otherEntity : otherEntities) { - if (otherEntity instanceof Portal) continue; - if (PortalCubedClient.cameraTransformedThroughPortal != null) { - final Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); - if (otherEntity == camera.getEntity() && !camera.isDetached()) continue; - } - poseStack.pushPose(); - poseStack.mulPose(otherPortal.getTransformQuat().toQuaternionf()); - poseStack.translate(0, Portal.SURFACE_OFFSET, 0); - dispatcher.render( - otherEntity, - Mth.lerp(tickDelta, otherEntity.xOld, otherEntity.getX()) - oplx, - Mth.lerp(tickDelta, otherEntity.yOld, otherEntity.getY()) - oply, - Mth.lerp(tickDelta, otherEntity.zOld, otherEntity.getZ()) - oplz, - Mth.lerp(tickDelta, otherEntity.yRotO, otherEntity.getYRot()), - tickDelta, poseStack, buffer, packedLight - ); - poseStack.popPose(); - } - dispatcher.setRenderHitBoxes(renderHitboxes); - } - - private void renderAxes(Portal entity, PoseStack matrices, VertexConsumer vertices) { - final PoseStack.Pose entry = matrices.last(); - renderAxis(entry, vertices, entity.getAxisW(), 1f, 0f, 0f); - renderAxis(entry, vertices, entity.getAxisH(), 1f, 0f, 0f); - renderAxis(entry, vertices, entity.getNormal(), 0f, 1f, 0f); - Quaternionf rotation = entity.getRotation().get(); - Vec3 rotationAxis = new Vec3(rotation.x, rotation.y, rotation.z).normalize(); - renderAxis(entry, vertices, rotationAxis, 0.5f, 0f, 0.5f); - } - - private void renderAxis(PoseStack.Pose entry, VertexConsumer vertices, Vec3 axis, float red, float green, float blue) { - vertices - .vertex(entry.pose(), 0, 0, 0) - .color(red, green, blue, 1f) - .normal(entry.normal(), (float)axis.x, (float)axis.y, (float)axis.z) - .endVertex(); - vertices - .vertex(entry.pose(), (float)axis.x, (float)axis.y, (float)axis.z) - .color(red, green, blue, 1f) - .normal(entry.normal(), (float)axis.x, (float)axis.y, (float)axis.z) - .endVertex(); - } - - @NotNull - @Override - public ResourceLocation getTextureLocation(@NotNull Portal entity) { - if (PortalCubedConfig.enableRoundPortals) { - return renderPhase == PortalRenderPhase.TRACER ? ROUND_TEXTURE_TRACER : ROUND_TEXTURE; - } else { - return renderPhase == PortalRenderPhase.TRACER ? SQUARE_TEXTURE_TRACER : SQUARE_TEXTURE; - } - } + private static final ResourceLocation SQUARE_TEXTURE = id("textures/entity/portal_square_outline_closed.png"); + private static final ResourceLocation ROUND_TEXTURE = id("textures/entity/portal_oval_outline_closed.png"); + private static final ResourceLocation SQUARE_TEXTURE_TRACER = id("textures/entity/portal_tracer_square.png"); + private static final ResourceLocation ROUND_TEXTURE_TRACER = id("textures/entity/portal_tracer_oval.png"); + protected final PortalModel model = new PortalModel(Minecraft.getInstance().getEntityModels().bakeLayer(PortalModel.MAIN_LAYER)); + + public static PortalRenderPhase renderPhase = PortalRenderPhase.ENTITY; + + public PortalRenderer(EntityRendererProvider.Context dispatcher) { + super(dispatcher); + } + + @Override + public void render(@NotNull Portal entity, float yaw, float tickDelta, @NotNull PoseStack matrices, @NotNull MultiBufferSource vertexConsumers, int light) { + super.render(entity, yaw, tickDelta, matrices, vertexConsumers, light); + matrices.pushPose(); + Quaternionf rotation = entity.getRotation().get(tickDelta); + matrices.mulPose(rotation); + matrices.mulPose(Axis.YP.rotationDegrees(180)); + + int color = entity.getColor() * -1; + if (color == -16383998) { + color = 1908001; + } + if (color == 16383998) { + color = -1908001; + } + int r = (color & 0xFF0000) >> 16; + int g = (color & 0xFF00) >> 8; + int b = color & 0xFF; + + final float progress = (entity.tickCount + tickDelta) / 2.5f; + if (progress <= 1) { + matrices.scale(progress, progress, progress); + } + + renderPortal(matrices, vertexConsumers, entity, light, r, g, b, tickDelta); + + matrices.popPose(); + + if (PortalCubedConfig.crossPortalEntityRendering) { + renderOtherEntities(entity, matrices, tickDelta, vertexConsumers, light); + } + + if (Minecraft.getInstance().getEntityRenderDispatcher().shouldRenderHitBoxes() && !entity.isInvisible() && !Minecraft.getInstance().showOnlyReducedInfo()) { + renderAxes(entity, matrices, vertexConsumers.getBuffer(RenderType.lines())); + LevelRenderer.renderLineBox( + matrices, + vertexConsumers.getBuffer(RenderType.lines()), + GeneralUtil.capAABBAt( + entity.getOriginPos().subtract(2, 2, 2), + entity.getOriginPos().add(2, 2, 2), + entity.getFacingDirection(), + entity.getOriginPos() + ).move(-entity.getX(), -entity.getY(), -entity.getZ()), + 1f, 1f, 0f, 1f + ); + LevelRenderer.renderVoxelShape( + matrices, + vertexConsumers.getBuffer(RenderType.lines()), + entity.getCrossPortalCollisionShapeOther(entity), + -entity.getX(), -entity.getY(), -entity.getZ(), + 1f, 0.55f, 0f, 1f, + true + ); + } + } + + public void renderPortal( + PoseStack poseStack, + MultiBufferSource vertexConsumers, + Portal entity, + int light, + int r, + int g, + int b, + float tickDelta + ) { + final PortalRendererImpl renderer = PortalCubedClient.getRenderer(); + final boolean renderContents = renderPhase == renderer.targetPhase() && renderer.enabled(entity); + if (renderContents) { + renderer.preRender(entity, tickDelta, poseStack, vertexConsumers); + } + model.renderToBuffer(poseStack, vertexConsumers.getBuffer(RenderType.entityTranslucentEmissive(getTextureLocation(entity))), light, OverlayTexture.NO_OVERLAY, r, g, b, 1F); + if (renderContents) { + renderer.postRender(entity, tickDelta, poseStack, vertexConsumers); + } + } + + private void renderOtherEntities(Portal entity, PoseStack poseStack, float tickDelta, MultiBufferSource buffer, int packedLight) { + if (renderPhase != PortalRenderPhase.ENTITY || !entity.getActive()) return; + final UUID otherUuid = entity.getLinkedPortalUUID().orElse(null); + if (otherUuid == null || !(((LevelExt)entity.level()).getEntityByUuid(otherUuid) instanceof Portal otherPortal)) return; + final double oplx = Mth.lerp(tickDelta, otherPortal.xOld, otherPortal.getX()); + final double oply = Mth.lerp(tickDelta, otherPortal.yOld, otherPortal.getY()); + final double oplz = Mth.lerp(tickDelta, otherPortal.zOld, otherPortal.getZ()); + final List otherEntities = otherPortal.level().getEntities(otherPortal, otherPortal.getBoundingBox().deflate(0.01), e -> !e.isInvisible()); + final EntityRenderDispatcher dispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); + final boolean renderHitboxes = dispatcher.shouldRenderHitBoxes(); + dispatcher.setRenderHitBoxes(false); + for (final Entity otherEntity : otherEntities) { + if (otherEntity instanceof Portal) continue; + if (PortalCubedClient.cameraTransformedThroughPortal != null) { + final Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); + if (otherEntity == camera.getEntity() && !camera.isDetached()) continue; + } + poseStack.pushPose(); + poseStack.mulPose(otherPortal.getTransformQuat().toQuaternionf()); + poseStack.translate(0, Portal.SURFACE_OFFSET, 0); + dispatcher.render( + otherEntity, + Mth.lerp(tickDelta, otherEntity.xOld, otherEntity.getX()) - oplx, + Mth.lerp(tickDelta, otherEntity.yOld, otherEntity.getY()) - oply, + Mth.lerp(tickDelta, otherEntity.zOld, otherEntity.getZ()) - oplz, + Mth.lerp(tickDelta, otherEntity.yRotO, otherEntity.getYRot()), + tickDelta, poseStack, buffer, packedLight + ); + poseStack.popPose(); + } + dispatcher.setRenderHitBoxes(renderHitboxes); + } + + private void renderAxes(Portal entity, PoseStack matrices, VertexConsumer vertices) { + final PoseStack.Pose entry = matrices.last(); + renderAxis(entry, vertices, entity.getAxisW(), 1f, 0f, 0f); + renderAxis(entry, vertices, entity.getAxisH(), 1f, 0f, 0f); + renderAxis(entry, vertices, entity.getNormal(), 0f, 1f, 0f); + Quaternionf rotation = entity.getRotation().get(); + Vec3 rotationAxis = new Vec3(rotation.x, rotation.y, rotation.z).normalize(); + renderAxis(entry, vertices, rotationAxis, 0.5f, 0f, 0.5f); + } + + private void renderAxis(PoseStack.Pose entry, VertexConsumer vertices, Vec3 axis, float red, float green, float blue) { + vertices + .vertex(entry.pose(), 0, 0, 0) + .color(red, green, blue, 1f) + .normal(entry.normal(), (float)axis.x, (float)axis.y, (float)axis.z) + .endVertex(); + vertices + .vertex(entry.pose(), (float)axis.x, (float)axis.y, (float)axis.z) + .color(red, green, blue, 1f) + .normal(entry.normal(), (float)axis.x, (float)axis.y, (float)axis.z) + .endVertex(); + } + + @NotNull + @Override + public ResourceLocation getTextureLocation(@NotNull Portal entity) { + if (PortalCubedConfig.enableRoundPortals) { + return renderPhase == PortalRenderPhase.TRACER ? ROUND_TEXTURE_TRACER : ROUND_TEXTURE; + } else { + return renderPhase == PortalRenderPhase.TRACER ? SQUARE_TEXTURE_TRACER : SQUARE_TEXTURE; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RadioRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RadioRenderer.java index 268812f1..a362f492 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RadioRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RadioRenderer.java @@ -9,16 +9,16 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RadioRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/radio.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/radio_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/radio.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/radio_e.png"); - public RadioRenderer(EntityRendererProvider.Context context) { - super(context, new RadioModel(context.bakeLayer(RadioModel.RADIO_MAIN_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public RadioRenderer(EntityRendererProvider.Context context) { + super(context, new RadioModel(context.bakeLayer(RadioModel.RADIO_MAIN_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(RadioEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(RadioEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RedirectionCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RedirectionCubeRenderer.java index 3da98e93..eaa62ab1 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RedirectionCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RedirectionCubeRenderer.java @@ -10,19 +10,19 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RedirectionCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/redirection_cube.png"); - private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/redirection_cube_lit.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/redirection_cube.png"); + private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/redirection_cube_lit.png"); - public RedirectionCubeRenderer(EntityRendererProvider.Context context) { - super(context, new RedirectionCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(RedirectionCubeModel.REDIRECTION_CUBE_MAIN_LAYER)), 0.5f); - } + public RedirectionCubeRenderer(EntityRendererProvider.Context context) { + super(context, new RedirectionCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(RedirectionCubeModel.REDIRECTION_CUBE_MAIN_LAYER)), 0.5f); + } - @NotNull - @Override - public ResourceLocation getTextureLocation(RedirectionCubeEntity entity) { - if (entity.isActive()) { - return ACTIVE_TEXTURE; - } - return BASE_TEXTURE; - } + @NotNull + @Override + public ResourceLocation getTextureLocation(RedirectionCubeEntity entity) { + if (entity.isActive()) { + return ACTIVE_TEXTURE; + } + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RocketRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RocketRenderer.java index 1c94273c..0ab9e8ad 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/RocketRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/RocketRenderer.java @@ -19,45 +19,45 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RocketRenderer extends EntityRenderer { - public static final ModelLayerLocation ROCKET_LAYER = new ModelLayerLocation(id("rocket"), "main"); + public static final ModelLayerLocation ROCKET_LAYER = new ModelLayerLocation(id("rocket"), "main"); - private final RocketModel model; + private final RocketModel model; - public RocketRenderer(EntityRendererProvider.Context ctx) { - super(ctx); - model = new RocketModel(ctx.bakeLayer(ROCKET_LAYER)); - } + public RocketRenderer(EntityRendererProvider.Context ctx) { + super(ctx); + model = new RocketModel(ctx.bakeLayer(ROCKET_LAYER)); + } - @Override - public void render(RocketEntity entity, float yaw2, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { - super.render(entity, yaw2, tickDelta, matrices, vertexConsumers, light); + @Override + public void render(RocketEntity entity, float yaw2, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light) { + super.render(entity, yaw2, tickDelta, matrices, vertexConsumers, light); - matrices.pushPose(); + matrices.pushPose(); - final float yaw = Mth.rotLerp(tickDelta, entity.yRotO, entity.getYRot()); - final float pitch = Mth.rotLerp(tickDelta, entity.xRotO, entity.getXRot()); + final float yaw = Mth.rotLerp(tickDelta, entity.yRotO, entity.getYRot()); + final float pitch = Mth.rotLerp(tickDelta, entity.xRotO, entity.getXRot()); - matrices.mulPose(Axis.XP.rotationDegrees(-pitch)); - matrices.mulPose(Axis.YP.rotationDegrees(180 - yaw)); - matrices.scale(-1, -1, 1); - matrices.translate(0.0, -1.501, 0.0); + matrices.mulPose(Axis.XP.rotationDegrees(-pitch)); + matrices.mulPose(Axis.YP.rotationDegrees(180 - yaw)); + matrices.scale(-1, -1, 1); + matrices.translate(0.0, -1.501, 0.0); - model.prepareMobModel(entity, 0, 0, tickDelta); - model.setupAnim(entity, 0, 0, entity.tickCount + tickDelta, yaw, pitch); + model.prepareMobModel(entity, 0, 0, tickDelta); + model.setupAnim(entity, 0, 0, entity.tickCount + tickDelta, yaw, pitch); - final RenderType renderLayer = model.renderType(getTextureLocation(entity)); - if (renderLayer != null) { - final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(renderLayer); - final int overlay2 = OverlayTexture.pack(OverlayTexture.u(0), OverlayTexture.v(false)); - model.renderToBuffer(matrices, vertexConsumer, light, overlay2, 1, 1, 1, 1); - } + final RenderType renderLayer = model.renderType(getTextureLocation(entity)); + if (renderLayer != null) { + final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(renderLayer); + final int overlay2 = OverlayTexture.pack(OverlayTexture.u(0), OverlayTexture.v(false)); + model.renderToBuffer(matrices, vertexConsumer, light, overlay2, 1, 1, 1, 1); + } - matrices.popPose(); - } + matrices.popPose(); + } - @NotNull - @Override - public ResourceLocation getTextureLocation(RocketEntity entity) { - return RocketTurretModel.TEXTURE_ACTIVE; - } + @NotNull + @Override + public ResourceLocation getTextureLocation(RocketEntity entity) { + return RocketTurretModel.TEXTURE_ACTIVE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/SchrodingerCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/SchrodingerCubeRenderer.java index 22bc389d..d3de1742 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/SchrodingerCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/SchrodingerCubeRenderer.java @@ -10,19 +10,19 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class SchrodingerCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation BASE_TEXTURE = id("textures/entity/schrodinger_cube.png"); - private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/schrodinger_cube_lit.png"); + private static final ResourceLocation BASE_TEXTURE = id("textures/entity/schrodinger_cube.png"); + private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/schrodinger_cube_lit.png"); - public SchrodingerCubeRenderer(EntityRendererProvider.Context context) { - super(context, new SchrodingerCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(SchrodingerCubeModel.SCHRODINGER_CUBE_MAIN_LAYER)), 0.5f); - } + public SchrodingerCubeRenderer(EntityRendererProvider.Context context) { + super(context, new SchrodingerCubeModel(Minecraft.getInstance().getEntityModels().bakeLayer(SchrodingerCubeModel.SCHRODINGER_CUBE_MAIN_LAYER)), 0.5f); + } - @NotNull - @Override - public ResourceLocation getTextureLocation(SchrodingerCubeEntity entity) { - if (entity.isActive()) { - return ACTIVE_TEXTURE; - } - return BASE_TEXTURE; - } + @NotNull + @Override + public ResourceLocation getTextureLocation(SchrodingerCubeEntity entity) { + if (entity.isActive()) { + return ACTIVE_TEXTURE; + } + return BASE_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/SpaceCoreRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/SpaceCoreRenderer.java index ac4f4936..535f8140 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/SpaceCoreRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/SpaceCoreRenderer.java @@ -11,17 +11,17 @@ public class SpaceCoreRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); + private static final ResourceLocation TEXTURE = id("textures/entity/portal_2_cores.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/portal_2_cores_e.png"); - public SpaceCoreRenderer(EntityRendererProvider.Context context) { - super(context, new SpaceCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(SpaceCoreModel.SPACE_CORE_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); - } + public SpaceCoreRenderer(EntityRendererProvider.Context context) { + super(context, new SpaceCoreModel(Minecraft.getInstance().getEntityModels().bakeLayer(SpaceCoreModel.SPACE_CORE_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> EMISSIVE_TEXTURE)); + } - @Override - public ResourceLocation getTextureLocation(SpaceCoreEntity entity) { - return TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(SpaceCoreEntity entity) { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/StorageCubeRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/StorageCubeRenderer.java index 18861aa6..b9133848 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/StorageCubeRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/StorageCubeRenderer.java @@ -10,30 +10,30 @@ public class StorageCubeRenderer extends CorePhysicsRenderer { - private static final ResourceLocation TEXTURE = id("textures/entity/storage_cube.png"); - private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/storage_cube_e.png"); - - private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/storage_cube_lit.png"); - private static final ResourceLocation EMISSIVE_ACTIVE_TEXTURE = id("textures/entity/storage_cube_lit_e.png"); - - public StorageCubeRenderer(EntityRendererProvider.Context context) { - super(context, new StorageCubeModel(context.bakeLayer(StorageCubeModel.STORAGE_CUBE_MAIN_LAYER)), 0.5f); - this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> { - if (entity.isOnButton()) { - return EMISSIVE_ACTIVE_TEXTURE; - } - - return EMISSIVE_TEXTURE; - })); - } - - @Override - public ResourceLocation getTextureLocation(StorageCubeEntity entity) { - if (entity.isOnButton()) { - return ACTIVE_TEXTURE; - } - - return TEXTURE; - } + private static final ResourceLocation TEXTURE = id("textures/entity/storage_cube.png"); + private static final ResourceLocation EMISSIVE_TEXTURE = id("textures/entity/storage_cube_e.png"); + + private static final ResourceLocation ACTIVE_TEXTURE = id("textures/entity/storage_cube_lit.png"); + private static final ResourceLocation EMISSIVE_ACTIVE_TEXTURE = id("textures/entity/storage_cube_lit_e.png"); + + public StorageCubeRenderer(EntityRendererProvider.Context context) { + super(context, new StorageCubeModel(context.bakeLayer(StorageCubeModel.STORAGE_CUBE_MAIN_LAYER)), 0.5f); + this.addLayer(EntityEmissiveRendering.featureRenderer(this, entity -> { + if (entity.isOnButton()) { + return EMISSIVE_ACTIVE_TEXTURE; + } + + return EMISSIVE_TEXTURE; + })); + } + + @Override + public ResourceLocation getTextureLocation(StorageCubeEntity entity) { + if (entity.isOnButton()) { + return ACTIVE_TEXTURE; + } + + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/TurretRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/TurretRenderer.java index 451f1a69..5295caea 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/TurretRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/TurretRenderer.java @@ -10,14 +10,14 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class TurretRenderer extends CorePhysicsRenderer { - public static final ModelLayerLocation TURRET_LAYER = new ModelLayerLocation(id("turret"), "main"); + public static final ModelLayerLocation TURRET_LAYER = new ModelLayerLocation(id("turret"), "main"); - public TurretRenderer(EntityRendererProvider.Context context) { - super(context, new TurretModel(Minecraft.getInstance().getEntityModels().bakeLayer(TurretModel.TURRET_MAIN_LAYER)), 0.5f); - } + public TurretRenderer(EntityRendererProvider.Context context) { + super(context, new TurretModel(Minecraft.getInstance().getEntityModels().bakeLayer(TurretModel.TURRET_MAIN_LAYER)), 0.5f); + } - @Override - public ResourceLocation getTextureLocation(TurretEntity entity) { - return TurretModel.DEFAULT_TEXTURE; - } + @Override + public ResourceLocation getTextureLocation(TurretEntity entity) { + return TurretModel.DEFAULT_TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedEntityTextures.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedEntityTextures.java index a15dddc2..ed4534a1 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedEntityTextures.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedEntityTextures.java @@ -18,35 +18,35 @@ public class AnimatedEntityTextures { - public static void init() { - ResourceLoader loader = ResourceLoader.get(PackType.CLIENT_RESOURCES); - loader.registerReloader(Reloader.INSTANCE); - loader.addReloaderOrdering(Client.TEXTURES, Reloader.ID); - } - - private static class Reloader extends SimplePreparableReloadListener> implements IdentifiableResourceReloader { - public static final ResourceLocation ID = PortalCubed.id("animated_entity_textures"); - public static final FileToIdConverter LISTER = new FileToIdConverter("textures/animated_entity", ".png"); - public static final Reloader INSTANCE = new Reloader(); - - @Override - @NotNull - protected Set prepare(ResourceManager manager, ProfilerFiller profiler) { - return LISTER.listMatchingResources(manager).keySet(); - } - - @Override - protected void apply(Set textures, ResourceManager manager, ProfilerFiller profiler) { - TextureManager textureManager = Minecraft.getInstance().getTextureManager(); - for (ResourceLocation texture : textures) { - textureManager.register(texture, new AnimatedTexture(texture)); - } - } - - @Override - @NotNull - public ResourceLocation getQuiltId() { - return ID; - } - } + public static void init() { + ResourceLoader loader = ResourceLoader.get(PackType.CLIENT_RESOURCES); + loader.registerReloader(Reloader.INSTANCE); + loader.addReloaderOrdering(Client.TEXTURES, Reloader.ID); + } + + private static class Reloader extends SimplePreparableReloadListener> implements IdentifiableResourceReloader { + public static final ResourceLocation ID = PortalCubed.id("animated_entity_textures"); + public static final FileToIdConverter LISTER = new FileToIdConverter("textures/animated_entity", ".png"); + public static final Reloader INSTANCE = new Reloader(); + + @Override + @NotNull + protected Set prepare(ResourceManager manager, ProfilerFiller profiler) { + return LISTER.listMatchingResources(manager).keySet(); + } + + @Override + protected void apply(Set textures, ResourceManager manager, ProfilerFiller profiler) { + TextureManager textureManager = Minecraft.getInstance().getTextureManager(); + for (ResourceLocation texture : textures) { + textureManager.register(texture, new AnimatedTexture(texture)); + } + } + + @Override + @NotNull + public ResourceLocation getQuiltId() { + return ID; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedTexture.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedTexture.java index 1408ae22..057a038b 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedTexture.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/animatedtextures/AnimatedTexture.java @@ -13,49 +13,49 @@ import java.io.IOException; public class AnimatedTexture extends AbstractTexture implements Tickable { - public final ResourceLocation texture; - - private SpriteContents contents; - private SpriteTicker ticker; - - public AnimatedTexture(ResourceLocation texture) { - this.texture = texture; - } - - @Override - public void load(ResourceManager manager) throws IOException { - Resource resource = manager.getResourceOrThrow(texture); - this.contents = SpriteLoader.loadSprite(texture, resource); - if (contents instanceof SpriteContentsAccessor access) { // != null - NativeImage image = access.getOriginalImage(); - if (RenderSystem.isOnRenderThreadOrInit()) { - init(image); - } else { - RenderSystem.recordRenderCall(() -> init(image)); - } - this.ticker = contents.createTicker(); - } - } - - private void init(NativeImage image) { - TextureUtil.prepareImage(this.getId(), 0, image.getWidth(), image.getHeight()); - contents.uploadFirstFrame(0, 0); - } - - @Override - public void tick() { - if (ticker != null) { - if (RenderSystem.isOnRenderThread()) { - cycle(); - } else { - RenderSystem.recordRenderCall(this::cycle); - } - } - } - - private void cycle() { - SodiumIntegration.INSTANCE.markSpriteActive(contents); - bind(); - ticker.tickAndUpload(0, 0); - } + public final ResourceLocation texture; + + private SpriteContents contents; + private SpriteTicker ticker; + + public AnimatedTexture(ResourceLocation texture) { + this.texture = texture; + } + + @Override + public void load(ResourceManager manager) throws IOException { + Resource resource = manager.getResourceOrThrow(texture); + this.contents = SpriteLoader.loadSprite(texture, resource); + if (contents instanceof SpriteContentsAccessor access) { // != null + NativeImage image = access.getOriginalImage(); + if (RenderSystem.isOnRenderThreadOrInit()) { + init(image); + } else { + RenderSystem.recordRenderCall(() -> init(image)); + } + this.ticker = contents.createTicker(); + } + } + + private void init(NativeImage image) { + TextureUtil.prepareImage(this.getId(), 0, image.getWidth(), image.getHeight()); + contents.uploadFirstFrame(0, 0); + } + + @Override + public void tick() { + if (ticker != null) { + if (RenderSystem.isOnRenderThread()) { + cycle(); + } else { + RenderSystem.recordRenderCall(this::cycle); + } + } + } + + private void cycle() { + SodiumIntegration.INSTANCE.markSpriteActive(contents); + bind(); + ticker.tickAndUpload(0, 0); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AdventureCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AdventureCoreModel.java index 69654fdd..47bc0f51 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AdventureCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AdventureCoreModel.java @@ -15,39 +15,39 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class AdventureCoreModel extends FizzleableModel { - public static final ModelLayerLocation ADVENTURE_CORE_LAYER = new ModelLayerLocation(id("adventure_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation ADVENTURE_CORE_LAYER = new ModelLayerLocation(id("adventure_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public AdventureCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public AdventureCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 3).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 3).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AngerCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AngerCoreModel.java index 3a385726..12b34bc7 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AngerCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/AngerCoreModel.java @@ -15,39 +15,39 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class AngerCoreModel extends FizzleableModel { - public static final ModelLayerLocation ANGER_CORE_LAYER = new ModelLayerLocation(id("anger_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation ANGER_CORE_LAYER = new ModelLayerLocation(id("anger_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public AngerCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public AngerCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(11, 26).addBox(-2.4F, -3.0F, 3.0F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, 5.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(11, 26).addBox(-2.4F, -3.0F, 3.0F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, 5.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(11, 26).addBox(-2.5F, -3.0F, 3.25F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(11, 26).addBox(-2.5F, -3.0F, 3.25F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(24, 3).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(24, 3).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/BeansModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/BeansModel.java index 4006af32..927c308f 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/BeansModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/BeansModel.java @@ -15,30 +15,30 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BeansModel extends FizzleableModel { - public static final ModelLayerLocation BEANS_LAYER = new ModelLayerLocation(id("beans"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation BEANS_LAYER = new ModelLayerLocation(id("beans"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public BeansModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public BeansModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-2.0F, -6.0F, -2.0F, 4.0F, 6.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-2.0F, -6.0F, -2.0F, 4.0F, 6.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 10).addBox(-2.0F, 0.0785F, -2.049F, 4.0F, 0.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -7.5305F, -0.7087F, -1.6581F, 0.0F, 0.0F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 10).addBox(-2.0F, 0.0785F, -2.049F, 4.0F, 0.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -7.5305F, -0.7087F, -1.6581F, 0.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(10, 0).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 0.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.0F, -2.0F, -2.2253F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(10, 0).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 0.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.0F, -2.0F, -2.2253F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CakeCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CakeCoreModel.java index a3b0691c..d675c6eb 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CakeCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CakeCoreModel.java @@ -15,39 +15,39 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class CakeCoreModel extends FizzleableModel { - public static final ModelLayerLocation CAKE_CORE_LAYER = new ModelLayerLocation(id("cake_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation CAKE_CORE_LAYER = new ModelLayerLocation(id("cake_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public CakeCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public CakeCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(19, 26).addBox(-2.4F, -3.0F, 3.0F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, 5.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(19, 26).addBox(-2.4F, -3.0F, 3.0F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, 5.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(19, 26).addBox(-2.5F, -3.0F, 3.25F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(19, 26).addBox(-2.5F, -3.0F, 3.25F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(24, 9).addBox(-1.5F, -1.5F, 0.35F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(24, 9).addBox(-1.5F, -1.5F, 0.35F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ChairModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ChairModel.java index 8029b169..a942d473 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ChairModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ChairModel.java @@ -15,38 +15,38 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class ChairModel extends FizzleableModel { - public static final ModelLayerLocation CHAIR_LAYER = new ModelLayerLocation(id("chair"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bone; + public static final ModelLayerLocation CHAIR_LAYER = new ModelLayerLocation(id("chair"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bone; - public ChairModel(ModelPart root) { - this.bone = root.getChild("bone"); - } + public ChairModel(ModelPart root) { + this.bone = root.getChild("bone"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition meshdefinition = new MeshDefinition(); - PartDefinition partdefinition = meshdefinition.getRoot(); + public static LayerDefinition getTexturedModelData() { + MeshDefinition meshdefinition = new MeshDefinition(); + PartDefinition partdefinition = meshdefinition.getRoot(); - PartDefinition bone = partdefinition.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-3.5263F, -2.9444F, -4.1769F, 7.0F, 1.0F, 7.0F, new CubeDeformation(0.0F)) - .texOffs(21, 0).addBox(-3.5263F, -10.9444F, 1.8231F, 7.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(21, 8).addBox(-1.0263F, -6.9444F, 2.8231F, 2.0F, 4.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(-0.0417F, 19.4444F, 0.6517F)); + PartDefinition bone = partdefinition.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-3.5263F, -2.9444F, -4.1769F, 7.0F, 1.0F, 7.0F, new CubeDeformation(0.0F)) + .texOffs(21, 0).addBox(-3.5263F, -10.9444F, 1.8231F, 7.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(21, 8).addBox(-1.0263F, -6.9444F, 2.8231F, 2.0F, 4.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(-0.0417F, 19.4444F, 0.6517F)); - PartDefinition cube_r1 = bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -2.0F, -1.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.7512F, 4.5556F, -0.7449F, 0.0F, -0.7854F, 0.0F)); + PartDefinition cube_r1 = bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -2.0F, -1.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.7512F, 4.5556F, -0.7449F, 0.0F, -0.7854F, 0.0F)); - PartDefinition cube_r2 = bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -2.0F, 0.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.7512F, 4.5556F, -0.7449F, 0.0F, 0.7854F, 0.0F)); + PartDefinition cube_r2 = bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -2.0F, 0.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.7512F, 4.5556F, -0.7449F, 0.0F, 0.7854F, 0.0F)); - PartDefinition cube_r3 = bone.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(3.0F, -2.0F, -1.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(0, 9).addBox(-5.0F, -6.5F, -0.5F, 9.0F, 6.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.7488F, 4.5556F, -0.7449F, 0.0F, 0.7854F, 0.0F)); + PartDefinition cube_r3 = bone.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(3.0F, -2.0F, -1.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(0, 9).addBox(-5.0F, -6.5F, -0.5F, 9.0F, 6.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.7488F, 4.5556F, -0.7449F, 0.0F, 0.7854F, 0.0F)); - PartDefinition cube_r4 = bone.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 9).addBox(-5.0F, -7.0F, 0.5F, 9.0F, 6.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(0, 0).addBox(3.0F, -2.5F, 0.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.7488F, 5.0556F, -0.7449F, 0.0F, -0.7854F, 0.0F)); + PartDefinition cube_r4 = bone.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 9).addBox(-5.0F, -7.0F, 0.5F, 9.0F, 6.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(0, 0).addBox(3.0F, -2.5F, 0.0F, 2.0F, 2.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.7488F, 5.0556F, -0.7449F, 0.0F, -0.7854F, 0.0F)); - return LayerDefinition.create(meshdefinition, 64, 64); - } + return LayerDefinition.create(meshdefinition, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bone.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + bone.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CompanionCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CompanionCubeModel.java index e2405ced..beb4c359 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CompanionCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CompanionCubeModel.java @@ -16,39 +16,39 @@ public class CompanionCubeModel extends FizzleableModel { - public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("companion_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("companion_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public CompanionCubeModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public CompanionCubeModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, -2.3562F, 0.0436F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, -2.3562F, 0.0436F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.7854F, 0.0F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.7854F, 0.0F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, -0.7854F, 0.0F, 0.0F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, -0.7854F, 0.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.0F, 1.5708F, 0.7854F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.0F, 1.5708F, 0.7854F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 2.3562F, 0.0436F, -3.1416F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 2.3562F, 0.0436F, -3.1416F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.0F, -1.5708F, -0.7854F)); - return LayerDefinition.create(modelData, 64, 64); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 0).addBox(-5.25F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -5.0F, 0.0F, 0.0F, -1.5708F, -0.7854F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ComputerModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ComputerModel.java index 83dd27b0..32f6754a 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ComputerModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ComputerModel.java @@ -15,25 +15,25 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class ComputerModel extends FizzleableModel { - public static final ModelLayerLocation COMPUTER_LAYER = new ModelLayerLocation(id("computer"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; - - public ComputerModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.0F, -3.0F, -4.0F, 8.0F, 3.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } - - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + public static final ModelLayerLocation COMPUTER_LAYER = new ModelLayerLocation(id("computer"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; + + public ComputerModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.0F, -3.0F, -4.0F, 8.0F, 3.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } + + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CoreFrameModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CoreFrameModel.java index 0f99d4e1..2066f919 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CoreFrameModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CoreFrameModel.java @@ -15,31 +15,31 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class CoreFrameModel extends FizzleableModel { - public static final ModelLayerLocation CORE_FRAME_LAYER = new ModelLayerLocation(id("core_frame"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation CORE_FRAME_LAYER = new ModelLayerLocation(id("core_frame"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public CoreFrameModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public CoreFrameModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CuriosityCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CuriosityCoreModel.java index cd604290..746ede9f 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CuriosityCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/CuriosityCoreModel.java @@ -15,38 +15,38 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class CuriosityCoreModel extends FizzleableModel { - public static final ModelLayerLocation CURIOSITY_CORE_LAYER = new ModelLayerLocation(id("curiosity_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation CURIOSITY_CORE_LAYER = new ModelLayerLocation(id("curiosity_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public CuriosityCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public CuriosityCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(7, 26).addBox(4.0159F, -2.5F, -1.816F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(7, 26).addBox(-1.741F, -2.5F, 4.0909F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(7, 26).addBox(4.0159F, -2.5F, -1.816F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(7, 26).addBox(-1.741F, -2.5F, 4.0909F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(24, 0).addBox(-1.5F, -1.5579F, -0.4437F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(24, 0).addBox(-1.5F, -1.5579F, -0.4437F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ExcursionFunnelModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ExcursionFunnelModel.java index 4dd6b226..33510216 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ExcursionFunnelModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/ExcursionFunnelModel.java @@ -19,47 +19,47 @@ import java.util.Set; public class ExcursionFunnelModel extends Model { - public static final Set VISIBLE_MIDDLE = Set.of(Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST); - public static final Set VISIBLE_END = Set.of(Direction.values()); - public static final ResourceLocation TEXTURE = PortalCubed.id("textures/animated_entity/excursion_funnel_beam_forward.png"); - public static final ResourceLocation REVERSED_TEXTURE = PortalCubed.id("textures/animated_entity/excursion_funnel_beam_reversed.png"); - private ModelPart part; + public static final Set VISIBLE_MIDDLE = Set.of(Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST); + public static final Set VISIBLE_END = Set.of(Direction.values()); + public static final ResourceLocation TEXTURE = PortalCubed.id("textures/animated_entity/excursion_funnel_beam_forward.png"); + public static final ResourceLocation REVERSED_TEXTURE = PortalCubed.id("textures/animated_entity/excursion_funnel_beam_reversed.png"); + private ModelPart part; - public ExcursionFunnelModel(ExcursionFunnelEntity entity) { - super(RenderType::entityTranslucent); - entity.modelUpdater = this::rebuildGeometry; - this.rebuildGeometry(entity); - } + public ExcursionFunnelModel(ExcursionFunnelEntity entity) { + super(RenderType::entityTranslucent); + entity.modelUpdater = this::rebuildGeometry; + this.rebuildGeometry(entity); + } - public void rebuildGeometry(EmittedEntity entity) { - MeshDefinition mesh = new MeshDefinition(); - PartDefinition root = mesh.getRoot(); - // this hurts my soul, but I don't know if improving it is possible - float length = entity.getLength(); - float tinyOffset = (entity.getId() % 20) / 10_000f; // avoids Z fighting when crossing - for (int block = 0; block < length; block++) { - float sectionLength = Math.min(length - block, 1); - boolean last = block + 1 >= length; - if (last) sectionLength -= 0.001; // avoid z fighting at end - root.addOrReplaceChild( - "cube_" + block, - CubeListBuilder.create() - .texOffs(0, 0) - .addBox( - -15 + tinyOffset, block * 16 + tinyOffset, -15 + tinyOffset, - 30, sectionLength * 16, 30, - last ? VISIBLE_END : VISIBLE_MIDDLE - ), - PartPose.ZERO - ); - } + public void rebuildGeometry(EmittedEntity entity) { + MeshDefinition mesh = new MeshDefinition(); + PartDefinition root = mesh.getRoot(); + // this hurts my soul, but I don't know if improving it is possible + float length = entity.getLength(); + float tinyOffset = (entity.getId() % 20) / 10_000f; // avoids Z fighting when crossing + for (int block = 0; block < length; block++) { + float sectionLength = Math.min(length - block, 1); + boolean last = block + 1 >= length; + if (last) sectionLength -= 0.001; // avoid z fighting at end + root.addOrReplaceChild( + "cube_" + block, + CubeListBuilder.create() + .texOffs(0, 0) + .addBox( + -15 + tinyOffset, block * 16 + tinyOffset, -15 + tinyOffset, + 30, sectionLength * 16, 30, + last ? VISIBLE_END : VISIBLE_MIDDLE + ), + PartPose.ZERO + ); + } - this.part = LayerDefinition.create(mesh, 120, 1472).bakeRoot(); - } + this.part = LayerDefinition.create(mesh, 120, 1472).bakeRoot(); + } - @Override - public void renderToBuffer(PoseStack poseStack, VertexConsumer buffer, int packedLight, - int packedOverlay, float red, float green, float blue, float alpha) { - this.part.render(poseStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + @Override + public void renderToBuffer(PoseStack poseStack, VertexConsumer buffer, int packedLight, + int packedOverlay, float red, float green, float blue, float alpha) { + this.part.render(poseStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FactCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FactCoreModel.java index 70751c7b..dc45a910 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FactCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FactCoreModel.java @@ -15,39 +15,39 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class FactCoreModel extends FizzleableModel { - public static final ModelLayerLocation FACT_CORE_LAYER = new ModelLayerLocation(id("fact_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation FACT_CORE_LAYER = new ModelLayerLocation(id("fact_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public FactCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public FactCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FizzleableModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FizzleableModel.java index f56f3dba..85b4c798 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FizzleableModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/FizzleableModel.java @@ -11,25 +11,25 @@ import java.util.function.Function; public abstract class FizzleableModel extends EntityModel { - private float fizzleProgress; + private float fizzleProgress; - public FizzleableModel() { - super(); - } + public FizzleableModel() { + super(); + } - public FizzleableModel(Function function) { - super(function); - } + public FizzleableModel(Function function) { + super(function); + } - @Override - public void setupAnim(T entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { - fizzleProgress = 1f - Math.min(entity.getFizzleProgress(), 1f); - } + @Override + public void setupAnim(T entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { + fizzleProgress = 1f - Math.min(entity.getFizzleProgress(), 1f); + } - @Override - public final void renderToBuffer(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) { - renderFizzled(matrices, vertices, light, overlay, red * fizzleProgress, green * fizzleProgress, blue * fizzleProgress, alpha); - } + @Override + public final void renderToBuffer(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) { + renderFizzled(matrices, vertices, light, overlay, red * fizzleProgress, green * fizzleProgress, blue * fizzleProgress, alpha); + } - public abstract void renderFizzled(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha); + public abstract void renderFizzled(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha); } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/HoopyModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/HoopyModel.java index c4f6b436..9457007e 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/HoopyModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/HoopyModel.java @@ -15,26 +15,26 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class HoopyModel extends FizzleableModel { - public static final ModelLayerLocation HOOPY_LAYER = new ModelLayerLocation(id("hoopy"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; - - public HoopyModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-13.0F, -1.0F, -13.0F, 26.0F, 1.0F, 26.0F, new CubeDeformation(0.0F)) - .texOffs(0, 27).addBox(-12.0F, -1.0F, -12.0F, 24.0F, 1.0F, 24.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 128, 128); - } - - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + public static final ModelLayerLocation HOOPY_LAYER = new ModelLayerLocation(id("hoopy"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; + + public HoopyModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-13.0F, -1.0F, -13.0F, 26.0F, 1.0F, 26.0F, new CubeDeformation(0.0F)) + .texOffs(0, 27).addBox(-12.0F, -1.0F, -12.0F, 24.0F, 1.0F, 24.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 128, 128); + } + + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/JugModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/JugModel.java index 4ea44a0a..4f40ab28 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/JugModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/JugModel.java @@ -15,27 +15,27 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class JugModel extends FizzleableModel { - public static final ModelLayerLocation JUG_LAYER = new ModelLayerLocation(id("jug"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation JUG_LAYER = new ModelLayerLocation(id("jug"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public JugModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public JugModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-3.0F, -1.75F, -3.0F, 6.0F, 8.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 17.75F, 0.0F, 0.0F, 3.1416F, 0.0F)); + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-3.0F, -1.75F, -3.0F, 6.0F, 8.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 17.75F, 0.0F, 0.0F, 3.1416F, 0.0F)); - bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 14).addBox(-1.0F, -0.5F, -1.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.25F, 0.0F, 0.0F, -0.7854F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 14).addBox(-1.0F, -0.5F, -1.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.25F, 0.0F, 0.0F, -0.7854F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/LilPineappleModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/LilPineappleModel.java index f1984368..dbdd5156 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/LilPineappleModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/LilPineappleModel.java @@ -15,32 +15,32 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class LilPineappleModel extends FizzleableModel { - public static final ModelLayerLocation LIL_PINEAPPLE = new ModelLayerLocation(id("lil_pineapple"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation LIL_PINEAPPLE = new ModelLayerLocation(id("lil_pineapple"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public LilPineappleModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public LilPineappleModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("bb_main_r1", CubeListBuilder.create().texOffs(0, 17).addBox(-4.0F, -8.0F, -5.0F, 8.0F, 7.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -3.1416F, 0.0F, 3.1416F)); + bb_main.addOrReplaceChild("bb_main_r1", CubeListBuilder.create().texOffs(0, 17).addBox(-4.0F, -8.0F, -5.0F, 8.0F, 7.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -3.1416F, 0.0F, 3.1416F)); - PartDefinition bd = bb_main.addOrReplaceChild("bd", CubeListBuilder.create().texOffs(0, 0).addBox(-9.0F, -8.5F, -7.0F, 9.0F, 8.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(4.5F, 0.5F, 2.5F)); + PartDefinition bd = bb_main.addOrReplaceChild("bd", CubeListBuilder.create().texOffs(0, 0).addBox(-9.0F, -8.5F, -7.0F, 9.0F, 8.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(4.5F, 0.5F, 2.5F)); - bd.addOrReplaceChild("bd_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-0.5F, -1.5F, -0.5F, 1.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-4.3F, -9.8F, -2.5F, 0.0F, 0.0F, -0.0873F)); - return LayerDefinition.create(modelData, 64, 64); - } + bd.addOrReplaceChild("bd_r1", CubeListBuilder.create().texOffs(0, 0).addBox(-0.5F, -1.5F, -0.5F, 1.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-4.3F, -9.8F, -2.5F, 0.0F, 0.0F, -0.0873F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MoralityCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MoralityCoreModel.java index 962482b9..5fd32e7d 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MoralityCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MoralityCoreModel.java @@ -15,38 +15,38 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class MoralityCoreModel extends FizzleableModel { - public static final ModelLayerLocation MORTALITY_CORE_LAYER = new ModelLayerLocation(id("mortality_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation MORTALITY_CORE_LAYER = new ModelLayerLocation(id("mortality_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public MoralityCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public MoralityCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(15, 26).addBox(4.0159F, -2.5F, -1.816F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)) - .texOffs(15, 26).addBox(-1.741F, -2.5F, 4.0909F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(15, 26).addBox(4.0159F, -2.5F, -1.816F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)) + .texOffs(15, 26).addBox(-1.741F, -2.5F, 4.0909F, 1.0F, 5.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -2.9421F, 2.3687F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(24, 6).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.175F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, -3.1416F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 21).addBox(0.0F, -3.5F, -1.5F, 0.0F, 7.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MugModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MugModel.java index 9f70ab8f..879359bd 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MugModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/MugModel.java @@ -15,28 +15,28 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class MugModel extends FizzleableModel { - public static final ModelLayerLocation MUG_LAYER = new ModelLayerLocation(id("mug"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation MUG_LAYER = new ModelLayerLocation(id("mug"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public MugModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public MugModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-3.0F, -2.0F, -1.25F, 3.0F, 4.0F, 3.0F, new CubeDeformation(0.01F)) - .texOffs(2, 2).mirror().addBox(1.5F, 2.0F, 0.25F, -3.0F, -4.0F, -3.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 22.0F, -0.25F, 0.0F, 3.1416F, 0.0F)); + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-3.0F, -2.0F, -1.25F, 3.0F, 4.0F, 3.0F, new CubeDeformation(0.01F)) + .texOffs(2, 2).mirror().addBox(1.5F, 2.0F, 0.25F, -3.0F, -4.0F, -3.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 22.0F, -0.25F, 0.0F, 3.1416F, 0.0F)); - bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 7).addBox(0.5F, -1.5F, 0.0F, 1.0F, 3.0F, 2.0F, new CubeDeformation(0.01F)), PartPose.offsetAndRotation(0.0F, 0.0F, 1.25F, 0.0F, 1.5708F, 0.0F)); - return LayerDefinition.create(modelData, 16, 16); - } + bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 7).addBox(0.5F, -1.5F, 0.0F, 1.0F, 3.0F, 2.0F, new CubeDeformation(0.01F)), PartPose.offsetAndRotation(0.0F, 0.0F, 1.25F, 0.0F, 1.5708F, 0.0F)); + return LayerDefinition.create(modelData, 16, 16); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/OldApModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/OldApModel.java index 93b3088d..80396f1f 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/OldApModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/OldApModel.java @@ -15,26 +15,26 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class OldApModel extends FizzleableModel { - public static final ModelLayerLocation OLD_AP_CUBE_MAIN_LAYER = new ModelLayerLocation(id("old_ap_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; - - public OldApModel(ModelPart root) { - this.bb_main = root.getChild("bone"); - } - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.3F)), PartPose.offset(0.5F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } - - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + public static final ModelLayerLocation OLD_AP_CUBE_MAIN_LAYER = new ModelLayerLocation(id("old_ap_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; + + public OldApModel(ModelPart root) { + this.bb_main = root.getChild("bone"); + } + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.3F)), PartPose.offset(0.5F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } + + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1CompanionCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1CompanionCubeModel.java index 07570c4c..a288b6b9 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1CompanionCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1CompanionCubeModel.java @@ -15,38 +15,38 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class Portal1CompanionCubeModel extends FizzleableModel { - public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("portal_1_companion_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("portal_1_companion_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public Portal1CompanionCubeModel(ModelPart root) { - this.bb_main = root.getChild("bone"); - } + public Portal1CompanionCubeModel(ModelPart root) { + this.bb_main = root.getChild("bone"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.5F, 24.0F, 0.0F)); + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.5F, 24.0F, 0.0F)); - bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 2.3562F, 0.0F, -3.1416F)); + bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 2.3562F, 0.0F, -3.1416F)); - bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, -0.7854F, 0.0F, 0.0F)); + bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, -0.7854F, 0.0F, 0.0F)); - bone.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -4.9929F, 0.0F, -2.3562F, 0.0F, -1.5708F)); + bone.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -4.9929F, 0.0F, -2.3562F, 0.0F, -1.5708F)); - bone.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -4.9929F, 0.0F, -2.3562F, 0.0F, 1.5708F)); + bone.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -4.9929F, 0.0F, -2.3562F, 0.0F, 1.5708F)); - bone.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 0.0F, -1.5708F, -0.7854F)); + bone.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 2).addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 0.0F, -1.5708F, -0.7854F)); - bone.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 0.0F, 1.5708F, 0.7854F)); - return LayerDefinition.create(modelData, 64, 64); - } + bone.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 2).mirror().addBox(5.25F, -2.0F, -2.0F, 0.0F, 4.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(-0.5F, -5.2929F, 0.0F, 0.0F, 1.5708F, 0.7854F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1StorageCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1StorageCubeModel.java index d668ddcb..4a3c0112 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1StorageCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/Portal1StorageCubeModel.java @@ -15,26 +15,26 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class Portal1StorageCubeModel extends FizzleableModel { - public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("portal_1_storage_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; - - public Portal1StorageCubeModel(ModelPart root) { - this.bb_main = root.getChild("bone"); - } - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.5F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } - - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + public static final ModelLayerLocation COMPANION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("portal_1_storage_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; + + public Portal1StorageCubeModel(ModelPart root) { + this.bb_main = root.getChild("bone"); + } + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + modelPartData.addOrReplaceChild("bone", CubeListBuilder.create().texOffs(0, 0).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-5.5F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.5F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } + + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/PortalModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/PortalModel.java index b07661eb..2d7ca18a 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/PortalModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/PortalModel.java @@ -16,36 +16,36 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalModel extends EntityModel { - public static final ModelLayerLocation MAIN_LAYER = new ModelLayerLocation(id("portal"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation MAIN_LAYER = new ModelLayerLocation(id("portal"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public PortalModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public PortalModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - public static MeshDefinition getModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); + public static MeshDefinition getModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -40.0F, -0.0F, 16.0F, 32.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 0.0F, 0.0F)); - return modelData; - } + modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -40.0F, -0.0F, 16.0F, 32.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 0.0F, 0.0F)); + return modelData; + } - public static LayerDefinition getTexturedModelData() { - return LayerDefinition.create(getModelData(), 32, 32); - } + public static LayerDefinition getTexturedModelData() { + return LayerDefinition.create(getModelData(), 32, 32); + } - @Override - public void setupAnim(Portal entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { - //previously the render function, render code was moved to a method below - } + @Override + public void setupAnim(Portal entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { + //previously the render function, render code was moved to a method below + } - @Override - public void renderToBuffer(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderToBuffer(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RadioModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RadioModel.java index 3bfe50dc..adc8a606 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RadioModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RadioModel.java @@ -15,30 +15,30 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RadioModel extends FizzleableModel { - public static final ModelLayerLocation RADIO_MAIN_LAYER = new ModelLayerLocation(id("radio"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation RADIO_MAIN_LAYER = new ModelLayerLocation(id("radio"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public RadioModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public RadioModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 4).mirror().addBox(-12.0F, -1.0F, 6.0F, 8.0F, 1.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(0, 13).mirror().addBox(-11.5F, -5.0F, 6.5F, 7.0F, 4.0F, 3.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offset(8.0F, 24.0F, -8.0F)); + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 4).mirror().addBox(-12.0F, -1.0F, 6.0F, 8.0F, 1.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(0, 13).mirror().addBox(-11.5F, -5.0F, 6.5F, 7.0F, 4.0F, 3.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offset(8.0F, 24.0F, -8.0F)); - bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(0.0F, -2.0F, -0.5F, 0.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-6.5F, -7.0F, 8.0F, 0.0F, 0.7854F, 0.0F)); + bone.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 0).addBox(0.0F, -2.0F, -0.5F, 0.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-6.5F, -7.0F, 8.0F, 0.0F, 0.7854F, 0.0F)); - bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(0.0F, -2.0F, -0.5F, 0.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-6.5F, -7.0F, 8.0F, 0.0F, -0.7854F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bone.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(0, 0).addBox(0.0F, -2.0F, -0.5F, 0.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-6.5F, -7.0F, 8.0F, 0.0F, -0.7854F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RedirectionCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RedirectionCubeModel.java index 7e7ff21a..e3f4d0f6 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RedirectionCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RedirectionCubeModel.java @@ -16,36 +16,36 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class RedirectionCubeModel extends FizzleableModel { - public static final ModelLayerLocation REDIRECTION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("redirection_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation REDIRECTION_CUBE_MAIN_LAYER = new ModelLayerLocation(id("redirection_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public RedirectionCubeModel(ModelPart root) { - super(RenderType::entityTranslucent); - this.bb_main = root.getChild("bb_main"); - } + public RedirectionCubeModel(ModelPart root) { + super(RenderType::entityTranslucent); + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.99F, -9.99F, -5.01F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-4.95F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.4F)) - .texOffs(0, 40).addBox(-3.0F, -8.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.99F, -9.99F, -5.01F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-4.95F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.4F)) + .texOffs(0, 40).addBox(-3.0F, -8.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.7854F, 0.0F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.7854F, 0.0F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, -0.7854F, 0.0F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, -0.7854F, 0.0F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, 0.8727F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, 0.8727F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RocketModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RocketModel.java index 5cd4124c..f1e77fd0 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RocketModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/RocketModel.java @@ -8,31 +8,31 @@ import net.minecraft.client.model.geom.builders.*; public class RocketModel extends FizzleableModel { - private final ModelPart bone; + private final ModelPart bone; - public RocketModel(ModelPart root) { - this.bone = root.getChild("bone"); - } + public RocketModel(ModelPart root) { + this.bone = root.getChild("bone"); + } - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 23.0F, 0.0F, 0.0F, 3.1416F, 0.0F)); + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bone = modelPartData.addOrReplaceChild("bone", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 23.0F, 0.0F, 0.0F, 3.1416F, 0.0F)); - bone.addOrReplaceChild( - "cube_r1", CubeListBuilder.create().texOffs(44, 51).addBox(0.0F, -1.5F, -5.0F, 0.0F, 3.0F, 10.0F, - new CubeDeformation(0.0F) - ), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.7854F)); + bone.addOrReplaceChild( + "cube_r1", CubeListBuilder.create().texOffs(44, 51).addBox(0.0F, -1.5F, -5.0F, 0.0F, 3.0F, 10.0F, + new CubeDeformation(0.0F) + ), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.7854F)); - bone.addOrReplaceChild( - "cube_r2", CubeListBuilder.create().texOffs(44, 51).mirror().addBox(0.0F, -1.5F, -5.0F, 0.0F, 3.0F, 10.0F, - new CubeDeformation(0.0F) - ).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, -0.7854F)); - return LayerDefinition.create(modelData, 64, 64); - } + bone.addOrReplaceChild( + "cube_r2", CubeListBuilder.create().texOffs(44, 51).mirror().addBox(0.0F, -1.5F, -5.0F, 0.0F, 3.0F, 10.0F, + new CubeDeformation(0.0F) + ).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, -0.7854F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrices, VertexConsumer vertexConsumer, int light, int overlay, float red, float green, float blue, float alpha) { - bone.render(matrices, vertexConsumer, light, overlay, red, green, blue, alpha); - } + @Override + public void renderFizzled(PoseStack matrices, VertexConsumer vertexConsumer, int light, int overlay, float red, float green, float blue, float alpha) { + bone.render(matrices, vertexConsumer, light, overlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SchrodingerCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SchrodingerCubeModel.java index 4247cb53..2aebafc7 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SchrodingerCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SchrodingerCubeModel.java @@ -16,36 +16,36 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class SchrodingerCubeModel extends FizzleableModel { - public static final ModelLayerLocation SCHRODINGER_CUBE_MAIN_LAYER = new ModelLayerLocation(id("schrodinger_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation SCHRODINGER_CUBE_MAIN_LAYER = new ModelLayerLocation(id("schrodinger_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public SchrodingerCubeModel(ModelPart root) { - super(RenderType::entityTranslucent); - this.bb_main = root.getChild("bb_main"); - } + public SchrodingerCubeModel(ModelPart root) { + super(RenderType::entityTranslucent); + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.99F, -9.99F, -5.01F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-4.95F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.4F)) - .texOffs(0, 40).addBox(-3.0F, -8.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-4.99F, -9.99F, -5.01F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-4.95F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.4F)) + .texOffs(0, 40).addBox(-3.0F, -8.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.7854F, 0.0F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.7854F, 0.0F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, -0.7854F, 0.0F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, -0.7854F, 0.0F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, 0.8727F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(47, 0).addBox(0.0F, -2.5F, -2.5F, 0.0F, 5.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -4.5F, 0.0F, 0.0F, 0.8727F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SpaceCoreModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SpaceCoreModel.java index fc3b7873..7b0b6437 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SpaceCoreModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/SpaceCoreModel.java @@ -15,39 +15,39 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class SpaceCoreModel extends FizzleableModel { - public static final ModelLayerLocation SPACE_CORE_LAYER = new ModelLayerLocation(id("space_core"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; + public static final ModelLayerLocation SPACE_CORE_LAYER = new ModelLayerLocation(id("space_core"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; - public SpaceCoreModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } + public SpaceCoreModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition bb_main = modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.182F, 3.8536F, 3.1416F, 0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -1.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); + bb_main.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(7, 27).addBox(-2.5F, -2.5F, 3.25F, 1.0F, 4.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.5F, -3.0F, 3.5F, 0.0F, -0.7854F, 1.5708F)); - bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 9).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); + bb_main.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(24, 9).addBox(-1.5F, -1.5F, 0.5F, 3.0F, 3.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 3.425F, 0.0F, 3.1416F, 0.0F)); - bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); + bb_main.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(0, 22).addBox(0.0F, -3.0F, -1.5F, 0.0F, 6.0F, 3.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -6.182F, 3.8536F, -3.1416F, 0.7854F, -1.5708F)); - bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) - .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); - return LayerDefinition.create(modelData, 32, 32); - } + bb_main.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(0, 12).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.2F)) + .texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, -3.0F, 0.0F, 3.1416F, 0.0F, 0.0F)); + return LayerDefinition.create(modelData, 32, 32); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/StorageCubeModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/StorageCubeModel.java index b4ea989f..c389f73e 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/StorageCubeModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/StorageCubeModel.java @@ -16,26 +16,26 @@ public class StorageCubeModel extends FizzleableModel { - public static final ModelLayerLocation STORAGE_CUBE_MAIN_LAYER = new ModelLayerLocation(id("storage_cube"), "main"); - @SuppressWarnings("checkstyle:MemberName") - private final ModelPart bb_main; - - public StorageCubeModel(ModelPart root) { - this.bb_main = root.getChild("bb_main"); - } - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) - .texOffs(0, 20).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.0F, 24.0F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } - - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - - bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - } + public static final ModelLayerLocation STORAGE_CUBE_MAIN_LAYER = new ModelLayerLocation(id("storage_cube"), "main"); + @SuppressWarnings("checkstyle:MemberName") + private final ModelPart bb_main; + + public StorageCubeModel(ModelPart root) { + this.bb_main = root.getChild("bb_main"); + } + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + modelPartData.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.0F)) + .texOffs(0, 20).addBox(-5.0F, -10.0F, -5.0F, 10.0F, 10.0F, 10.0F, new CubeDeformation(0.5F)), PartPose.offset(0.0F, 24.0F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } + + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + + bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/TurretModel.java b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/TurretModel.java index f501f59b..b09bb0e6 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/TurretModel.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/entity/model/TurretModel.java @@ -17,100 +17,100 @@ import static com.fusionflux.portalcubed.entity.TurretEntity.MODEL_SCALE; public class TurretModel extends FizzleableModel { - public static final ModelLayerLocation TURRET_MAIN_LAYER = new ModelLayerLocation(id("turret"), "main"); + public static final ModelLayerLocation TURRET_MAIN_LAYER = new ModelLayerLocation(id("turret"), "main"); - public static final ResourceLocation DEFAULT_TEXTURE = id("textures/entity/default_turret.png"); + public static final ResourceLocation DEFAULT_TEXTURE = id("textures/entity/default_turret.png"); - private final ModelPart turret; + private final ModelPart turret; - public TurretModel(ModelPart root) { - this.turret = root.getChild("turret"); - } + public TurretModel(ModelPart root) { + this.turret = root.getChild("turret"); + } - @SuppressWarnings("checkstyle:LocalVariableName") - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - PartDefinition turret = modelPartData.addOrReplaceChild("turret", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); + @SuppressWarnings("checkstyle:LocalVariableName") + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + PartDefinition turret = modelPartData.addOrReplaceChild("turret", CubeListBuilder.create(), PartPose.offset(0.0F, 24.0F, 0.0F)); - PartDefinition body = turret.addOrReplaceChild("body", CubeListBuilder.create(), PartPose.offset(0.0F, 2.0F, 0.0F)); + PartDefinition body = turret.addOrReplaceChild("body", CubeListBuilder.create(), PartPose.offset(0.0F, 2.0F, 0.0F)); - PartDefinition center = body.addOrReplaceChild("center", CubeListBuilder.create().texOffs(0, 0).addBox(-2.75F, -9.875F, -4.5F, 6.0F, 16.0F, 8.0F, new CubeDeformation(0.02F)) - .texOffs(29, 41).addBox(-2.75F, -2.375F, -0.525F, 6.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(0, 42).addBox(-1.75F, -7.85F, -4.5F, 4.0F, 14.0F, 8.0F, new CubeDeformation(0.0F)) - .texOffs(-6, 0).addBox(-2.75F, -7.925F, -4.5F, 6.0F, 0.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(-0.25F, -16.125F, 0.5F)); + PartDefinition center = body.addOrReplaceChild("center", CubeListBuilder.create().texOffs(0, 0).addBox(-2.75F, -9.875F, -4.5F, 6.0F, 16.0F, 8.0F, new CubeDeformation(0.02F)) + .texOffs(29, 41).addBox(-2.75F, -2.375F, -0.525F, 6.0F, 1.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(0, 42).addBox(-1.75F, -7.85F, -4.5F, 4.0F, 14.0F, 8.0F, new CubeDeformation(0.0F)) + .texOffs(-6, 0).addBox(-2.75F, -7.925F, -4.5F, 6.0F, 0.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(-0.25F, -16.125F, 0.5F)); - PartDefinition antenna = center.addOrReplaceChild("antenna", CubeListBuilder.create(), PartPose.offset(-0.9F, -6.125F, 1.5F)); + PartDefinition antenna = center.addOrReplaceChild("antenna", CubeListBuilder.create(), PartPose.offset(-0.9F, -6.125F, 1.5F)); - antenna.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(28, 0).addBox(0.0F, -3.55F, -2.5F, 0.0F, 9.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -1.1781F, 0.0F)); + antenna.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(28, 0).addBox(0.0F, -3.55F, -2.5F, 0.0F, 9.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, -1.1781F, 0.0F)); - PartDefinition crown = center.addOrReplaceChild("crown", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F)); + PartDefinition crown = center.addOrReplaceChild("crown", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F)); - crown.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(37, 42).mirror().addBox(-2.5F, -2.5F, -3.5F, 7.0F, 5.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(37, 42).addBox(-2.5F, -2.5F, 3.5F, 7.0F, 5.0F, 0.0F, new CubeDeformation(0.0F)) - .texOffs(37, 35).mirror().addBox(4.5F, -2.5F, -3.5F, 0.0F, 5.0F, 7.0F, new CubeDeformation(0.0F)).mirror(false) - .texOffs(37, 35).mirror().addBox(-2.5F, -2.5F, -3.5F, 0.0F, 5.0F, 7.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.5F, -12.5F, -0.5F, -0.0289F, -0.2163F, 0.134F)); + crown.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(37, 42).mirror().addBox(-2.5F, -2.5F, -3.5F, 7.0F, 5.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(37, 42).addBox(-2.5F, -2.5F, 3.5F, 7.0F, 5.0F, 0.0F, new CubeDeformation(0.0F)) + .texOffs(37, 35).mirror().addBox(4.5F, -2.5F, -3.5F, 0.0F, 5.0F, 7.0F, new CubeDeformation(0.0F)).mirror(false) + .texOffs(37, 35).mirror().addBox(-2.5F, -2.5F, -3.5F, 0.0F, 5.0F, 7.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.5F, -12.5F, -0.5F, -0.0289F, -0.2163F, 0.134F)); - PartDefinition eye = center.addOrReplaceChild("eye", CubeListBuilder.create(), PartPose.offsetAndRotation(0.25F, -0.875F, -4.425F, 0.0F, 0.0F, -0.7854F)); + PartDefinition eye = center.addOrReplaceChild("eye", CubeListBuilder.create(), PartPose.offsetAndRotation(0.25F, -0.875F, -4.425F, 0.0F, 0.0F, -0.7854F)); - eye.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(22, 0).addBox(-1.5177F, -1.5177F, 0.0F, 3.0F, 3.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.025F, 0.0F, 0.0F, -1.5708F)); + eye.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(22, 0).addBox(-1.5177F, -1.5177F, 0.0F, 3.0F, 3.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.025F, 0.0F, 0.0F, -1.5708F)); - PartDefinition left_hatch = body.addOrReplaceChild("left_hatch", CubeListBuilder.create().texOffs(29, 42).mirror().addBox(-3.405F, -1.93F, -0.1362F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offset(1.365F, -16.585F, 0.1213F)); + PartDefinition left_hatch = body.addOrReplaceChild("left_hatch", CubeListBuilder.create().texOffs(29, 42).mirror().addBox(-3.405F, -1.93F, -0.1362F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offset(1.365F, -16.585F, 0.1213F)); - PartDefinition left_pivot = left_hatch.addOrReplaceChild("left_pivot", CubeListBuilder.create().texOffs(44, 40).mirror().addBox(2.3333F, -7.75F, -4.1667F, 2.0F, 16.0F, 8.0F, new CubeDeformation(0.01F)).mirror(false) - .texOffs(48, 12).mirror().addBox(0.0333F, -3.5F, -2.1667F, 3.0F, 6.0F, 5.0F, new CubeDeformation(0.01F)).mirror(false) - .texOffs(24, 40).mirror().addBox(4.1333F, -7.75F, -4.1667F, 0.0F, 16.0F, 8.0F, new CubeDeformation(-0.01F)).mirror(false), PartPose.offset(-2.6983F, 0.31F, 0.0454F)); + PartDefinition left_pivot = left_hatch.addOrReplaceChild("left_pivot", CubeListBuilder.create().texOffs(44, 40).mirror().addBox(2.3333F, -7.75F, -4.1667F, 2.0F, 16.0F, 8.0F, new CubeDeformation(0.01F)).mirror(false) + .texOffs(48, 12).mirror().addBox(0.0333F, -3.5F, -2.1667F, 3.0F, 6.0F, 5.0F, new CubeDeformation(0.01F)).mirror(false) + .texOffs(24, 40).mirror().addBox(4.1333F, -7.75F, -4.1667F, 0.0F, 16.0F, 8.0F, new CubeDeformation(-0.01F)).mirror(false), PartPose.offset(-2.6983F, 0.31F, 0.0454F)); - PartDefinition left_barrels = left_pivot.addOrReplaceChild("left_barrels", CubeListBuilder.create().texOffs(58, 23).mirror().addBox(-0.75F, -1.5F, -1.0F, 1.0F, 2.0F, 2.0F, new CubeDeformation(0.01F)).mirror(false) - .texOffs(58, 23).mirror().addBox(-0.75F, 1.5F, -1.0F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.01F)).mirror(false), PartPose.offset(1.7833F, -1.0F, -2.9167F)); + PartDefinition left_barrels = left_pivot.addOrReplaceChild("left_barrels", CubeListBuilder.create().texOffs(58, 23).mirror().addBox(-0.75F, -1.5F, -1.0F, 1.0F, 2.0F, 2.0F, new CubeDeformation(0.01F)).mirror(false) + .texOffs(58, 23).mirror().addBox(-0.75F, 1.5F, -1.0F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.01F)).mirror(false), PartPose.offset(1.7833F, -1.0F, -2.9167F)); - PartDefinition top_left_flash = left_barrels.addOrReplaceChild("top_left_flash", CubeListBuilder.create(), PartPose.offset(-0.25F, -0.5F, 5.0F)); + PartDefinition top_left_flash = left_barrels.addOrReplaceChild("top_left_flash", CubeListBuilder.create(), PartPose.offset(-0.25F, -0.5F, 5.0F)); - top_left_flash.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(22, -1).addBox(-0.075F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, 0.7854F)); + top_left_flash.addOrReplaceChild("cube_r4", CubeListBuilder.create().texOffs(22, -1).addBox(-0.075F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, 0.7854F)); - top_left_flash.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(22, -1).addBox(-0.075F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, -0.7854F)); + top_left_flash.addOrReplaceChild("cube_r5", CubeListBuilder.create().texOffs(22, -1).addBox(-0.075F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, -0.7854F)); - PartDefinition bottom_left_flash = left_barrels.addOrReplaceChild("bottom_left_flash", CubeListBuilder.create(), PartPose.offset(-0.325F, 2.0F, 5.0F)); + PartDefinition bottom_left_flash = left_barrels.addOrReplaceChild("bottom_left_flash", CubeListBuilder.create(), PartPose.offset(-0.325F, 2.0F, 5.0F)); - bottom_left_flash.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(22, -1).addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, 0.7854F)); + bottom_left_flash.addOrReplaceChild("cube_r6", CubeListBuilder.create().texOffs(22, -1).addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, 0.7854F)); - bottom_left_flash.addOrReplaceChild("cube_r7", CubeListBuilder.create().texOffs(22, -1).addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, -0.7854F)); + bottom_left_flash.addOrReplaceChild("cube_r7", CubeListBuilder.create().texOffs(22, -1).addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, -0.7854F)); - PartDefinition right_hatch = body.addOrReplaceChild("right_hatch", CubeListBuilder.create().texOffs(29, 42).addBox(-1.595F, -1.93F, -0.1362F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(-1.365F, -16.585F, 0.1213F)); + PartDefinition right_hatch = body.addOrReplaceChild("right_hatch", CubeListBuilder.create().texOffs(29, 42).addBox(-1.595F, -1.93F, -0.1362F, 5.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(-1.365F, -16.585F, 0.1213F)); - PartDefinition right_pivot = right_hatch.addOrReplaceChild("right_pivot", CubeListBuilder.create().texOffs(48, 12).addBox(-3.0333F, -3.5F, -2.1667F, 3.0F, 6.0F, 5.0F, new CubeDeformation(0.01F)) - .texOffs(24, 40).addBox(-4.1333F, -7.75F, -4.1667F, 0.0F, 16.0F, 8.0F, new CubeDeformation(-0.01F)) - .texOffs(20, 16).addBox(-4.3333F, -7.75F, -4.1667F, 2.0F, 16.0F, 8.0F, new CubeDeformation(0.01F)), PartPose.offset(2.6983F, 0.31F, 0.0454F)); + PartDefinition right_pivot = right_hatch.addOrReplaceChild("right_pivot", CubeListBuilder.create().texOffs(48, 12).addBox(-3.0333F, -3.5F, -2.1667F, 3.0F, 6.0F, 5.0F, new CubeDeformation(0.01F)) + .texOffs(24, 40).addBox(-4.1333F, -7.75F, -4.1667F, 0.0F, 16.0F, 8.0F, new CubeDeformation(-0.01F)) + .texOffs(20, 16).addBox(-4.3333F, -7.75F, -4.1667F, 2.0F, 16.0F, 8.0F, new CubeDeformation(0.01F)), PartPose.offset(2.6983F, 0.31F, 0.0454F)); - PartDefinition right_barrels = right_pivot.addOrReplaceChild("right_barrels", CubeListBuilder.create().texOffs(58, 23).addBox(-0.25F, -1.5F, -1.0F, 1.0F, 2.0F, 2.0F, new CubeDeformation(0.01F)) - .texOffs(58, 23).addBox(-0.25F, 1.5F, -1.0F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.01F)), PartPose.offset(-1.7833F, -1.0F, -2.9167F)); + PartDefinition right_barrels = right_pivot.addOrReplaceChild("right_barrels", CubeListBuilder.create().texOffs(58, 23).addBox(-0.25F, -1.5F, -1.0F, 1.0F, 2.0F, 2.0F, new CubeDeformation(0.01F)) + .texOffs(58, 23).addBox(-0.25F, 1.5F, -1.0F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.01F)), PartPose.offset(-1.7833F, -1.0F, -2.9167F)); - PartDefinition bottom_right_flash = right_barrels.addOrReplaceChild("bottom_right_flash", CubeListBuilder.create(), PartPose.offset(0.25F, 2.0F, 5.0F)); + PartDefinition bottom_right_flash = right_barrels.addOrReplaceChild("bottom_right_flash", CubeListBuilder.create(), PartPose.offset(0.25F, 2.0F, 5.0F)); - bottom_right_flash.addOrReplaceChild("cube_r8", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, -0.7854F)); + bottom_right_flash.addOrReplaceChild("cube_r8", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, -0.7854F)); - bottom_right_flash.addOrReplaceChild("cube_r9", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, 0.7854F)); + bottom_right_flash.addOrReplaceChild("cube_r9", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, 0.7854F)); - PartDefinition top_right_flash = right_barrels.addOrReplaceChild("top_right_flash", CubeListBuilder.create(), PartPose.offset(0.25F, -0.5F, 5.0F)); + PartDefinition top_right_flash = right_barrels.addOrReplaceChild("top_right_flash", CubeListBuilder.create(), PartPose.offset(0.25F, -0.5F, 5.0F)); - top_right_flash.addOrReplaceChild("cube_r10", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, -0.7854F)); + top_right_flash.addOrReplaceChild("cube_r10", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -2.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -1.5F, 0.0F, 0.0F, -0.7854F)); - top_right_flash.addOrReplaceChild("cube_r11", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, 0.7854F)); + top_right_flash.addOrReplaceChild("cube_r11", CubeListBuilder.create().texOffs(22, -1).mirror().addBox(0.0F, -1.5F, -3.5F, 0.0F, 3.0F, 4.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.0F, 0.0F, -0.5F, 0.0F, 0.0F, 0.7854F)); - PartDefinition legs = turret.addOrReplaceChild("legs", CubeListBuilder.create().texOffs(0, 15).addBox(0.0F, -7.6667F, 0.7663F, 0.0F, 14.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, -6.3333F, 0.7337F)); + PartDefinition legs = turret.addOrReplaceChild("legs", CubeListBuilder.create().texOffs(0, 15).addBox(0.0F, -7.6667F, 0.7663F, 0.0F, 14.0F, 9.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, -6.3333F, 0.7337F)); - legs.addOrReplaceChild("cube_r12", CubeListBuilder.create().texOffs(42, -11).addBox(0.0F, -11.0F, 0.0F, 0.0F, 9.0F, 11.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.25F, 8.3333F, -0.4837F, 0.0F, -2.7227F, 0.0F)); + legs.addOrReplaceChild("cube_r12", CubeListBuilder.create().texOffs(42, -11).addBox(0.0F, -11.0F, 0.0F, 0.0F, 9.0F, 11.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.25F, 8.3333F, -0.4837F, 0.0F, -2.7227F, 0.0F)); - legs.addOrReplaceChild("cube_r13", CubeListBuilder.create().texOffs(42, -11).mirror().addBox(0.0F, -11.0F, 0.0F, 0.0F, 9.0F, 11.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.25F, 8.3333F, -0.4837F, 0.0F, 2.7227F, 0.0F)); - return LayerDefinition.create(modelData, 64, 64); - } + legs.addOrReplaceChild("cube_r13", CubeListBuilder.create().texOffs(42, -11).mirror().addBox(0.0F, -11.0F, 0.0F, 0.0F, 9.0F, 11.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(0.25F, 8.3333F, -0.4837F, 0.0F, 2.7227F, 0.0F)); + return LayerDefinition.create(modelData, 64, 64); + } - @Override - public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { - matrixStack.pushPose(); - matrixStack.translate(0, 24 / 16f * (1 - MODEL_SCALE), 0); - matrixStack.scale(MODEL_SCALE, MODEL_SCALE, MODEL_SCALE); - turret.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); - matrixStack.popPose(); - } + @Override + public void renderFizzled(PoseStack matrixStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { + matrixStack.pushPose(); + matrixStack.translate(0, 24 / 16f * (1 - MODEL_SCALE), 0); + matrixStack.scale(MODEL_SCALE, MODEL_SCALE, MODEL_SCALE); + turret.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha); + matrixStack.popPose(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/DisabledRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/DisabledRenderer.java index ad7dcc4c..b61b0b10 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/DisabledRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/DisabledRenderer.java @@ -5,21 +5,21 @@ import net.minecraft.client.renderer.MultiBufferSource; public class DisabledRenderer extends PortalRendererImpl { - @Override - public boolean enabled(Portal portal) { - return false; - } + @Override + public boolean enabled(Portal portal) { + return false; + } - @Override - public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - } + @Override + public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + } - @Override - public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - } + @Override + public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + } - @Override - public PortalRenderPhase targetPhase() { - return PortalRenderPhase.ENTITY; - } + @Override + public PortalRenderPhase targetPhase() { + return PortalRenderPhase.ENTITY; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/FramebufferRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/FramebufferRenderer.java index 781c6908..02d3440c 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/FramebufferRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/FramebufferRenderer.java @@ -18,75 +18,75 @@ import static org.lwjgl.opengl.GL11.*; public class FramebufferRenderer extends PortalRendererImpl { - private static final Queue FREE_TARGETS = new ArrayDeque<>(); - - private final PortalRendererImpl stencilRenderer = new StencilRenderer(); - private int portalLayer = 0; - - private static RenderTarget getRenderTarget(int width, int height) { - final RenderTarget target = FREE_TARGETS.poll(); - if (target == null) { - return new TextureTarget(width, height, true, Minecraft.ON_OSX); - } - if (target.width != width || target.height != height) { - target.resize(width, height, Minecraft.ON_OSX); - } - return target; - } - - private static void freeRenderTarget(RenderTarget target) { - if (!FREE_TARGETS.offer(target)) { - target.destroyBuffers(); - } - } - - @Override - public boolean enabled(Portal portal) { - return portalLayer < MAX_PORTAL_LAYER && portal.getActive(); - } - - @Override - public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - stencilRenderer.preRender(portal, tickDelta, poseStack, bufferSource); - } - - @Override - public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - ((MultiBufferSource.BufferSource)bufferSource).endBatch(); - RenderSystem.colorMask(true, true, true, true); - RenderSystem.depthMask(true); - RenderSystem.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - RenderSystem.stencilFunc(GL_ALWAYS, 0, 0xff); - glDisable(GL_STENCIL_TEST); - - final Minecraft minecraft = Minecraft.getInstance(); - final RenderTarget oldTarget = minecraft.getMainRenderTarget(); - final RenderTarget newTarget = getRenderTarget(oldTarget.width, oldTarget.height); - - ((MinecraftAccessor)minecraft).setMainRenderTarget(newTarget); - newTarget.bindWrite(true); - - GlStateManager._clearColor(1, 0, 1, 1); - GlStateManager._clearDepth(1); - GlStateManager._clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, Minecraft.ON_OSX); - - portalLayer++; - renderWorld(portal, tickDelta); - portalLayer--; - - ((MinecraftAccessor)minecraft).setMainRenderTarget(oldTarget); - oldTarget.bindWrite(true); - - glEnable(GL_STENCIL_TEST); - RenderSystem.stencilFunc(GL_LEQUAL, portalLayer + 1, 0xff); - newTarget.blitToScreen(oldTarget.width, oldTarget.height, false); - glDisable(GL_STENCIL_TEST); - - freeRenderTarget(newTarget); - } - - @Override - public PortalRenderPhase targetPhase() { - return PortalRenderPhase.FINAL; - } + private static final Queue FREE_TARGETS = new ArrayDeque<>(); + + private final PortalRendererImpl stencilRenderer = new StencilRenderer(); + private int portalLayer = 0; + + private static RenderTarget getRenderTarget(int width, int height) { + final RenderTarget target = FREE_TARGETS.poll(); + if (target == null) { + return new TextureTarget(width, height, true, Minecraft.ON_OSX); + } + if (target.width != width || target.height != height) { + target.resize(width, height, Minecraft.ON_OSX); + } + return target; + } + + private static void freeRenderTarget(RenderTarget target) { + if (!FREE_TARGETS.offer(target)) { + target.destroyBuffers(); + } + } + + @Override + public boolean enabled(Portal portal) { + return portalLayer < MAX_PORTAL_LAYER && portal.getActive(); + } + + @Override + public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + stencilRenderer.preRender(portal, tickDelta, poseStack, bufferSource); + } + + @Override + public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + ((MultiBufferSource.BufferSource)bufferSource).endBatch(); + RenderSystem.colorMask(true, true, true, true); + RenderSystem.depthMask(true); + RenderSystem.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + RenderSystem.stencilFunc(GL_ALWAYS, 0, 0xff); + glDisable(GL_STENCIL_TEST); + + final Minecraft minecraft = Minecraft.getInstance(); + final RenderTarget oldTarget = minecraft.getMainRenderTarget(); + final RenderTarget newTarget = getRenderTarget(oldTarget.width, oldTarget.height); + + ((MinecraftAccessor)minecraft).setMainRenderTarget(newTarget); + newTarget.bindWrite(true); + + GlStateManager._clearColor(1, 0, 1, 1); + GlStateManager._clearDepth(1); + GlStateManager._clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, Minecraft.ON_OSX); + + portalLayer++; + renderWorld(portal, tickDelta); + portalLayer--; + + ((MinecraftAccessor)minecraft).setMainRenderTarget(oldTarget); + oldTarget.bindWrite(true); + + glEnable(GL_STENCIL_TEST); + RenderSystem.stencilFunc(GL_LEQUAL, portalLayer + 1, 0xff); + newTarget.blitToScreen(oldTarget.width, oldTarget.height, false); + glDisable(GL_STENCIL_TEST); + + freeRenderTarget(newTarget); + } + + @Override + public PortalRenderPhase targetPhase() { + return PortalRenderPhase.FINAL; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderPhase.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderPhase.java index 4fc05f00..6c666ef0 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderPhase.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderPhase.java @@ -1,5 +1,5 @@ package com.fusionflux.portalcubed.client.render.portal; public enum PortalRenderPhase { - ENTITY, TRACER, FINAL + ENTITY, TRACER, FINAL } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRendererImpl.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRendererImpl.java index e9ef17a4..c9909e77 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRendererImpl.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRendererImpl.java @@ -20,101 +20,101 @@ @SuppressWarnings("UnstableApiUsage") public abstract class PortalRendererImpl { - private static final Deque RENDER_BUFFERS_POOL = new ArrayDeque<>(4); - private static int buffersPoolCount = 0; - - protected static final int MAX_PORTAL_LAYER = 1; // No recursive rendering yet - - public abstract boolean enabled(Portal portal); - - public abstract void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource); - - public abstract void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource); - - public abstract PortalRenderPhase targetPhase(); - - protected void renderWorld(Portal portal, float tickDelta) { - final Minecraft minecraft = Minecraft.getInstance(); - minecraft.getProfiler().push("pc_portal_render"); - - final WorldRenderContextImpl contextObj = (WorldRenderContextImpl)PortalCubedClient.worldRenderContext; - - final Camera oldCamera = minecraft.gameRenderer.getMainCamera(); - final Frustum oldFrustum = ((LevelRendererExt)minecraft.levelRenderer).getCullingFrustum(); - final RenderBuffers oldRenderBuffers = ((LevelRendererExt)minecraft.levelRenderer).getRenderBuffers(); - final RenderBuffers oldGlobalBuffers = minecraft.renderBuffers(); - final WorldRenderContextImpl oldRenderContext = copyWorldRenderContext(contextObj, new WorldRenderContextImpl()); - - final Camera newCamera = new Camera(); - - final RenderBuffers newRenderBuffers = newRenderBuffers(); - if (newRenderBuffers != null) { - ((LevelRendererExt)minecraft.levelRenderer).setRenderBuffers(newRenderBuffers); - ((MinecraftExt)minecraft).setRenderBuffers(newRenderBuffers); - } - - ((GameRendererExt)minecraft.gameRenderer).setMainCamera(newCamera); - - final PortalRenderPhase phase = PortalRenderer.renderPhase; - PortalRenderer.renderPhase = PortalRenderPhase.ENTITY; - minecraft.gameRenderer.renderLevel(tickDelta, Util.getNanos(), new PoseStack()); - PortalRenderer.renderPhase = phase; - - ((GameRendererExt)minecraft.gameRenderer).setMainCamera(oldCamera); - ((LevelRendererExt)minecraft.levelRenderer).setCullingFrustum(oldFrustum); - ((LevelRendererExt)minecraft.levelRenderer).setRenderBuffers(oldRenderBuffers); - ((MinecraftExt)minecraft).setRenderBuffers(oldGlobalBuffers); - copyWorldRenderContext(oldRenderContext, contextObj); - - if (newRenderBuffers != null) { - freeRenderBuffers(newRenderBuffers); - } - - minecraft.getProfiler().pop(); - } - - private static RenderBuffers newRenderBuffers() { - if (buffersPoolCount >= 2) { - return null; - } - buffersPoolCount--; - if (RENDER_BUFFERS_POOL.isEmpty()) { - return new RenderBuffers(); - } - return RENDER_BUFFERS_POOL.pop(); - } - - private static void freeRenderBuffers(RenderBuffers buffers) { - buffersPoolCount++; - RENDER_BUFFERS_POOL.add(buffers); - } - - private static WorldRenderContextImpl copyWorldRenderContext(WorldRenderContextImpl from, WorldRenderContextImpl to) { - to.prepare( - from.worldRenderer(), - from.matrixStack(), - from.tickDelta(), - from.limitTime(), - from.blockOutlines(), - from.camera(), - from.gameRenderer(), - from.lightmapTextureManager(), - from.projectionMatrix(), - from.consumers(), - from.profiler(), - from.advancedTranslucency(), - from.world() - ); - to.setFrustum(from.frustum()); - to.prepareBlockOutline( - from.entity(), - from.cameraX(), - from.cameraY(), - from.cameraZ(), - from.blockPos(), - from.blockState() - ); - to.renderBlockOutline = from.renderBlockOutline; - return to; - } + private static final Deque RENDER_BUFFERS_POOL = new ArrayDeque<>(4); + private static int buffersPoolCount = 0; + + protected static final int MAX_PORTAL_LAYER = 1; // No recursive rendering yet + + public abstract boolean enabled(Portal portal); + + public abstract void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource); + + public abstract void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource); + + public abstract PortalRenderPhase targetPhase(); + + protected void renderWorld(Portal portal, float tickDelta) { + final Minecraft minecraft = Minecraft.getInstance(); + minecraft.getProfiler().push("pc_portal_render"); + + final WorldRenderContextImpl contextObj = (WorldRenderContextImpl)PortalCubedClient.worldRenderContext; + + final Camera oldCamera = minecraft.gameRenderer.getMainCamera(); + final Frustum oldFrustum = ((LevelRendererExt)minecraft.levelRenderer).getCullingFrustum(); + final RenderBuffers oldRenderBuffers = ((LevelRendererExt)minecraft.levelRenderer).getRenderBuffers(); + final RenderBuffers oldGlobalBuffers = minecraft.renderBuffers(); + final WorldRenderContextImpl oldRenderContext = copyWorldRenderContext(contextObj, new WorldRenderContextImpl()); + + final Camera newCamera = new Camera(); + + final RenderBuffers newRenderBuffers = newRenderBuffers(); + if (newRenderBuffers != null) { + ((LevelRendererExt)minecraft.levelRenderer).setRenderBuffers(newRenderBuffers); + ((MinecraftExt)minecraft).setRenderBuffers(newRenderBuffers); + } + + ((GameRendererExt)minecraft.gameRenderer).setMainCamera(newCamera); + + final PortalRenderPhase phase = PortalRenderer.renderPhase; + PortalRenderer.renderPhase = PortalRenderPhase.ENTITY; + minecraft.gameRenderer.renderLevel(tickDelta, Util.getNanos(), new PoseStack()); + PortalRenderer.renderPhase = phase; + + ((GameRendererExt)minecraft.gameRenderer).setMainCamera(oldCamera); + ((LevelRendererExt)minecraft.levelRenderer).setCullingFrustum(oldFrustum); + ((LevelRendererExt)minecraft.levelRenderer).setRenderBuffers(oldRenderBuffers); + ((MinecraftExt)minecraft).setRenderBuffers(oldGlobalBuffers); + copyWorldRenderContext(oldRenderContext, contextObj); + + if (newRenderBuffers != null) { + freeRenderBuffers(newRenderBuffers); + } + + minecraft.getProfiler().pop(); + } + + private static RenderBuffers newRenderBuffers() { + if (buffersPoolCount >= 2) { + return null; + } + buffersPoolCount--; + if (RENDER_BUFFERS_POOL.isEmpty()) { + return new RenderBuffers(); + } + return RENDER_BUFFERS_POOL.pop(); + } + + private static void freeRenderBuffers(RenderBuffers buffers) { + buffersPoolCount++; + RENDER_BUFFERS_POOL.add(buffers); + } + + private static WorldRenderContextImpl copyWorldRenderContext(WorldRenderContextImpl from, WorldRenderContextImpl to) { + to.prepare( + from.worldRenderer(), + from.matrixStack(), + from.tickDelta(), + from.limitTime(), + from.blockOutlines(), + from.camera(), + from.gameRenderer(), + from.lightmapTextureManager(), + from.projectionMatrix(), + from.consumers(), + from.profiler(), + from.advancedTranslucency(), + from.world() + ); + to.setFrustum(from.frustum()); + to.prepareBlockOutline( + from.entity(), + from.cameraX(), + from.cameraY(), + from.cameraZ(), + from.blockPos(), + from.blockState() + ); + to.renderBlockOutline = from.renderBlockOutline; + return to; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderers.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderers.java index a356d4db..8440a184 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderers.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/PortalRenderers.java @@ -4,13 +4,13 @@ @SuppressWarnings("Convert2MethodRef") // Using a lambda makes the classes be loaded more lazily, preventing crashes on the dedicated server public enum PortalRenderers { - DISABLED(() -> new DisabledRenderer()), - STENCIL(() -> new StencilRenderer()), - FRAMEBUFFER(() -> new FramebufferRenderer()); + DISABLED(() -> new DisabledRenderer()), + STENCIL(() -> new StencilRenderer()), + FRAMEBUFFER(() -> new FramebufferRenderer()); - public final Supplier creator; + public final Supplier creator; - PortalRenderers(Supplier creator) { - this.creator = creator; - } + PortalRenderers(Supplier creator) { + this.creator = creator; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/client/render/portal/StencilRenderer.java b/src/main/java/com/fusionflux/portalcubed/client/render/portal/StencilRenderer.java index 77be6754..f59ed806 100644 --- a/src/main/java/com/fusionflux/portalcubed/client/render/portal/StencilRenderer.java +++ b/src/main/java/com/fusionflux/portalcubed/client/render/portal/StencilRenderer.java @@ -10,44 +10,44 @@ import static org.lwjgl.opengl.GL11.*; public class StencilRenderer extends PortalRendererImpl { - private int portalLayer = 0; - - @Override - public boolean enabled(Portal portal) { - return portalLayer < MAX_PORTAL_LAYER && portal.getActive(); - } - - @Override - public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - ((MultiBufferSource.BufferSource)bufferSource).endBatch(); - // TODO: PortingLib compat - ((RenderTargetExt)Minecraft.getInstance().getMainRenderTarget()).setStencilBufferEnabled(true); - glEnable(GL_STENCIL_TEST); - RenderSystem.clear(GL_STENCIL_BUFFER_BIT, Minecraft.ON_OSX); - RenderSystem.colorMask(false, false, false, false); - RenderSystem.depthMask(false); - RenderSystem.stencilMask(0xff); - RenderSystem.stencilFunc(GL_NEVER, 0, 0xff); - RenderSystem.stencilOp(GL_INCR, GL_KEEP, GL_KEEP); - } - - @Override - public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { - ((MultiBufferSource.BufferSource)bufferSource).endBatch(); - RenderSystem.colorMask(true, true, true, true); - RenderSystem.depthMask(true); - RenderSystem.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - RenderSystem.stencilFunc(GL_NEVER, 123, 0xff); - - portalLayer++; - renderWorld(portal, tickDelta); - portalLayer--; - - glDisable(GL_STENCIL_TEST); - } - - @Override - public PortalRenderPhase targetPhase() { - return PortalRenderPhase.FINAL; - } + private int portalLayer = 0; + + @Override + public boolean enabled(Portal portal) { + return portalLayer < MAX_PORTAL_LAYER && portal.getActive(); + } + + @Override + public void preRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + ((MultiBufferSource.BufferSource)bufferSource).endBatch(); + // TODO: PortingLib compat + ((RenderTargetExt)Minecraft.getInstance().getMainRenderTarget()).setStencilBufferEnabled(true); + glEnable(GL_STENCIL_TEST); + RenderSystem.clear(GL_STENCIL_BUFFER_BIT, Minecraft.ON_OSX); + RenderSystem.colorMask(false, false, false, false); + RenderSystem.depthMask(false); + RenderSystem.stencilMask(0xff); + RenderSystem.stencilFunc(GL_NEVER, 0, 0xff); + RenderSystem.stencilOp(GL_INCR, GL_KEEP, GL_KEEP); + } + + @Override + public void postRender(Portal portal, float tickDelta, PoseStack poseStack, MultiBufferSource bufferSource) { + ((MultiBufferSource.BufferSource)bufferSource).endBatch(); + RenderSystem.colorMask(true, true, true, true); + RenderSystem.depthMask(true); + RenderSystem.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + RenderSystem.stencilFunc(GL_NEVER, 123, 0xff); + + portalLayer++; + renderWorld(portal, tickDelta); + portalLayer--; + + glDisable(GL_STENCIL_TEST); + } + + @Override + public PortalRenderPhase targetPhase() { + return PortalRenderPhase.FINAL; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/ChellScaleCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/ChellScaleCommand.java index 6ca95df9..c832a47d 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/ChellScaleCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/ChellScaleCommand.java @@ -13,22 +13,22 @@ import static net.minecraft.commands.Commands.literal; public class ChellScaleCommand { - public static final float CHELL_SCALE = 1f / 1.62f; + public static final float CHELL_SCALE = 1f / 1.62f; - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(literal("chellscale") - .requires(s -> s.hasPermission(2)) - .executes(ctx -> scale(Collections.singleton(ctx.getSource().getEntity()))) - .then(argument("targets", EntityArgument.entities()) - .executes(ctx -> scale(EntityArgument.getEntities(ctx, "targets"))) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(literal("chellscale") + .requires(s -> s.hasPermission(2)) + .executes(ctx -> scale(Collections.singleton(ctx.getSource().getEntity()))) + .then(argument("targets", EntityArgument.entities()) + .executes(ctx -> scale(EntityArgument.getEntities(ctx, "targets"))) + ) + ); + } - public static int scale(Collection entities) { - for (final Entity entity : entities) { - ScaleTypes.BASE.getScaleData(entity).setTargetScale(CHELL_SCALE); - } - return entities.size(); - } + public static int scale(Collection entities) { + for (final Entity entity : entities) { + ScaleTypes.BASE.getScaleData(entity).setTargetScale(CHELL_SCALE); + } + return entities.size(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/DirectionArgumentType.java b/src/main/java/com/fusionflux/portalcubed/commands/DirectionArgumentType.java index 77bb2339..d9d1390a 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/DirectionArgumentType.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/DirectionArgumentType.java @@ -5,15 +5,15 @@ import net.minecraft.core.Direction; public class DirectionArgumentType extends StringRepresentableArgument { - private DirectionArgumentType() { - super(Direction.CODEC, Direction::values); - } + private DirectionArgumentType() { + super(Direction.CODEC, Direction::values); + } - public static StringRepresentableArgument direction() { - return new DirectionArgumentType(); - } + public static StringRepresentableArgument direction() { + return new DirectionArgumentType(); + } - public static Direction getDirection(CommandContext context, String name) { - return context.getArgument(name, Direction.class); - } + public static Direction getDirection(CommandContext context, String name) { + return context.getArgument(name, Direction.class); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/FireRocketCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/FireRocketCommand.java index bff55869..42f35920 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/FireRocketCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/FireRocketCommand.java @@ -16,27 +16,27 @@ import static net.minecraft.commands.Commands.literal; public class FireRocketCommand { - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(literal("firerocket") - .requires(s -> s.hasPermission(2)) - .executes(ctx -> fireRocket(ctx.getSource(), null)) - .then(argument("rotation", RotationArgument.rotation()) - .executes(ctx -> fireRocket(ctx.getSource(), RotationArgument.getRotation(ctx, "rotation"))) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(literal("firerocket") + .requires(s -> s.hasPermission(2)) + .executes(ctx -> fireRocket(ctx.getSource(), null)) + .then(argument("rotation", RotationArgument.rotation()) + .executes(ctx -> fireRocket(ctx.getSource(), RotationArgument.getRotation(ctx, "rotation"))) + ) + ); + } - public static int fireRocket(CommandSourceStack source, @Nullable Coordinates rotationArg) { - final RocketEntity rocket = PortalCubedEntities.ROCKET.create(source.getLevel()); - if (rocket == null) return 0; - final Vec2 rotation = rotationArg != null - ? rotationArg.getRotation(source) - : source.getRotation(); - rocket.setPos(source.getAnchor().apply(source)); - rocket.setYRot(rotation.y); - rocket.setXRot(rotation.x); - source.getLevel().addFreshEntity(rocket); - source.getLevel().playSound(null, rocket, PortalCubedSounds.ROCKET_FIRE_EVENT, SoundSource.HOSTILE, 1, 1); - return Command.SINGLE_SUCCESS; - } + public static int fireRocket(CommandSourceStack source, @Nullable Coordinates rotationArg) { + final RocketEntity rocket = PortalCubedEntities.ROCKET.create(source.getLevel()); + if (rocket == null) return 0; + final Vec2 rotation = rotationArg != null + ? rotationArg.getRotation(source) + : source.getRotation(); + rocket.setPos(source.getAnchor().apply(source)); + rocket.setYRot(rotation.y); + rocket.setXRot(rotation.x); + source.getLevel().addFreshEntity(rocket); + source.getLevel().playSound(null, rocket, PortalCubedSounds.ROCKET_FIRE_EVENT, SoundSource.HOSTILE, 1, 1); + return Command.SINGLE_SUCCESS; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/FizzleCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/FizzleCommand.java index 0cf0c2b1..3191a0b3 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/FizzleCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/FizzleCommand.java @@ -13,33 +13,33 @@ import static net.minecraft.commands.Commands.literal; public class FizzleCommand { - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(literal("fizzle") - .requires(s -> s.hasPermission(2)) - .then(argument("entity", EntityArgument.entities()) - .executes(ctx -> { - final List entities = EntityArgument.getOptionalEntities(ctx, "entity") - .stream() - .filter(e -> e instanceof Fizzleable) - .map(e -> (Fizzleable)e) - .toList(); - if (entities.isEmpty()) { - throw EntityArgument.NO_ENTITIES_FOUND.create(); - } - fizzle(entities); - ctx.getSource().sendSuccess( - () -> Component.translatable("portalcubed.command.fizzle.success", entities.size()), - true - ); - return entities.size(); - }) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(literal("fizzle") + .requires(s -> s.hasPermission(2)) + .then(argument("entity", EntityArgument.entities()) + .executes(ctx -> { + final List entities = EntityArgument.getOptionalEntities(ctx, "entity") + .stream() + .filter(e -> e instanceof Fizzleable) + .map(e -> (Fizzleable)e) + .toList(); + if (entities.isEmpty()) { + throw EntityArgument.NO_ENTITIES_FOUND.create(); + } + fizzle(entities); + ctx.getSource().sendSuccess( + () -> Component.translatable("portalcubed.command.fizzle.success", entities.size()), + true + ); + return entities.size(); + }) + ) + ); + } - public static void fizzle(Collection entities) { - for (final Fizzleable physics : entities) { - physics.fizzle(); - } - } + public static void fizzle(Collection entities) { + for (final Fizzleable physics : entities) { + physics.fizzle(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/FogCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/FogCommand.java index 41e0ac08..b1f5fe49 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/FogCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/FogCommand.java @@ -21,126 +21,126 @@ import static net.minecraft.commands.Commands.literal; public class FogCommand { - @FunctionalInterface - private interface DefaultDimensionAction { - int run(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException; - } + @FunctionalInterface + private interface DefaultDimensionAction { + int run(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException; + } - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(buildDefaultDimension(literal("fog"), FogCommand::getFog) - .requires(s -> s.hasPermission(2)) - .then(buildDefaultDimension(literal("reset"), FogCommand::resetFog)) - .then(buildSet(literal("set"), true) - .then(buildSet(argument("dimension", DimensionArgument.dimension()), false)) - ) - .then(literal("preset") - .then(buildDefaultDimension(argument("preset", EnumArgumentType.enumConstant(FogPreset.class)), FogCommand::presetFog)) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(buildDefaultDimension(literal("fog"), FogCommand::getFog) + .requires(s -> s.hasPermission(2)) + .then(buildDefaultDimension(literal("reset"), FogCommand::resetFog)) + .then(buildSet(literal("set"), true) + .then(buildSet(argument("dimension", DimensionArgument.dimension()), false)) + ) + .then(literal("preset") + .then(buildDefaultDimension(argument("preset", EnumArgumentType.enumConstant(FogPreset.class)), FogCommand::presetFog)) + ) + ); + } - private static > ArgumentBuilder buildDefaultDimension( - ArgumentBuilder builder, - DefaultDimensionAction action - ) { - return builder.executes(ctx -> action.run(ctx, true)) - .then(argument("dimension", DimensionArgument.dimension()) - .executes(ctx -> action.run(ctx, false)) - ); - } + private static > ArgumentBuilder buildDefaultDimension( + ArgumentBuilder builder, + DefaultDimensionAction action + ) { + return builder.executes(ctx -> action.run(ctx, true)) + .then(argument("dimension", DimensionArgument.dimension()) + .executes(ctx -> action.run(ctx, false)) + ); + } - private static ArgumentBuilder buildSet(ArgumentBuilder builder, boolean defaultDimension) { - return builder.then(argument("near", FloatArgumentType.floatArg()) - .then(argument("far", FloatArgumentType.floatArg(0)) - .then(argument("red", IntegerArgumentType.integer(0, 255)) - .then(argument("green", IntegerArgumentType.integer(0, 255)) - .then(argument("blue", IntegerArgumentType.integer(0, 255)) - .executes(ctx -> setFog(ctx, defaultDimension, true)) - .then(argument("shape", EnumArgumentType.enumConstant(FogSettings.Shape.class)) - .executes(ctx -> setFog(ctx, defaultDimension, false)) - ) - ) - ) - ) - ) - ); - } + private static ArgumentBuilder buildSet(ArgumentBuilder builder, boolean defaultDimension) { + return builder.then(argument("near", FloatArgumentType.floatArg()) + .then(argument("far", FloatArgumentType.floatArg(0)) + .then(argument("red", IntegerArgumentType.integer(0, 255)) + .then(argument("green", IntegerArgumentType.integer(0, 255)) + .then(argument("blue", IntegerArgumentType.integer(0, 255)) + .executes(ctx -> setFog(ctx, defaultDimension, true)) + .then(argument("shape", EnumArgumentType.enumConstant(FogSettings.Shape.class)) + .executes(ctx -> setFog(ctx, defaultDimension, false)) + ) + ) + ) + ) + ) + ); + } - public static int getFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { - final ServerLevel dimension = getDimension(ctx, defaultDimension); - ctx.getSource().sendSuccess(() -> Component.translatable( - "portalcubed.command.fog.success", - dimension.dimension().location(), - FogPersistentState.getOrCreate(dimension).getSettings() - ), false); - return Command.SINGLE_SUCCESS; - } + public static int getFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { + final ServerLevel dimension = getDimension(ctx, defaultDimension); + ctx.getSource().sendSuccess(() -> Component.translatable( + "portalcubed.command.fog.success", + dimension.dimension().location(), + FogPersistentState.getOrCreate(dimension).getSettings() + ), false); + return Command.SINGLE_SUCCESS; + } - public static int resetFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { - final ServerLevel dimension = getDimension(ctx, defaultDimension); - FogPersistentState.getOrCreate(dimension).setSettings(null); - PortalCubed.syncFog(dimension); - ctx.getSource().sendSuccess(() -> Component.translatable( - "portalcubed.command.fog.reset.success", - dimension.dimension().location() - ), true); - return Command.SINGLE_SUCCESS; - } + public static int resetFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { + final ServerLevel dimension = getDimension(ctx, defaultDimension); + FogPersistentState.getOrCreate(dimension).setSettings(null); + PortalCubed.syncFog(dimension); + ctx.getSource().sendSuccess(() -> Component.translatable( + "portalcubed.command.fog.reset.success", + dimension.dimension().location() + ), true); + return Command.SINGLE_SUCCESS; + } - public static int setFog(CommandContext ctx, boolean defaultDimension, boolean defaultShape) throws CommandSyntaxException { - final ServerLevel dimension = getDimension(ctx, defaultDimension); - final FogSettings settings = new FogSettings( - FloatArgumentType.getFloat(ctx, "near"), - FloatArgumentType.getFloat(ctx, "far"), - new FogSettings.Color( - IntegerArgumentType.getInteger(ctx, "red"), - IntegerArgumentType.getInteger(ctx, "green"), - IntegerArgumentType.getInteger(ctx, "blue") - ), - defaultShape - ? FogSettings.Shape.SPHERE - : EnumArgumentType.getEnumConstant(ctx, "shape", FogSettings.Shape.class) - ); - FogPersistentState.getOrCreate(dimension).setSettings(settings); - PortalCubed.syncFog(dimension); - ctx.getSource().sendSuccess(() -> Component.translatable( - "portalcubed.command.fog.set.success", - dimension.dimension().location(), - settings - ), true); - return Command.SINGLE_SUCCESS; - } + public static int setFog(CommandContext ctx, boolean defaultDimension, boolean defaultShape) throws CommandSyntaxException { + final ServerLevel dimension = getDimension(ctx, defaultDimension); + final FogSettings settings = new FogSettings( + FloatArgumentType.getFloat(ctx, "near"), + FloatArgumentType.getFloat(ctx, "far"), + new FogSettings.Color( + IntegerArgumentType.getInteger(ctx, "red"), + IntegerArgumentType.getInteger(ctx, "green"), + IntegerArgumentType.getInteger(ctx, "blue") + ), + defaultShape + ? FogSettings.Shape.SPHERE + : EnumArgumentType.getEnumConstant(ctx, "shape", FogSettings.Shape.class) + ); + FogPersistentState.getOrCreate(dimension).setSettings(settings); + PortalCubed.syncFog(dimension); + ctx.getSource().sendSuccess(() -> Component.translatable( + "portalcubed.command.fog.set.success", + dimension.dimension().location(), + settings + ), true); + return Command.SINGLE_SUCCESS; + } - public static int presetFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { - final ServerLevel dimension = getDimension(ctx, defaultDimension); - final FogPreset preset = getEnumConstant(ctx, "preset", FogPreset.class); - FogPersistentState.getOrCreate(dimension).setSettings(preset.getSettings()); - PortalCubed.syncFog(dimension); - ctx.getSource().sendSuccess(() -> Component.translatable( - "portalcubed.command.fog.preset.success", - dimension.dimension().location(), - preset - ), true); - return Command.SINGLE_SUCCESS; - } + public static int presetFog(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { + final ServerLevel dimension = getDimension(ctx, defaultDimension); + final FogPreset preset = getEnumConstant(ctx, "preset", FogPreset.class); + FogPersistentState.getOrCreate(dimension).setSettings(preset.getSettings()); + PortalCubed.syncFog(dimension); + ctx.getSource().sendSuccess(() -> Component.translatable( + "portalcubed.command.fog.preset.success", + dimension.dimension().location(), + preset + ), true); + return Command.SINGLE_SUCCESS; + } - private static ServerLevel getDimension(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { - return defaultDimension - ? ctx.getSource().getLevel() - : DimensionArgument.getDimension(ctx, "dimension"); - } + private static ServerLevel getDimension(CommandContext ctx, boolean defaultDimension) throws CommandSyntaxException { + return defaultDimension + ? ctx.getSource().getLevel() + : DimensionArgument.getDimension(ctx, "dimension"); + } - // Reimplemented here because QSL implements a validation that's also bugged and throws exceptions when it shouldn't - private static > E getEnumConstant(CommandContext context, String argumentName, Class enumClass) throws CommandSyntaxException { - String value = context.getArgument(argumentName, String.class); - E[] constants = enumClass.getEnumConstants(); + // Reimplemented here because QSL implements a validation that's also bugged and throws exceptions when it shouldn't + private static > E getEnumConstant(CommandContext context, String argumentName, Class enumClass) throws CommandSyntaxException { + String value = context.getArgument(argumentName, String.class); + E[] constants = enumClass.getEnumConstants(); - for (var constant : constants) { - if (constant.name().equalsIgnoreCase(value)) { - return constant; - } - } + for (var constant : constants) { + if (constant.name().equalsIgnoreCase(value)) { + return constant; + } + } - throw EnumArgumentType.UNKNOWN_VALUE_EXCEPTION.create(argumentName); - } + throw EnumArgumentType.UNKNOWN_VALUE_EXCEPTION.create(argumentName); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/LaserSongCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/LaserSongCommand.java index ac4b021f..fd8f83dd 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/LaserSongCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/LaserSongCommand.java @@ -16,35 +16,35 @@ import static net.minecraft.commands.Commands.literal; public class LaserSongCommand { - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(literal("lasersong") - .requires(s -> s.hasPermission(2)) - .then(argument("node", BlockPosArgument.blockPos()) - .then(argument("song", ResourceLocationArgument.id()) - .suggests(SuggestionProviders.AVAILABLE_SOUNDS) - .executes(ctx -> { - final BlockPos pos = BlockPosArgument.getLoadedBlockPos(ctx, "node"); - final ResourceLocation song = ResourceLocationArgument.getId(ctx, "song"); - final LaserNodeBlockEntity entity = ctx.getSource() - .getLevel() - .getBlockEntity(pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY) - .orElse(null); - if (entity == null) { - ctx.getSource().sendFailure( - Component.translatable("portalcubed.command.lasersong.failed", pos) - .withStyle(ChatFormatting.RED) - ); - return 0; - } - entity.setSound(song); - ctx.getSource().sendSuccess( - () -> Component.translatable("portalcubed.command.lasersong.success", pos, song), - true - ); - return 1; - }) - ) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(literal("lasersong") + .requires(s -> s.hasPermission(2)) + .then(argument("node", BlockPosArgument.blockPos()) + .then(argument("song", ResourceLocationArgument.id()) + .suggests(SuggestionProviders.AVAILABLE_SOUNDS) + .executes(ctx -> { + final BlockPos pos = BlockPosArgument.getLoadedBlockPos(ctx, "node"); + final ResourceLocation song = ResourceLocationArgument.getId(ctx, "song"); + final LaserNodeBlockEntity entity = ctx.getSource() + .getLevel() + .getBlockEntity(pos, PortalCubedBlocks.LASER_NODE_BLOCK_ENTITY) + .orElse(null); + if (entity == null) { + ctx.getSource().sendFailure( + Component.translatable("portalcubed.command.lasersong.failed", pos) + .withStyle(ChatFormatting.RED) + ); + return 0; + } + entity.setSound(song); + ctx.getSource().sendSuccess( + () -> Component.translatable("portalcubed.command.lasersong.success", pos, song), + true + ); + return 1; + }) + ) + ) + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/PortalCubedCommands.java b/src/main/java/com/fusionflux/portalcubed/commands/PortalCubedCommands.java index 52c133b9..7a9ef59e 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/PortalCubedCommands.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/PortalCubedCommands.java @@ -8,15 +8,15 @@ import org.quiltmc.qsl.command.api.CommandRegistrationCallback; public class PortalCubedCommands implements CommandRegistrationCallback { - @Override - public void registerCommands(CommandDispatcher dispatcher, CommandBuildContext buildContext, Commands.CommandSelection environment) { - FizzleCommand.register(dispatcher); - FireRocketCommand.register(dispatcher); - LaserSongCommand.register(dispatcher); - FogCommand.register(dispatcher); - RotatePortalCommand.register(dispatcher); - if (QuiltLoader.isModLoaded("pehkui")) { - ChellScaleCommand.register(dispatcher); - } - } + @Override + public void registerCommands(CommandDispatcher dispatcher, CommandBuildContext buildContext, Commands.CommandSelection environment) { + FizzleCommand.register(dispatcher); + FireRocketCommand.register(dispatcher); + LaserSongCommand.register(dispatcher); + FogCommand.register(dispatcher); + RotatePortalCommand.register(dispatcher); + if (QuiltLoader.isModLoaded("pehkui")) { + ChellScaleCommand.register(dispatcher); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/commands/RotatePortalCommand.java b/src/main/java/com/fusionflux/portalcubed/commands/RotatePortalCommand.java index c9692afa..9e36ad25 100644 --- a/src/main/java/com/fusionflux/portalcubed/commands/RotatePortalCommand.java +++ b/src/main/java/com/fusionflux/portalcubed/commands/RotatePortalCommand.java @@ -16,35 +16,35 @@ import static net.minecraft.commands.Commands.literal; public class RotatePortalCommand { - private static final SimpleCommandExceptionType NOT_PORTAL = new SimpleCommandExceptionType(Component.literal("Entity is not a Portal")); + private static final SimpleCommandExceptionType NOT_PORTAL = new SimpleCommandExceptionType(Component.literal("Entity is not a Portal")); - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(literal("rotateportal") - .requires(source -> source.hasPermission(2)) - .then(argument("portal", EntityArgument.entity()) - .then(argument("x", FloatArgumentType.floatArg()) - .then(argument("y", FloatArgumentType.floatArg()) - .then(argument("z", FloatArgumentType.floatArg()) - .then(argument("w", FloatArgumentType.floatArg()) - .executes(RotatePortalCommand::rotatePortal) - ) - ) - ) - ) - ) - ); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(literal("rotateportal") + .requires(source -> source.hasPermission(2)) + .then(argument("portal", EntityArgument.entity()) + .then(argument("x", FloatArgumentType.floatArg()) + .then(argument("y", FloatArgumentType.floatArg()) + .then(argument("z", FloatArgumentType.floatArg()) + .then(argument("w", FloatArgumentType.floatArg()) + .executes(RotatePortalCommand::rotatePortal) + ) + ) + ) + ) + ) + ); + } - private static int rotatePortal(CommandContext ctx) throws CommandSyntaxException { - Entity entity = EntityArgument.getEntity(ctx, "portal"); - if (!(entity instanceof Portal portal)) - throw NOT_PORTAL.create(); - float x = FloatArgumentType.getFloat(ctx, "x"); - float y = FloatArgumentType.getFloat(ctx, "y"); - float z = FloatArgumentType.getFloat(ctx, "z"); - float w = FloatArgumentType.getFloat(ctx, "w"); - portal.setDisableValidation(true); - portal.getRotation().lerpTo(new Quaternionf(x, y, z, w).normalize()); - return 1; - } + private static int rotatePortal(CommandContext ctx) throws CommandSyntaxException { + Entity entity = EntityArgument.getEntity(ctx, "portal"); + if (!(entity instanceof Portal portal)) + throw NOT_PORTAL.create(); + float x = FloatArgumentType.getFloat(ctx, "x"); + float y = FloatArgumentType.getFloat(ctx, "y"); + float z = FloatArgumentType.getFloat(ctx, "z"); + float w = FloatArgumentType.getFloat(ctx, "w"); + portal.setDisableValidation(true); + portal.getRotation().lerpTo(new Quaternionf(x, y, z, w).normalize()); + return 1; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/LambDynamicLightsIntegration.java b/src/main/java/com/fusionflux/portalcubed/compat/LambDynamicLightsIntegration.java index 50f1530e..ec56dff1 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/LambDynamicLightsIntegration.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/LambDynamicLightsIntegration.java @@ -6,28 +6,28 @@ import net.minecraft.util.Mth; public class LambDynamicLightsIntegration implements DynamicLightsInitializer { - public static final int CUBE_LIGHT = 1; - public static final int CORE_LIGHT = CUBE_LIGHT; + public static final int CUBE_LIGHT = 1; + public static final int CORE_LIGHT = CUBE_LIGHT; - @Override - public void onInitializeDynamicLights() { - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.STORAGE_CUBE, e -> CUBE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.COMPANION_CUBE, e -> CUBE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, e -> CUBE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, e -> CUBE_LIGHT); + @Override + public void onInitializeDynamicLights() { + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.STORAGE_CUBE, e -> CUBE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.COMPANION_CUBE, e -> CUBE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, e -> CUBE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, e -> CUBE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ANGER_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.MORALITY_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.CAKE_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.CURIOSITY_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.SPACE_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.FACT_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ADVENTURE_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ANGER_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.MORALITY_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.CAKE_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.CURIOSITY_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.SPACE_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.FACT_CORE, e -> CORE_LIGHT); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ADVENTURE_CORE, e -> CORE_LIGHT); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ENERGY_PELLET, e -> - Math.round((e.getStartingLife() > 0 ? Mth.clamp(Mth.lerp((float)e.getLife() / e.getStartingLife(), 0.25f, 1f), 0f, 1f) : 1f) * 15) - ); + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.ENERGY_PELLET, e -> + Math.round((e.getStartingLife() > 0 ? Mth.clamp(Mth.lerp((float)e.getLife() / e.getStartingLife(), 0.25f, 1f), 0f, 1f) : 1f) * 15) + ); - DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL, e -> 2); - } + DynamicLightHandlers.registerDynamicLightHandler(PortalCubedEntities.PORTAL, e -> 2); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/ModMenuIntegration.java b/src/main/java/com/fusionflux/portalcubed/compat/ModMenuIntegration.java index 3b97c863..fbb8242b 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/ModMenuIntegration.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/ModMenuIntegration.java @@ -6,8 +6,8 @@ @SuppressWarnings("unused") public class ModMenuIntegration implements ModMenuApi { - @Override - public ConfigScreenFactory getModConfigScreenFactory() { - return parent -> PortalCubedConfig.getScreen(parent, "portalcubed"); - } + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return parent -> PortalCubedConfig.getScreen(parent, "portalcubed"); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/create/CreateIntegration.java b/src/main/java/com/fusionflux/portalcubed/compat/create/CreateIntegration.java index f92c1a95..36cc169e 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/create/CreateIntegration.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/create/CreateIntegration.java @@ -1,7 +1,7 @@ //package com.fusionflux.portalcubed.compat.create; // //public class CreateIntegration { -// public static void init() { -// PCPonder.register(); -// } +// public static void init() { +// PCPonder.register(); +// } //} diff --git a/src/main/java/com/fusionflux/portalcubed/compat/create/PCPonder.java b/src/main/java/com/fusionflux/portalcubed/compat/create/PCPonder.java index 3507bbc7..633c37e5 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/create/PCPonder.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/create/PCPonder.java @@ -23,183 +23,183 @@ //import static com.fusionflux.portalcubed.PortalCubed.id; // //public class PCPonder { -// private static final PonderRegistrationHelper HELPER = new PonderRegistrationHelper(PortalCubed.MOD_ID); -// -// public static final PonderTag PORTAL_CUBED = new PonderTag(id("portal_cubed")) -// .item(PortalCubedItems.BLOCK_ITEM_ICON, true, false) -// .addToIndex(); -// -// private static final boolean GENERATE_TRANSLATIONS = false; -// -// public static void register() { -// HELPER.addStoryBoard( -// id("auto_portal"), -// "auto_portal", -// PCPonder::autoPortal, -// PORTAL_CUBED -// ); -// -// if (GENERATE_TRANSLATIONS) { -// PonderLocalization.generateSceneLang(); -// final JsonObject translation = new JsonObject(); -// PonderLocalization.record("portalcubed", translation); -// try (Writer writer = new FileWriter("create_ponder_portalcubed.json", StandardCharsets.UTF_8)) { -// new GsonBuilder().setPrettyPrinting().create().toJson(translation, writer); -// } catch (IOException e) { -// PortalCubed.LOGGER.error("Failed to save file", e); -// } -// } -// } -// -// public static void autoPortal(SceneBuilder scene, SceneBuildingUtil util) { -// scene.title("auto_portal", "Using the Auto Portal"); -// scene.configureBasePlate(0, 0, 4); -// scene.showBasePlate(); -// scene.idle(5); -// -// scene.world.showSection(util.select.position(2, 1, 2), Direction.DOWN); -// scene.idle(5); -// scene.world.showSection(util.select.position(2, 2, 2), Direction.DOWN); -// scene.idle(5); -// scene.world.showSection(util.select.fromTo(2, 1, 1, 2, 2, 1), Direction.SOUTH); -// scene.idle(5); -// scene.world.showSection(util.select.position(1, 2, 2), Direction.EAST); -// scene.idle(5); -// -// scene.overlay.showText(80) -// .text("Power an Auto Portal with redstone to open it.") -// .placeNearTarget() -// .pointAt(util.vector.centerOf(1, 2, 2)); -// scene.idle(60); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// var portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( -// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false -// )); -// -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.idle(20); -// -// scene.overlay.showText(80) -// .text("Power an Auto Portal with redstone again to close it.") -// .placeNearTarget() -// .pointAt(util.vector.centerOf(1, 2, 2)); -// scene.idle(60); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.world.modifyEntity(portalLink, Entity::kill); -// -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// -// scene.overlay.showControls( -// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) -// .rightClick() -// .withItem(new ItemStack(PortalCubedItems.HAMMER)), -// 70 -// ); -// scene.idle(10); -// scene.overlay.showText(60) -// .text("Right-click with a hammer to switch between primary and secondary modes.") -// .attachKeyFrame() -// .placeNearTarget() -// .pointAt(util.vector.centerOf(2, 1, 1)); -// scene.world.cycleBlockProperty(new BlockPos(2, 1, 1), AutoPortalBlock.TYPE); -// scene.world.cycleBlockProperty(new BlockPos(2, 2, 1), AutoPortalBlock.TYPE); -// scene.idle(90); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( -// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false -// )); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.idle(30); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.world.modifyEntity(portalLink, Entity::kill); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// -// scene.idle(10); -// scene.overlay.showControls( -// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) -// .rightClick() -// .withItem(new ItemStack(Items.PURPLE_DYE)), -// 70 -// ); -// scene.idle(10); -// scene.overlay.showText(60) -// .text("Right-click with dye to change the portal's base color.") -// .attachKeyFrame() -// .placeNearTarget() -// .pointAt(util.vector.centerOf(2, 1, 1)); -// scene.world.modifyTileNBT( -// util.select.position(2, 1, 1), -// AutoPortalBlockEntity.class, -// nbt -> nbt.putInt("Color", 0x8932b8) -// ); -// scene.world.modifyTileNBT( -// util.select.position(2, 2, 1), -// AutoPortalBlockEntity.class, -// nbt -> nbt.putInt("Color", 0x8932b8) -// ); -// scene.idle(90); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( -// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false -// )); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// -// scene.overlay.showText(60) -// .text("This portal is green because the Auto Portal is still set to secondary.") -// .placeNearTarget() -// .pointAt(util.vector.centerOf(2, 2, 1)); -// scene.idle(80); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.world.modifyEntity(portalLink, Entity::kill); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// -// scene.idle(10); -// scene.overlay.showControls( -// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) -// .rightClick() -// .withItem(new ItemStack(PortalCubedItems.HAMMER)) -// .whileSneaking(), -// 70 -// ); -// scene.idle(10); -// scene.overlay.showText(60) -// .text("Sneak right-click with a hammer to reset the portal's base color.") -// .attachKeyFrame() -// .placeNearTarget() -// .pointAt(util.vector.centerOf(2, 1, 1)); -// scene.world.modifyTileNBT( -// util.select.position(2, 1, 1), -// AutoPortalBlockEntity.class, -// nbt -> nbt.putInt("Color", 0x1d86db) -// ); -// scene.world.modifyTileNBT( -// util.select.position(2, 2, 1), -// AutoPortalBlockEntity.class, -// nbt -> nbt.putInt("Color", 0x1d86db) -// ); -// scene.idle(90); -// -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( -// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false -// )); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.idle(30); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// scene.world.modifyEntity(portalLink, Entity::kill); -// scene.idle(20); -// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); -// } +// private static final PonderRegistrationHelper HELPER = new PonderRegistrationHelper(PortalCubed.MOD_ID); +// +// public static final PonderTag PORTAL_CUBED = new PonderTag(id("portal_cubed")) +// .item(PortalCubedItems.BLOCK_ITEM_ICON, true, false) +// .addToIndex(); +// +// private static final boolean GENERATE_TRANSLATIONS = false; +// +// public static void register() { +// HELPER.addStoryBoard( +// id("auto_portal"), +// "auto_portal", +// PCPonder::autoPortal, +// PORTAL_CUBED +// ); +// +// if (GENERATE_TRANSLATIONS) { +// PonderLocalization.generateSceneLang(); +// final JsonObject translation = new JsonObject(); +// PonderLocalization.record("portalcubed", translation); +// try (Writer writer = new FileWriter("create_ponder_portalcubed.json", StandardCharsets.UTF_8)) { +// new GsonBuilder().setPrettyPrinting().create().toJson(translation, writer); +// } catch (IOException e) { +// PortalCubed.LOGGER.error("Failed to save file", e); +// } +// } +// } +// +// public static void autoPortal(SceneBuilder scene, SceneBuildingUtil util) { +// scene.title("auto_portal", "Using the Auto Portal"); +// scene.configureBasePlate(0, 0, 4); +// scene.showBasePlate(); +// scene.idle(5); +// +// scene.world.showSection(util.select.position(2, 1, 2), Direction.DOWN); +// scene.idle(5); +// scene.world.showSection(util.select.position(2, 2, 2), Direction.DOWN); +// scene.idle(5); +// scene.world.showSection(util.select.fromTo(2, 1, 1, 2, 2, 1), Direction.SOUTH); +// scene.idle(5); +// scene.world.showSection(util.select.position(1, 2, 2), Direction.EAST); +// scene.idle(5); +// +// scene.overlay.showText(80) +// .text("Power an Auto Portal with redstone to open it.") +// .placeNearTarget() +// .pointAt(util.vector.centerOf(1, 2, 2)); +// scene.idle(60); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// var portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( +// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false +// )); +// +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.idle(20); +// +// scene.overlay.showText(80) +// .text("Power an Auto Portal with redstone again to close it.") +// .placeNearTarget() +// .pointAt(util.vector.centerOf(1, 2, 2)); +// scene.idle(60); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.world.modifyEntity(portalLink, Entity::kill); +// +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// +// scene.overlay.showControls( +// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) +// .rightClick() +// .withItem(new ItemStack(PortalCubedItems.HAMMER)), +// 70 +// ); +// scene.idle(10); +// scene.overlay.showText(60) +// .text("Right-click with a hammer to switch between primary and secondary modes.") +// .attachKeyFrame() +// .placeNearTarget() +// .pointAt(util.vector.centerOf(2, 1, 1)); +// scene.world.cycleBlockProperty(new BlockPos(2, 1, 1), AutoPortalBlock.TYPE); +// scene.world.cycleBlockProperty(new BlockPos(2, 2, 1), AutoPortalBlock.TYPE); +// scene.idle(90); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( +// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false +// )); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.idle(30); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.world.modifyEntity(portalLink, Entity::kill); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// +// scene.idle(10); +// scene.overlay.showControls( +// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) +// .rightClick() +// .withItem(new ItemStack(Items.PURPLE_DYE)), +// 70 +// ); +// scene.idle(10); +// scene.overlay.showText(60) +// .text("Right-click with dye to change the portal's base color.") +// .attachKeyFrame() +// .placeNearTarget() +// .pointAt(util.vector.centerOf(2, 1, 1)); +// scene.world.modifyTileNBT( +// util.select.position(2, 1, 1), +// AutoPortalBlockEntity.class, +// nbt -> nbt.putInt("Color", 0x8932b8) +// ); +// scene.world.modifyTileNBT( +// util.select.position(2, 2, 1), +// AutoPortalBlockEntity.class, +// nbt -> nbt.putInt("Color", 0x8932b8) +// ); +// scene.idle(90); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( +// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false +// )); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// +// scene.overlay.showText(60) +// .text("This portal is green because the Auto Portal is still set to secondary.") +// .placeNearTarget() +// .pointAt(util.vector.centerOf(2, 2, 1)); +// scene.idle(80); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.world.modifyEntity(portalLink, Entity::kill); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// +// scene.idle(10); +// scene.overlay.showControls( +// new InputWindowElement(util.vector.centerOf(2, 2, 1), Pointing.RIGHT) +// .rightClick() +// .withItem(new ItemStack(PortalCubedItems.HAMMER)) +// .whileSneaking(), +// 70 +// ); +// scene.idle(10); +// scene.overlay.showText(60) +// .text("Sneak right-click with a hammer to reset the portal's base color.") +// .attachKeyFrame() +// .placeNearTarget() +// .pointAt(util.vector.centerOf(2, 1, 1)); +// scene.world.modifyTileNBT( +// util.select.position(2, 1, 1), +// AutoPortalBlockEntity.class, +// nbt -> nbt.putInt("Color", 0x1d86db) +// ); +// scene.world.modifyTileNBT( +// util.select.position(2, 2, 1), +// AutoPortalBlockEntity.class, +// nbt -> nbt.putInt("Color", 0x1d86db) +// ); +// scene.idle(90); +// +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// portalLink = scene.world.createEntity(world -> AutoPortalBlock.openOrClosePortal( +// world, new BlockPos(2, 1, 1), Direction.NORTH, false, false, false +// )); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.idle(30); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// scene.world.modifyEntity(portalLink, Entity::kill); +// scene.idle(20); +// scene.world.toggleRedstonePower(util.select.position(1, 2, 2)); +// } //} diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiApi.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiApi.java index a98e351e..0bfca514 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiApi.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiApi.java @@ -7,23 +7,23 @@ import org.quiltmc.loader.api.QuiltLoader; public interface PehkuiApi { - PehkuiApi INSTANCE = QuiltLoader.isModLoaded("pehkui") ? PehkuiPresentHolder.getPresent() : PehkuiApiAbsent.INSTANCE; + PehkuiApi INSTANCE = QuiltLoader.isModLoaded("pehkui") ? PehkuiPresentHolder.getPresent() : PehkuiApiAbsent.INSTANCE; - PehkuiScaleType getScaleType(ResourceLocation id); + PehkuiScaleType getScaleType(ResourceLocation id); - PehkuiScaleModifier getScaleModifier(ResourceLocation id); + PehkuiScaleModifier getScaleModifier(ResourceLocation id); - PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier); + PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier); - float getFallingScale(Entity entity); + float getFallingScale(Entity entity); - static ResourceLocation id(String path) { - return new ResourceLocation("pehkui", path); - } + static ResourceLocation id(String path) { + return new ResourceLocation("pehkui", path); + } - class PehkuiPresentHolder { - private static PehkuiApi getPresent() { - return new PehkuiApiPresent(); - } - } + class PehkuiPresentHolder { + private static PehkuiApi getPresent() { + return new PehkuiApiPresent(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleData.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleData.java index 283fde2c..670aee2b 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleData.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleData.java @@ -1,5 +1,5 @@ package com.fusionflux.portalcubed.compat.pehkui; public interface PehkuiScaleData { - double getScale(); + double getScale(); } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleModifiers.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleModifiers.java index 53b25b77..51cf1193 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleModifiers.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleModifiers.java @@ -1,5 +1,5 @@ package com.fusionflux.portalcubed.compat.pehkui; public class PehkuiScaleModifiers { - public static final PehkuiScaleModifier HEIGHT_MULTIPLIER = PehkuiApi.INSTANCE.getScaleModifier(PehkuiApi.id("height_multiplier")); + public static final PehkuiScaleModifier HEIGHT_MULTIPLIER = PehkuiApi.INSTANCE.getScaleModifier(PehkuiApi.id("height_multiplier")); } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleType.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleType.java index 6d0afbe3..2aa0c7a0 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleType.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleType.java @@ -3,5 +3,5 @@ import net.minecraft.world.entity.Entity; public interface PehkuiScaleType { - PehkuiScaleData getScaleData(Entity entity); + PehkuiScaleData getScaleData(Entity entity); } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleTypes.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleTypes.java index 1d7c9095..4cb06a23 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleTypes.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/PehkuiScaleTypes.java @@ -1,7 +1,7 @@ package com.fusionflux.portalcubed.compat.pehkui; public class PehkuiScaleTypes { - public static final PehkuiScaleType HITBOX_WIDTH = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("hitbox_width")); - public static final PehkuiScaleType HITBOX_HEIGHT = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("hitbox_height")); - public static final PehkuiScaleType ENTITY_REACH = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("entity_reach")); + public static final PehkuiScaleType HITBOX_WIDTH = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("hitbox_width")); + public static final PehkuiScaleType HITBOX_HEIGHT = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("hitbox_height")); + public static final PehkuiScaleType ENTITY_REACH = PehkuiApi.INSTANCE.getScaleType(PehkuiApi.id("entity_reach")); } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiApiAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiApiAbsent.java index 6f7b2b8b..7fd21206 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiApiAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiApiAbsent.java @@ -7,25 +7,25 @@ import net.minecraft.world.entity.Entity; public enum PehkuiApiAbsent implements PehkuiApi { - INSTANCE; + INSTANCE; - @Override - public PehkuiScaleType getScaleType(ResourceLocation id) { - return PehkuiScaleTypeAbsent.INSTANCE; - } + @Override + public PehkuiScaleType getScaleType(ResourceLocation id) { + return PehkuiScaleTypeAbsent.INSTANCE; + } - @Override - public PehkuiScaleModifier getScaleModifier(ResourceLocation id) { - return PehkuiScaleModifierAbsent.INSTANCE; - } + @Override + public PehkuiScaleModifier getScaleModifier(ResourceLocation id) { + return PehkuiScaleModifierAbsent.INSTANCE; + } - @Override - public PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier) { - return PehkuiScaleTypeAbsent.INSTANCE; - } + @Override + public PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier) { + return PehkuiScaleTypeAbsent.INSTANCE; + } - @Override - public float getFallingScale(Entity entity) { - return 1f; - } + @Override + public float getFallingScale(Entity entity) { + return 1f; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleDataAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleDataAbsent.java index 693e4646..47ff24bb 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleDataAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleDataAbsent.java @@ -3,10 +3,10 @@ import com.fusionflux.portalcubed.compat.pehkui.PehkuiScaleData; enum PehkuiScaleDataAbsent implements PehkuiScaleData { - INSTANCE; + INSTANCE; - @Override - public double getScale() { - return 1; - } + @Override + public double getScale() { + return 1; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleModifierAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleModifierAbsent.java index 2db7c897..6f8837a7 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleModifierAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleModifierAbsent.java @@ -3,5 +3,5 @@ import com.fusionflux.portalcubed.compat.pehkui.PehkuiScaleModifier; enum PehkuiScaleModifierAbsent implements PehkuiScaleModifier { - INSTANCE + INSTANCE } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleTypeAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleTypeAbsent.java index b2d60d8a..1d8e2749 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleTypeAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/absent/PehkuiScaleTypeAbsent.java @@ -5,10 +5,10 @@ import net.minecraft.world.entity.Entity; enum PehkuiScaleTypeAbsent implements PehkuiScaleType { - INSTANCE; + INSTANCE; - @Override - public PehkuiScaleData getScaleData(Entity entity) { - return PehkuiScaleDataAbsent.INSTANCE; - } + @Override + public PehkuiScaleData getScaleData(Entity entity) { + return PehkuiScaleDataAbsent.INSTANCE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiApiPresent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiApiPresent.java index 4bcf7aaf..ce14dc4d 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiApiPresent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiApiPresent.java @@ -11,30 +11,30 @@ import virtuoel.pehkui.api.ScaleTypes; public class PehkuiApiPresent implements PehkuiApi { - @Override - public PehkuiScaleType getScaleType(ResourceLocation id) { - final ScaleType scaleType = ScaleRegistries.getEntry(ScaleRegistries.SCALE_TYPES, id); - return scaleType == null ? null : new PehkuiScaleTypePresent(scaleType); - } + @Override + public PehkuiScaleType getScaleType(ResourceLocation id) { + final ScaleType scaleType = ScaleRegistries.getEntry(ScaleRegistries.SCALE_TYPES, id); + return scaleType == null ? null : new PehkuiScaleTypePresent(scaleType); + } - @Override - public PehkuiScaleModifier getScaleModifier(ResourceLocation id) { - final ScaleModifier scaleType = ScaleRegistries.getEntry(ScaleRegistries.SCALE_MODIFIERS, id); - return scaleType == null ? null : new PehkuiScaleModifierPresent(scaleType); - } + @Override + public PehkuiScaleModifier getScaleModifier(ResourceLocation id) { + final ScaleModifier scaleType = ScaleRegistries.getEntry(ScaleRegistries.SCALE_MODIFIERS, id); + return scaleType == null ? null : new PehkuiScaleModifierPresent(scaleType); + } - @Override - public PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier) { - return new PehkuiScaleTypePresent(ScaleRegistries.register( - ScaleRegistries.SCALE_TYPES, id, - ScaleType.Builder.create() - .addBaseValueModifier(((PehkuiScaleModifierPresent)valueModifier).inner()) - .build() - )); - } + @Override + public PehkuiScaleType registerScaleType(ResourceLocation id, PehkuiScaleModifier valueModifier) { + return new PehkuiScaleTypePresent(ScaleRegistries.register( + ScaleRegistries.SCALE_TYPES, id, + ScaleType.Builder.create() + .addBaseValueModifier(((PehkuiScaleModifierPresent)valueModifier).inner()) + .build() + )); + } - @Override - public float getFallingScale(Entity entity) { - return ScaleTypes.FALLING.getScaleData(entity).getScale(); - } + @Override + public float getFallingScale(Entity entity) { + return ScaleTypes.FALLING.getScaleData(entity).getScale(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleDataPresent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleDataPresent.java index 2110b82c..4e0960bb 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleDataPresent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleDataPresent.java @@ -4,8 +4,8 @@ import virtuoel.pehkui.api.ScaleData; record PehkuiScaleDataPresent(ScaleData inner) implements PehkuiScaleData { - @Override - public double getScale() { - return inner.getScale(); - } + @Override + public double getScale() { + return inner.getScale(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleTypePresent.java b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleTypePresent.java index 8a54827b..51222455 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleTypePresent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/pehkui/present/PehkuiScaleTypePresent.java @@ -6,8 +6,8 @@ import virtuoel.pehkui.api.ScaleType; record PehkuiScaleTypePresent(ScaleType inner) implements PehkuiScaleType { - @Override - public PehkuiScaleData getScaleData(Entity entity) { - return new PehkuiScaleDataPresent(inner.getScaleData(entity)); - } + @Override + public PehkuiScaleData getScaleData(Entity entity) { + return new PehkuiScaleDataPresent(inner.getScaleData(entity)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/PortalCubedRayonMixinPlugin.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/PortalCubedRayonMixinPlugin.java index 38b623b9..46b51c04 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/PortalCubedRayonMixinPlugin.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/PortalCubedRayonMixinPlugin.java @@ -9,34 +9,34 @@ import java.util.Set; public class PortalCubedRayonMixinPlugin implements IMixinConfigPlugin { - @Override - public void onLoad(String mixinPackage) { - } - - @Override - public String getRefMapperConfig() { - return null; - } - - @Override - public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { - return QuiltLoader.isModLoaded("rayon"); - } - - @Override - public void acceptTargets(Set myTargets, Set otherTargets) { - } - - @Override - public List getMixins() { - return null; - } - - @Override - public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - } - - @Override - public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - } + @Override + public void onLoad(String mixinPackage) { + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return QuiltLoader.isModLoaded("rayon"); + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) { + } + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonIntegration.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonIntegration.java index d0b24719..1b1c562e 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonIntegration.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonIntegration.java @@ -11,30 +11,30 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public interface RayonIntegration { - RayonIntegration INSTANCE = QuiltLoader.isModLoaded("rayon") ? RayonPresentHolder.create() : RayonIntegrationAbsent.INSTANCE; + RayonIntegration INSTANCE = QuiltLoader.isModLoaded("rayon") ? RayonPresentHolder.create() : RayonIntegrationAbsent.INSTANCE; - void init(); + void init(); - boolean isPresent(); + boolean isPresent(); - void setVelocity(Entity entity, Vec3 velocity); + void setVelocity(Entity entity, Vec3 velocity); - void simpleMove(Entity entity, MoverType movementType, Vec3 movement); + void simpleMove(Entity entity, MoverType movementType, Vec3 movement); - void setNoGravity(Entity entity, boolean noGravity); + void setNoGravity(Entity entity, boolean noGravity); - float getYaw(Entity entity); + float getYaw(Entity entity); - void rotateYaw(Entity entity, float amount); + void rotateYaw(Entity entity, float amount); - void setAngularVelocityYaw(Entity entity, Vector3f angle); + void setAngularVelocityYaw(Entity entity, Vector3f angle); - @ClientOnly - void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta); + @ClientOnly + void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta); - class RayonPresentHolder { - private static RayonIntegration create() { - return new RayonIntegrationPresent(); - } - } + class RayonPresentHolder { + private static RayonIntegration create() { + return new RayonIntegrationPresent(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonUtil.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonUtil.java index d979b7a6..ac62d637 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonUtil.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/RayonUtil.java @@ -8,63 +8,63 @@ import java.util.List; public class RayonUtil { - public static List getMeshOf(BoundingBox box, Vector3f offset) { - final var x = box.getXExtent() * 0.5f; - final var y = box.getYExtent() * 0.5f; - final var z = box.getZExtent() * 0.5f; + public static List getMeshOf(BoundingBox box, Vector3f offset) { + final var x = box.getXExtent() * 0.5f; + final var y = box.getYExtent() * 0.5f; + final var z = box.getZExtent() * 0.5f; - final var points = new Vector3f[] { - // south - new Vector3f(x, y, z), new Vector3f(-x, y, z), new Vector3f(0, 0, z), - new Vector3f(-x, y, z), new Vector3f(-x, -y, z), new Vector3f(0, 0, z), - new Vector3f(-x, -y, z), new Vector3f(x, -y, z), new Vector3f(0, 0, z), - new Vector3f(x, -y, z), new Vector3f(x, y, z), new Vector3f(0, 0, z), + final var points = new Vector3f[] { + // south + new Vector3f(x, y, z), new Vector3f(-x, y, z), new Vector3f(0, 0, z), + new Vector3f(-x, y, z), new Vector3f(-x, -y, z), new Vector3f(0, 0, z), + new Vector3f(-x, -y, z), new Vector3f(x, -y, z), new Vector3f(0, 0, z), + new Vector3f(x, -y, z), new Vector3f(x, y, z), new Vector3f(0, 0, z), - // north - new Vector3f(-x, y, -z), new Vector3f(x, y, -z), new Vector3f(0, 0, -z), - new Vector3f(x, y, -z), new Vector3f(x, -y, -z), new Vector3f(0, 0, -z), - new Vector3f(x, -y, -z), new Vector3f(-x, -y, -z), new Vector3f(0, 0, -z), - new Vector3f(-x, -y, -z), new Vector3f(-x, y, -z), new Vector3f(0, 0, -z), + // north + new Vector3f(-x, y, -z), new Vector3f(x, y, -z), new Vector3f(0, 0, -z), + new Vector3f(x, y, -z), new Vector3f(x, -y, -z), new Vector3f(0, 0, -z), + new Vector3f(x, -y, -z), new Vector3f(-x, -y, -z), new Vector3f(0, 0, -z), + new Vector3f(-x, -y, -z), new Vector3f(-x, y, -z), new Vector3f(0, 0, -z), - // east - new Vector3f(x, y, -z), new Vector3f(x, y, z), new Vector3f(x, 0, 0), - new Vector3f(x, y, z), new Vector3f(x, -y, z), new Vector3f(x, 0, 0), - new Vector3f(x, -y, z), new Vector3f(x, -y, -z), new Vector3f(x, 0, 0), - new Vector3f(x, -y, -z), new Vector3f(x, y, -z), new Vector3f(x, 0, 0), + // east + new Vector3f(x, y, -z), new Vector3f(x, y, z), new Vector3f(x, 0, 0), + new Vector3f(x, y, z), new Vector3f(x, -y, z), new Vector3f(x, 0, 0), + new Vector3f(x, -y, z), new Vector3f(x, -y, -z), new Vector3f(x, 0, 0), + new Vector3f(x, -y, -z), new Vector3f(x, y, -z), new Vector3f(x, 0, 0), - // west - new Vector3f(-x, y, z), new Vector3f(-x, y, -z), new Vector3f(-x, 0, 0), - new Vector3f(-x, y, -z), new Vector3f(-x, -y, -z), new Vector3f(-x, 0, 0), - new Vector3f(-x, -y, -z), new Vector3f(-x, -y, z), new Vector3f(-x, 0, 0), - new Vector3f(-x, -y, z), new Vector3f(-x, y, z), new Vector3f(-x, 0, 0), + // west + new Vector3f(-x, y, z), new Vector3f(-x, y, -z), new Vector3f(-x, 0, 0), + new Vector3f(-x, y, -z), new Vector3f(-x, -y, -z), new Vector3f(-x, 0, 0), + new Vector3f(-x, -y, -z), new Vector3f(-x, -y, z), new Vector3f(-x, 0, 0), + new Vector3f(-x, -y, z), new Vector3f(-x, y, z), new Vector3f(-x, 0, 0), - // up - new Vector3f(x, y, -z), new Vector3f(-x, y, -z), new Vector3f(0, y, 0), - new Vector3f(-x, y, -z), new Vector3f(-x, y, z), new Vector3f(0, y, 0), - new Vector3f(-x, y, z), new Vector3f(x, y, z), new Vector3f(0, y, 0), - new Vector3f(x, y, z), new Vector3f(x, y, -z), new Vector3f(0, y, 0), + // up + new Vector3f(x, y, -z), new Vector3f(-x, y, -z), new Vector3f(0, y, 0), + new Vector3f(-x, y, -z), new Vector3f(-x, y, z), new Vector3f(0, y, 0), + new Vector3f(-x, y, z), new Vector3f(x, y, z), new Vector3f(0, y, 0), + new Vector3f(x, y, z), new Vector3f(x, y, -z), new Vector3f(0, y, 0), - // down - new Vector3f(x, -y, z), new Vector3f(-x, -y, z), new Vector3f(0, -y, 0), - new Vector3f(-x, -y, z), new Vector3f(-x, -y, -z), new Vector3f(0, -y, 0), - new Vector3f(-x, -y, -z), new Vector3f(x, -y, -z), new Vector3f(0, -y, 0), - new Vector3f(x, -y, -z), new Vector3f(x, -y, z), new Vector3f(0, -y, 0) - }; + // down + new Vector3f(x, -y, z), new Vector3f(-x, -y, z), new Vector3f(0, -y, 0), + new Vector3f(-x, -y, z), new Vector3f(-x, -y, -z), new Vector3f(0, -y, 0), + new Vector3f(-x, -y, -z), new Vector3f(x, -y, -z), new Vector3f(0, -y, 0), + new Vector3f(x, -y, -z), new Vector3f(x, -y, z), new Vector3f(0, -y, 0) + }; - final var triangles = new ArrayList(); + final var triangles = new ArrayList(); - for (int i = 0; i < points.length; i += 3) { - triangles.add(new Triangle( - points[i].add(offset), - points[i + 1].add(offset), - points[i + 2].add(offset) - )); - } + for (int i = 0; i < points.length; i += 3) { + triangles.add(new Triangle( + points[i].add(offset), + points[i + 1].add(offset), + points[i + 2].add(offset) + )); + } - return triangles; - } + return triangles; + } - public static List getShiftedMeshOf(BoundingBox box) { - return getMeshOf(box, new Vector3f(0, box.getYExtent() / 2, 0)); - } + public static List getShiftedMeshOf(BoundingBox box) { + return getMeshOf(box, new Vector3f(0, box.getYExtent() / 2, 0)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/absent/RayonIntegrationAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/absent/RayonIntegrationAbsent.java index 90784a50..801f9130 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/absent/RayonIntegrationAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/absent/RayonIntegrationAbsent.java @@ -10,51 +10,51 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public enum RayonIntegrationAbsent implements RayonIntegration { - INSTANCE; - - @Override - public void init() { - } - - @Override - public boolean isPresent() { - return false; - } - - @Override - public void setVelocity(Entity entity, Vec3 velocity) { - entity.setDeltaMovement(velocity); - } - - @Override - public void simpleMove(Entity entity, MoverType movementType, Vec3 movement) { - entity.move(movementType, movement); - } - - @Override - public void setNoGravity(Entity entity, boolean noGravity) { - entity.setNoGravity(noGravity); - } - - @Override - public float getYaw(Entity entity) { - return entity.getYRot(); - } - - @Override - public void rotateYaw(Entity entity, float amount) { - entity.setYRot(entity.getYRot() + amount); - } - - @Override - public void setAngularVelocityYaw(Entity entity, Vector3f angle) { - } - - @Override - @ClientOnly - public void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta) { - matrices.mulPose(Axis.YP.rotationDegrees(180f - entity.getViewYRot(tickDelta))); - matrices.mulPose(Axis.XP.rotationDegrees(entity.getViewXRot(tickDelta))); - } + INSTANCE; + + @Override + public void init() { + } + + @Override + public boolean isPresent() { + return false; + } + + @Override + public void setVelocity(Entity entity, Vec3 velocity) { + entity.setDeltaMovement(velocity); + } + + @Override + public void simpleMove(Entity entity, MoverType movementType, Vec3 movement) { + entity.move(movementType, movement); + } + + @Override + public void setNoGravity(Entity entity, boolean noGravity) { + entity.setNoGravity(noGravity); + } + + @Override + public float getYaw(Entity entity) { + return entity.getYRot(); + } + + @Override + public void rotateYaw(Entity entity, float amount) { + entity.setYRot(entity.getYRot() + amount); + } + + @Override + public void setAngularVelocityYaw(Entity entity, Vector3f angle) { + } + + @Override + @ClientOnly + public void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta) { + matrices.mulPose(Axis.YP.rotationDegrees(180f - entity.getViewYRot(tickDelta))); + matrices.mulPose(Axis.XP.rotationDegrees(entity.getViewXRot(tickDelta))); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/CorePhysicsEntityMixin.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/CorePhysicsEntityMixin.java index 114142d6..b37f70fa 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/CorePhysicsEntityMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/CorePhysicsEntityMixin.java @@ -20,41 +20,41 @@ @Mixin(value = CorePhysicsEntity.class, remap = false) @SuppressWarnings("UnresolvedMixinReference") public abstract class CorePhysicsEntityMixin extends PathfinderMob implements EntityPhysicsElement { - private final EntityRigidBody rigidBody = new EntityRigidBody(this); - - protected CorePhysicsEntityMixin(EntityType entityType, Level world) { - super(entityType, world); - } - - @Inject(method = "", at = @At("TAIL")) - private void setupRigidBody(EntityType type, Level world, CallbackInfo ci) { - rigidBody.setDragCoefficient(0.001f); - rigidBody.setMass(1.5f); - rigidBody.setProtectGravity(true); - rigidBody.setGravity(new Vector3f(0, -16.8f, 0)); - rigidBody.setDragType(ElementRigidBody.DragType.NONE); - } - - @Inject(method = {"tick", "method_5773"}, at = @At("TAIL")) - private void checkBlockCollisions(CallbackInfo ci) { - // Rayon normally prevents this call, as it's called in move() and Rayon yeets move() - tryCheckInsideBlocks(); - } - - @Override - public EntityRigidBody getRigidBody() { - return rigidBody; - } - - @Override - public MinecraftShape.Convex createShape() { - return new MinecraftShape.Convex(RayonUtil.getShiftedMeshOf( - Convert.toBullet(getBoundingBox().contract(0, 0.1, 0)) - )); - } - - @Override - protected AABB makeBoundingBox() { - return super.makeBoundingBox().expandTowards(0, 0.1, 0); - } + private final EntityRigidBody rigidBody = new EntityRigidBody(this); + + protected CorePhysicsEntityMixin(EntityType entityType, Level world) { + super(entityType, world); + } + + @Inject(method = "", at = @At("TAIL")) + private void setupRigidBody(EntityType type, Level world, CallbackInfo ci) { + rigidBody.setDragCoefficient(0.001f); + rigidBody.setMass(1.5f); + rigidBody.setProtectGravity(true); + rigidBody.setGravity(new Vector3f(0, -16.8f, 0)); + rigidBody.setDragType(ElementRigidBody.DragType.NONE); + } + + @Inject(method = {"tick", "method_5773"}, at = @At("TAIL")) + private void checkBlockCollisions(CallbackInfo ci) { + // Rayon normally prevents this call, as it's called in move() and Rayon yeets move() + tryCheckInsideBlocks(); + } + + @Override + public EntityRigidBody getRigidBody() { + return rigidBody; + } + + @Override + public MinecraftShape.Convex createShape() { + return new MinecraftShape.Convex(RayonUtil.getShiftedMeshOf( + Convert.toBullet(getBoundingBox().contract(0, 0.1, 0)) + )); + } + + @Override + protected AABB makeBoundingBox() { + return super.makeBoundingBox().expandTowards(0, 0.1, 0); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/TurretEntityMixin.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/TurretEntityMixin.java index 062d1c26..77ae5628 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/TurretEntityMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/mixin/TurretEntityMixin.java @@ -10,15 +10,15 @@ @Mixin(TurretEntity.class) public abstract class TurretEntityMixin extends CorePhysicsEntity implements EntityPhysicsElement { - public TurretEntityMixin(EntityType type, Level world) { - super(type, world); - } + public TurretEntityMixin(EntityType type, Level world) { + super(type, world); + } - // TODO: Custom shape -// @Override -// public MinecraftShape.Convex createShape() { -// return new MinecraftShape.Convex(Stream.of( -// RayonUtil.getShiftedMeshOf(Convert.toBullet(new Box(0, 0, 0, 1, 1, 0.75f))) -// ).flatMap(List::stream).toList()); -// } + // TODO: Custom shape +// @Override +// public MinecraftShape.Convex createShape() { +// return new MinecraftShape.Convex(Stream.of( +// RayonUtil.getShiftedMeshOf(Convert.toBullet(new Box(0, 0, 0, 1, 1, 0.75f))) +// ).flatMap(List::stream).toList()); +// } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/rayon/present/RayonIntegrationPresent.java b/src/main/java/com/fusionflux/portalcubed/compat/rayon/present/RayonIntegrationPresent.java index d3fe4b1d..b6ca6b5f 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/rayon/present/RayonIntegrationPresent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/rayon/present/RayonIntegrationPresent.java @@ -12,85 +12,85 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class RayonIntegrationPresent implements RayonIntegration { - private static final Vector3f UP = new Vector3f(0, 1, 0); + private static final Vector3f UP = new Vector3f(0, 1, 0); - @Override - public void init() { - } + @Override + public void init() { + } - @Override - public boolean isPresent() { - return true; - } + @Override + public boolean isPresent() { + return true; + } - @Override - public void setVelocity(Entity entity, Vec3 velocity) { - if (entity instanceof EntityPhysicsElement physicsElement) { - physicsElement.getRigidBody().setLinearVelocity(Convert.toBullet(velocity.scale(14.5))); - } else { - entity.setDeltaMovement(velocity); - } - } + @Override + public void setVelocity(Entity entity, Vec3 velocity) { + if (entity instanceof EntityPhysicsElement physicsElement) { + physicsElement.getRigidBody().setLinearVelocity(Convert.toBullet(velocity.scale(14.5))); + } else { + entity.setDeltaMovement(velocity); + } + } - @Override - public void simpleMove(Entity entity, MoverType movementType, Vec3 movement) { - if (entity instanceof EntityPhysicsElement physicsElement) { - physicsElement.getRigidBody().setPhysicsLocation( - physicsElement.getRigidBody() - .getPhysicsLocation(new Vector3f()) - .add(Convert.toBullet(movement)) - ); - } else { - entity.move(movementType, movement); - } - } + @Override + public void simpleMove(Entity entity, MoverType movementType, Vec3 movement) { + if (entity instanceof EntityPhysicsElement physicsElement) { + physicsElement.getRigidBody().setPhysicsLocation( + physicsElement.getRigidBody() + .getPhysicsLocation(new Vector3f()) + .add(Convert.toBullet(movement)) + ); + } else { + entity.move(movementType, movement); + } + } - @Override - public void setNoGravity(Entity entity, boolean noGravity) { - if (entity instanceof EntityPhysicsElement physicsElement) { - physicsElement.getRigidBody().setKinematic(noGravity); - } - entity.setNoGravity(noGravity); - } + @Override + public void setNoGravity(Entity entity, boolean noGravity) { + if (entity instanceof EntityPhysicsElement physicsElement) { + physicsElement.getRigidBody().setKinematic(noGravity); + } + entity.setNoGravity(noGravity); + } - @Override - public float getYaw(Entity entity) { - if (entity instanceof EntityPhysicsElement physicsElement) { - final com.jme3.math.Quaternion q = physicsElement.getRigidBody().getPhysicsRotation(null); - // https://stackoverflow.com/a/5783030/8840278 - return (float)Math.toDegrees(2 * Math.acos(q.getW())); - } - return entity.getYRot(); - } + @Override + public float getYaw(Entity entity) { + if (entity instanceof EntityPhysicsElement physicsElement) { + final com.jme3.math.Quaternion q = physicsElement.getRigidBody().getPhysicsRotation(null); + // https://stackoverflow.com/a/5783030/8840278 + return (float)Math.toDegrees(2 * Math.acos(q.getW())); + } + return entity.getYRot(); + } - @Override - public void rotateYaw(Entity entity, float amount) { - if (entity instanceof EntityPhysicsElement physicsElement) { - physicsElement.getRigidBody().setPhysicsRotation( - physicsElement.getRigidBody() - .getPhysicsRotation(null) - .mult(new com.jme3.math.Quaternion().fromAngleNormalAxis((float)Math.toRadians(amount), UP)) - ); - } else { - entity.setYRot(entity.getYRot() + amount); - } - } + @Override + public void rotateYaw(Entity entity, float amount) { + if (entity instanceof EntityPhysicsElement physicsElement) { + physicsElement.getRigidBody().setPhysicsRotation( + physicsElement.getRigidBody() + .getPhysicsRotation(null) + .mult(new com.jme3.math.Quaternion().fromAngleNormalAxis((float)Math.toRadians(amount), UP)) + ); + } else { + entity.setYRot(entity.getYRot() + amount); + } + } - @Override - public void setAngularVelocityYaw(Entity entity, org.joml.Vector3f angle) { - if (entity instanceof EntityPhysicsElement physicsElement) { - physicsElement.getRigidBody().setAngularVelocity(Convert.toBullet(angle)); - } - } + @Override + public void setAngularVelocityYaw(Entity entity, org.joml.Vector3f angle) { + if (entity instanceof EntityPhysicsElement physicsElement) { + physicsElement.getRigidBody().setAngularVelocity(Convert.toBullet(angle)); + } + } - @Override - @ClientOnly - public void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta) { - if (entity instanceof EntityPhysicsElement physicsElement) { - matrices.mulPose(Convert.toMinecraft(physicsElement.getPhysicsRotation(new com.jme3.math.Quaternion(), tickDelta))); - } else { - RayonIntegrationAbsent.INSTANCE.multiplyMatrices(matrices, entity, tickDelta); - } - } + @Override + @ClientOnly + public void multiplyMatrices(PoseStack matrices, Entity entity, float tickDelta) { + if (entity instanceof EntityPhysicsElement physicsElement) { + matrices.mulPose(Convert.toMinecraft(physicsElement.getPhysicsRotation(new com.jme3.math.Quaternion(), tickDelta))); + } else { + RayonIntegrationAbsent.INSTANCE.multiplyMatrices(matrices, entity, tickDelta); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/sodium/SodiumIntegration.java b/src/main/java/com/fusionflux/portalcubed/compat/sodium/SodiumIntegration.java index 3ed1106d..4dca3610 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/sodium/SodiumIntegration.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/sodium/SodiumIntegration.java @@ -9,26 +9,26 @@ import org.quiltmc.loader.api.QuiltLoader; public interface SodiumIntegration { - SodiumIntegration INSTANCE = Util.make(() -> { - if (!QuiltLoader.isModLoaded("sodium")) { - return SodiumIntegrationAbsent.INSTANCE; - } + SodiumIntegration INSTANCE = Util.make(() -> { + if (!QuiltLoader.isModLoaded("sodium")) { + return SodiumIntegrationAbsent.INSTANCE; + } - try { - Class spriteContentsEx = Class.forName("me.jellysquid.mods.sodium.client.render.texture.SpriteContentsExtended"); - spriteContentsEx.getDeclaredMethod("sodium$setActive", Boolean.TYPE); - return SodiumPresentHolder.create(); - } catch (ClassNotFoundException | NoSuchMethodException e) { - PortalCubed.LOGGER.error("Portal Cubed has outdated Sodium compatibility! Some things may not work properly."); - return SodiumIntegrationAbsent.INSTANCE; - } - }); + try { + Class spriteContentsEx = Class.forName("me.jellysquid.mods.sodium.client.render.texture.SpriteContentsExtended"); + spriteContentsEx.getDeclaredMethod("sodium$setActive", Boolean.TYPE); + return SodiumPresentHolder.create(); + } catch (ClassNotFoundException | NoSuchMethodException e) { + PortalCubed.LOGGER.error("Portal Cubed has outdated Sodium compatibility! Some things may not work properly."); + return SodiumIntegrationAbsent.INSTANCE; + } + }); - void markSpriteActive(SpriteContents sprite); + void markSpriteActive(SpriteContents sprite); - class SodiumPresentHolder { - private static SodiumIntegration create() { - return new SodiumIntegrationPresent(); - } - } + class SodiumPresentHolder { + private static SodiumIntegration create() { + return new SodiumIntegrationPresent(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/sodium/absent/SodiumIntegrationAbsent.java b/src/main/java/com/fusionflux/portalcubed/compat/sodium/absent/SodiumIntegrationAbsent.java index 049f7e7f..c9482fd0 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/sodium/absent/SodiumIntegrationAbsent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/sodium/absent/SodiumIntegrationAbsent.java @@ -4,9 +4,9 @@ import net.minecraft.client.renderer.texture.SpriteContents; public enum SodiumIntegrationAbsent implements SodiumIntegration { - INSTANCE; + INSTANCE; - @Override - public void markSpriteActive(SpriteContents sprite) { - } + @Override + public void markSpriteActive(SpriteContents sprite) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/compat/sodium/present/SodiumIntegrationPresent.java b/src/main/java/com/fusionflux/portalcubed/compat/sodium/present/SodiumIntegrationPresent.java index 385492b3..ac9c0cd0 100644 --- a/src/main/java/com/fusionflux/portalcubed/compat/sodium/present/SodiumIntegrationPresent.java +++ b/src/main/java/com/fusionflux/portalcubed/compat/sodium/present/SodiumIntegrationPresent.java @@ -6,10 +6,10 @@ import net.minecraft.client.renderer.texture.SpriteContents; public class SodiumIntegrationPresent implements SodiumIntegration { - @Override - public void markSpriteActive(SpriteContents sprite) { - if (sprite instanceof SpriteContentsExtended extended) { - extended.sodium$setActive(true); - } - } + @Override + public void markSpriteActive(SpriteContents sprite) { + if (sprite instanceof SpriteContentsExtended extended) { + extended.sodium$setActive(true); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedBlockLoot.java b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedBlockLoot.java index 2fae1954..3006bc84 100644 --- a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedBlockLoot.java +++ b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedBlockLoot.java @@ -14,25 +14,25 @@ import net.minecraft.world.level.storage.loot.predicates.LootItemBlockStatePropertyCondition; public class PortalCubedBlockLoot extends PortalCubedLootProvider { - public PortalCubedBlockLoot(FabricDataOutput output) { - super(output, LootContextParamSets.BLOCK); - } + public PortalCubedBlockLoot(FabricDataOutput output) { + super(output, LootContextParamSets.BLOCK); + } - @Override - public void buildLootTables() { - dropSelfWhenProperty(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER, ExcursionFunnelEmitterBlock.QUADRANT, "1"); - } + @Override + public void buildLootTables() { + dropSelfWhenProperty(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER, ExcursionFunnelEmitterBlock.QUADRANT, "1"); + } - public void dropSelfWhenProperty(Block block, Property property, String value) { - tables.put(block.getLootTable(), LootTable.lootTable() - .withPool(LootPool.lootPool() - .when(LootItemBlockStatePropertyCondition.hasBlockStateProperties(block) - .setProperties(StatePropertiesPredicate.Builder.properties() - .hasProperty(property, value) - ) - ) - .add(LootItem.lootTableItem(block)) - ) - ); - } + public void dropSelfWhenProperty(Block block, Property property, String value) { + tables.put(block.getLootTable(), LootTable.lootTable() + .withPool(LootPool.lootPool() + .when(LootItemBlockStatePropertyCondition.hasBlockStateProperties(block) + .setProperties(StatePropertiesPredicate.Builder.properties() + .hasProperty(property, value) + ) + ) + .add(LootItem.lootTableItem(block)) + ) + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedDatagen.java b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedDatagen.java index bd35a2fb..f01ea4ef 100644 --- a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedDatagen.java +++ b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedDatagen.java @@ -5,11 +5,11 @@ import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator.Pack; public class PortalCubedDatagen implements DataGeneratorEntrypoint { - @Override - public void onInitializeDataGenerator(FabricDataGenerator generator) { - Pack pack = generator.createPack(); - pack.addProvider(PortalCubedEntityLoot::new); - pack.addProvider(PortalCubedBlockLoot::new); - pack.addProvider(PortalCubedModels::new); - } + @Override + public void onInitializeDataGenerator(FabricDataGenerator generator) { + Pack pack = generator.createPack(); + pack.addProvider(PortalCubedEntityLoot::new); + pack.addProvider(PortalCubedBlockLoot::new); + pack.addProvider(PortalCubedModels::new); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedEntityLoot.java b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedEntityLoot.java index 0f5d189d..3f3967b2 100644 --- a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedEntityLoot.java +++ b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedEntityLoot.java @@ -14,50 +14,50 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; public class PortalCubedEntityLoot extends PortalCubedLootProvider { - public PortalCubedEntityLoot(FabricDataOutput output) { - super(output, LootContextParamSets.ENTITY); - } + public PortalCubedEntityLoot(FabricDataOutput output) { + super(output, LootContextParamSets.ENTITY); + } - @Override - public void buildLootTables() { - keepName(PortalCubedEntities.STORAGE_CUBE, PortalCubedItems.STORAGE_CUBE); - keepName(PortalCubedEntities.COMPANION_CUBE, PortalCubedItems.COMPANION_CUBE); - keepName(PortalCubedEntities.REDIRECTION_CUBE, PortalCubedItems.REDIRECTION_CUBE); - keepName(PortalCubedEntities.SCHRODINGER_CUBE, PortalCubedItems.SCHRODINGER_CUBE); - keepName(PortalCubedEntities.RADIO, PortalCubedItems.RADIO); - keepName(PortalCubedEntities.OLD_AP_CUBE, PortalCubedItems.OLD_AP_CUBE); - keepName(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, PortalCubedItems.PORTAL_1_COMPANION_CUBE); - keepName(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, PortalCubedItems.PORTAL_1_STORAGE_CUBE); - keepName(PortalCubedEntities.BEANS, PortalCubedItems.BEANS); - keepName(PortalCubedEntities.MUG, PortalCubedItems.MUG); - keepName(PortalCubedEntities.JUG, PortalCubedItems.JUG); - keepName(PortalCubedEntities.COMPUTER, PortalCubedItems.COMPUTER); - keepName(PortalCubedEntities.CHAIR, PortalCubedItems.CHAIR); - keepName(PortalCubedEntities.LIL_PINEAPPLE, PortalCubedItems.LIL_PINEAPPLE); - keepName(PortalCubedEntities.HOOPY, PortalCubedItems.HOOPY); - keepName(PortalCubedEntities.CORE_FRAME, PortalCubedItems.CORE_FRAME); - keepName(PortalCubedEntities.ANGER_CORE, PortalCubedItems.ANGER_CORE); - keepName(PortalCubedEntities.MORALITY_CORE, PortalCubedItems.MORALITY_CORE); - keepName(PortalCubedEntities.CAKE_CORE, PortalCubedItems.CAKE_CORE); - keepName(PortalCubedEntities.CURIOSITY_CORE, PortalCubedItems.CURIOSITY_CORE); - keepName(PortalCubedEntities.SPACE_CORE, PortalCubedItems.SPACE_CORE); - keepName(PortalCubedEntities.FACT_CORE, PortalCubedItems.FACT_CORE); - keepName(PortalCubedEntities.ADVENTURE_CORE, PortalCubedItems.ADVENTURE_CORE); - keepName(PortalCubedEntities.ENERGY_PELLET, PortalCubedItems.ENERGY_PELLET); - keepName(PortalCubedEntities.TURRET, PortalCubedItems.TURRET); - } + @Override + public void buildLootTables() { + keepName(PortalCubedEntities.STORAGE_CUBE, PortalCubedItems.STORAGE_CUBE); + keepName(PortalCubedEntities.COMPANION_CUBE, PortalCubedItems.COMPANION_CUBE); + keepName(PortalCubedEntities.REDIRECTION_CUBE, PortalCubedItems.REDIRECTION_CUBE); + keepName(PortalCubedEntities.SCHRODINGER_CUBE, PortalCubedItems.SCHRODINGER_CUBE); + keepName(PortalCubedEntities.RADIO, PortalCubedItems.RADIO); + keepName(PortalCubedEntities.OLD_AP_CUBE, PortalCubedItems.OLD_AP_CUBE); + keepName(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, PortalCubedItems.PORTAL_1_COMPANION_CUBE); + keepName(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, PortalCubedItems.PORTAL_1_STORAGE_CUBE); + keepName(PortalCubedEntities.BEANS, PortalCubedItems.BEANS); + keepName(PortalCubedEntities.MUG, PortalCubedItems.MUG); + keepName(PortalCubedEntities.JUG, PortalCubedItems.JUG); + keepName(PortalCubedEntities.COMPUTER, PortalCubedItems.COMPUTER); + keepName(PortalCubedEntities.CHAIR, PortalCubedItems.CHAIR); + keepName(PortalCubedEntities.LIL_PINEAPPLE, PortalCubedItems.LIL_PINEAPPLE); + keepName(PortalCubedEntities.HOOPY, PortalCubedItems.HOOPY); + keepName(PortalCubedEntities.CORE_FRAME, PortalCubedItems.CORE_FRAME); + keepName(PortalCubedEntities.ANGER_CORE, PortalCubedItems.ANGER_CORE); + keepName(PortalCubedEntities.MORALITY_CORE, PortalCubedItems.MORALITY_CORE); + keepName(PortalCubedEntities.CAKE_CORE, PortalCubedItems.CAKE_CORE); + keepName(PortalCubedEntities.CURIOSITY_CORE, PortalCubedItems.CURIOSITY_CORE); + keepName(PortalCubedEntities.SPACE_CORE, PortalCubedItems.SPACE_CORE); + keepName(PortalCubedEntities.FACT_CORE, PortalCubedItems.FACT_CORE); + keepName(PortalCubedEntities.ADVENTURE_CORE, PortalCubedItems.ADVENTURE_CORE); + keepName(PortalCubedEntities.ENERGY_PELLET, PortalCubedItems.ENERGY_PELLET); + keepName(PortalCubedEntities.TURRET, PortalCubedItems.TURRET); + } - public void add(EntityType type, Builder builder) { - tables.put(type.getDefaultLootTable(), builder); - } + public void add(EntityType type, Builder builder) { + tables.put(type.getDefaultLootTable(), builder); + } - public void keepName(EntityType type, ItemLike item) { - add(type, LootTable.lootTable() - .withPool(LootPool.lootPool() - .add(LootItem.lootTableItem(item) - .apply(CopyNameFunction.copyName(NameSource.THIS)) - ) - ) - ); - } + public void keepName(EntityType type, ItemLike item) { + add(type, LootTable.lootTable() + .withPool(LootPool.lootPool() + .add(LootItem.lootTableItem(item) + .apply(CopyNameFunction.copyName(NameSource.THIS)) + ) + ) + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedLootProvider.java b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedLootProvider.java index 9d52e244..36a426c6 100644 --- a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedLootProvider.java +++ b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedLootProvider.java @@ -12,17 +12,17 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; public abstract class PortalCubedLootProvider extends SimpleFabricLootTableProvider { - protected final Map tables = new HashMap<>(); + protected final Map tables = new HashMap<>(); - public PortalCubedLootProvider(FabricDataOutput output, LootContextParamSet lootContextType) { - super(output, lootContextType); - } + public PortalCubedLootProvider(FabricDataOutput output, LootContextParamSet lootContextType) { + super(output, lootContextType); + } - @Override - public void generate(BiConsumer out) { - buildLootTables(); - tables.forEach(out); - } + @Override + public void generate(BiConsumer out) { + buildLootTables(); + tables.forEach(out); + } - public abstract void buildLootTables(); + public abstract void buildLootTables(); } diff --git a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedModels.java b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedModels.java index fdd7fdfa..f8e83f7d 100644 --- a/src/main/java/com/fusionflux/portalcubed/data/PortalCubedModels.java +++ b/src/main/java/com/fusionflux/portalcubed/data/PortalCubedModels.java @@ -17,69 +17,69 @@ import net.minecraft.world.level.ItemLike; public class PortalCubedModels extends FabricModelProvider { - public PortalCubedModels(FabricDataOutput output) { - super(output); - } + public PortalCubedModels(FabricDataOutput output) { + super(output); + } - @Override - public void generateBlockStateModels(BlockModelGenerators gen) { - gen.blockStateOutput.accept(excursionFunnelEmitter()); - gen.skipAutoItemBlock(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER); + @Override + public void generateBlockStateModels(BlockModelGenerators gen) { + gen.blockStateOutput.accept(excursionFunnelEmitter()); + gen.skipAutoItemBlock(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER); - gen.skipAutoItemBlock(PortalCubedBlocks.HLB_EMITTER_BLOCK); - gen.blockStateOutput.accept( - MultiVariantGenerator.multiVariant(PortalCubedBlocks.HLB_EMITTER_BLOCK) - .with(BlockModelGenerators.createFacingDispatch()) - .with(PropertyDispatch.properties(HardLightBridgePart.EDGE, HardLightBridgeEmitterBlock.POWERED) - .generate((edge, powered) -> { - String power = powered ? "on" : "off"; - String model = "block/light_bridge_emitter_" + edge + "_edge_" + power; - ResourceLocation id = PortalCubed.id(model); - return Variant.variant().with(VariantProperties.MODEL, id); - }) - ) - ); - gen.blockStateOutput.accept( - MultiVariantGenerator.multiVariant(PortalCubedBlocks.HLB_BLOCK) - .with(BlockModelGenerators.createFacingDispatch()) - .with(PropertyDispatch.property(HardLightBridgePart.EDGE) - .generate(edge -> { - ResourceLocation id = PortalCubed.id("block/light_bridge_" + edge); - return Variant.variant().with(VariantProperties.MODEL, id); - }) - ) - ); - } + gen.skipAutoItemBlock(PortalCubedBlocks.HLB_EMITTER_BLOCK); + gen.blockStateOutput.accept( + MultiVariantGenerator.multiVariant(PortalCubedBlocks.HLB_EMITTER_BLOCK) + .with(BlockModelGenerators.createFacingDispatch()) + .with(PropertyDispatch.properties(HardLightBridgePart.EDGE, HardLightBridgeEmitterBlock.POWERED) + .generate((edge, powered) -> { + String power = powered ? "on" : "off"; + String model = "block/light_bridge_emitter_" + edge + "_edge_" + power; + ResourceLocation id = PortalCubed.id(model); + return Variant.variant().with(VariantProperties.MODEL, id); + }) + ) + ); + gen.blockStateOutput.accept( + MultiVariantGenerator.multiVariant(PortalCubedBlocks.HLB_BLOCK) + .with(BlockModelGenerators.createFacingDispatch()) + .with(PropertyDispatch.property(HardLightBridgePart.EDGE) + .generate(edge -> { + ResourceLocation id = PortalCubed.id("block/light_bridge_" + edge); + return Variant.variant().with(VariantProperties.MODEL, id); + }) + ) + ); + } - protected BlockStateGenerator excursionFunnelEmitter() { - return MultiVariantGenerator.multiVariant(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER) - .with( - PropertyDispatch.properties(ExcursionFunnelEmitterBlock.QUADRANT, ExcursionFunnelEmitterBlock.MODE) - .generate(this::generateEmitterVariant) - ) - .with(BlockModelGenerators.createFacingDispatch()); - } + protected BlockStateGenerator excursionFunnelEmitter() { + return MultiVariantGenerator.multiVariant(PortalCubedBlocks.EXCURSION_FUNNEL_EMITTER) + .with( + PropertyDispatch.properties(ExcursionFunnelEmitterBlock.QUADRANT, ExcursionFunnelEmitterBlock.MODE) + .generate(this::generateEmitterVariant) + ) + .with(BlockModelGenerators.createFacingDispatch()); + } - protected Variant generateEmitterVariant(int quadrant, Mode state) { - ResourceLocation id = PortalCubed.id("block/excursion_funnel_emitter_" + state.getSerializedName() + "_quadrant_" + quadrant); - return Variant.variant().with(VariantProperties.MODEL, id); - } + protected Variant generateEmitterVariant(int quadrant, Mode state) { + ResourceLocation id = PortalCubed.id("block/excursion_funnel_emitter_" + state.getSerializedName() + "_quadrant_" + quadrant); + return Variant.variant().with(VariantProperties.MODEL, id); + } - protected Variant generateTubeVariant(int quadrant, boolean reversed) { - String reversion = reversed ? "reversed_" : ""; - ResourceLocation id = PortalCubed.id("block/excursion_funnel_" + reversion + "quadrant_" + quadrant); - return Variant.variant().with(VariantProperties.MODEL, id); - } + protected Variant generateTubeVariant(int quadrant, boolean reversed) { + String reversion = reversed ? "reversed_" : ""; + ResourceLocation id = PortalCubed.id("block/excursion_funnel_" + reversion + "quadrant_" + quadrant); + return Variant.variant().with(VariantProperties.MODEL, id); + } - @Override - public void generateItemModels(ItemModelGenerators gen) { - } + @Override + public void generateItemModels(ItemModelGenerators gen) { + } - protected void inheritFrom(ItemLike item, ResourceLocation parent, ItemModelGenerators gen) { - gen.output.accept(ModelLocationUtils.getModelLocation(item.asItem()), () -> { - JsonObject json = new JsonObject(); - json.addProperty("parent", parent.toString()); - return json; - }); - } + protected void inheritFrom(ItemLike item, ResourceLocation parent, ItemModelGenerators gen) { + gen.output.accept(ModelLocationUtils.getModelLocation(item.asItem()), () -> { + JsonObject json = new JsonObject(); + json.addProperty("parent", parent.toString()); + return json; + }); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/AdventureCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/AdventureCoreEntity.java index d2bc6bd9..db245d8d 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/AdventureCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/AdventureCoreEntity.java @@ -7,21 +7,21 @@ public class AdventureCoreEntity extends CorePhysicsEntity { - public AdventureCoreEntity(EntityType type, Level world) { - super(type, world); - } + public AdventureCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.ADVENTURE_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 3429; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.ADVENTURE_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 3429; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/AngerCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/AngerCoreEntity.java index a25a91b7..22d30646 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/AngerCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/AngerCoreEntity.java @@ -7,21 +7,21 @@ public class AngerCoreEntity extends CorePhysicsEntity { - public AngerCoreEntity(EntityType type, Level world) { - super(type, world); - } + public AngerCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.ANGER_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 401; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.ANGER_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 401; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/BeansEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/BeansEntity.java index 799cb96b..6b5ad61c 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/BeansEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/BeansEntity.java @@ -5,8 +5,8 @@ import net.minecraft.world.level.Level; public class BeansEntity extends CorePhysicsEntity { - public BeansEntity(EntityType type, Level world) { - super(type, world); - } + public BeansEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/BlockCollisionLimiter.java b/src/main/java/com/fusionflux/portalcubed/entity/BlockCollisionLimiter.java index 3c4d5af5..ea344d97 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/BlockCollisionLimiter.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/BlockCollisionLimiter.java @@ -7,24 +7,24 @@ import java.util.UUID; public class BlockCollisionLimiter { - private final ThreadLocal> lastCollidingEntity = new ThreadLocal<>(); + private final ThreadLocal> lastCollidingEntity = new ThreadLocal<>(); - /** - * Written by chylex and onehalf - * Prevents handling collision for an entity multiple times if the entity is touching 2 or more blocks. - *

- * Because onEntityCollision is always called in succession for all blocks colliding with an entity, - * it is enough to compare if either the world time or the entity has changed since last call (on the same thread). - *

- * Returns true if the collision should be handled. - */ - public boolean check(Level world, Entity entity) { - long currentWorldTime = world.getGameTime(); - Tuple last = this.lastCollidingEntity.get(); - if (last == null || last.getA() != currentWorldTime || !last.getB().equals(entity.getUUID())) { - this.lastCollidingEntity.set(new Tuple<>(currentWorldTime, entity.getUUID())); - return true; - } - return false; - } + /** + * Written by chylex and onehalf + * Prevents handling collision for an entity multiple times if the entity is touching 2 or more blocks. + *

+ * Because onEntityCollision is always called in succession for all blocks colliding with an entity, + * it is enough to compare if either the world time or the entity has changed since last call (on the same thread). + *

+ * Returns true if the collision should be handled. + */ + public boolean check(Level world, Entity entity) { + long currentWorldTime = world.getGameTime(); + Tuple last = this.lastCollidingEntity.get(); + if (last == null || last.getA() != currentWorldTime || !last.getB().equals(entity.getUUID())) { + this.lastCollidingEntity.set(new Tuple<>(currentWorldTime, entity.getUUID())); + return true; + } + return false; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/CakeCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/CakeCoreEntity.java index 8de421dc..c58a9d01 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/CakeCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/CakeCoreEntity.java @@ -7,22 +7,22 @@ public class CakeCoreEntity extends CorePhysicsEntity { - public CakeCoreEntity(EntityType type, Level world) { - super(type, world); - } + public CakeCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.CAKE_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 2407; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.CAKE_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 2407; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/ChairEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/ChairEntity.java index e737a1a4..c1674339 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/ChairEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/ChairEntity.java @@ -10,19 +10,19 @@ import net.minecraft.world.level.Level; public class ChairEntity extends CorePhysicsEntity { - public ChairEntity(EntityType type, Level world) { - super(type, world); - } + public ChairEntity(EntityType type, Level world) { + super(type, world); + } - @Override - protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { - if (isVehicle() || level().isClientSide()) - return InteractionResult.PASS; - CorePhysicsEntity heldEntity = PortalCubedComponents.HOLDER_COMPONENT.get(player).entityBeingHeld(); - if (heldEntity == this) - return InteractionResult.PASS; + @Override + protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { + if (isVehicle() || level().isClientSide()) + return InteractionResult.PASS; + CorePhysicsEntity heldEntity = PortalCubedComponents.HOLDER_COMPONENT.get(player).entityBeingHeld(); + if (heldEntity == this) + return InteractionResult.PASS; - player.startRiding(this); - return InteractionResult.SUCCESS; - } + player.startRiding(this); + return InteractionResult.SUCCESS; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/CompanionCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/CompanionCubeEntity.java index 3d25a3dd..2b7a2764 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/CompanionCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/CompanionCubeEntity.java @@ -8,31 +8,31 @@ public class CompanionCubeEntity extends StorageCubeEntity { - public CompanionCubeEntity(EntityType type, Level world) { - super(type, world); - } - - private int t = 1500; - - @Override - public void tick() { - super.tick(); - if (!this.level().isClientSide) { - if (t == 1500) { - level().playSound(null, this, PortalCubedSounds.COMPANION_CUBE_AMBIANCE_EVENT, this.getSoundSource(), 1f, 1f); - } - t--; - if (t == 0) { - t = 1500; - } - - } - } - - @Override - public void recreateFromPacket(ClientboundAddEntityPacket packet) { - t = 40; - super.recreateFromPacket(packet); - } + public CompanionCubeEntity(EntityType type, Level world) { + super(type, world); + } + + private int t = 1500; + + @Override + public void tick() { + super.tick(); + if (!this.level().isClientSide) { + if (t == 1500) { + level().playSound(null, this, PortalCubedSounds.COMPANION_CUBE_AMBIANCE_EVENT, this.getSoundSource(), 1f, 1f); + } + t--; + if (t == 0) { + t = 1500; + } + + } + } + + @Override + public void recreateFromPacket(ClientboundAddEntityPacket packet) { + t = 40; + super.recreateFromPacket(packet); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/ComputerEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/ComputerEntity.java index dd9d6019..d8bfe692 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/ComputerEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/ComputerEntity.java @@ -5,8 +5,8 @@ import net.minecraft.world.level.Level; public class ComputerEntity extends CorePhysicsEntity { - public ComputerEntity(EntityType type, Level world) { - super(type, world); - } + public ComputerEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/CoreFrameEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/CoreFrameEntity.java index 83176409..80297f5f 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/CoreFrameEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/CoreFrameEntity.java @@ -6,8 +6,8 @@ public class CoreFrameEntity extends CorePhysicsEntity { - public CoreFrameEntity(EntityType type, Level world) { - super(type, world); - } + public CoreFrameEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/CorePhysicsEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/CorePhysicsEntity.java index f1d86d6d..82973f55 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/CorePhysicsEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/CorePhysicsEntity.java @@ -58,414 +58,414 @@ // TODO: Extend LivingEntity public class CorePhysicsEntity extends PathfinderMob implements Fizzleable { - private float fizzleProgress = 0f; - private boolean fizzling = false; - - public CorePhysicsEntity(EntityType type, Level world) { - super(type, world); - } - - private boolean canUsePortals = true; - private boolean hasCollided; - private int timeSinceLastSound; - - private List intermediaryPortals = List.of(); - - public Vec3 lastPos = this.position(); - - private final Vec3 offsetHeight = new Vec3(0, this.getBbHeight() / 2, 0); - - private boolean locked = false; - private boolean onButton = false; - private Optional holder = Optional.empty(); - - @Override - public boolean canBeCollidedWith() { - return canUsePortals; - } - - @Override - public boolean canCollideWith(Entity other) { - return other != this && canBeCollidedWith() && other instanceof LivingEntity && other.isAlive(); - } - - @Override - public boolean isPushable() { - return false; - } - - @Override - public boolean isInvulnerableTo(DamageSource source) { - if (source.isCreativePlayer() || source.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) - return false; - if (!(source.getEntity() instanceof Player player)) - return true; - return !player.getItemInHand(InteractionHand.MAIN_HAND).is(PortalCubedItems.WRENCHES); - } - - @Override - public boolean hurt(DamageSource source, float amount) { - if (!level().isClientSide && !isInvulnerableTo(source) && !isRemoved()) { - if (!source.isCreativePlayer()) { - dropAllDeathLoot(source); - } - discard(); - return true; - } - return false; - } - - @Override - @NotNull - protected InteractionResult mobInteract(Player player, InteractionHand hand) { - return player.isShiftKeyDown() ? toggleLock(player, hand) : physicsEntityInteraction(player, hand); - } - - protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { - return InteractionResult.PASS; - } - - private InteractionResult toggleLock(Player player, InteractionHand hand) { - if (level().isClientSide() || !player.isCreative()) - return InteractionResult.PASS; - ItemStack stack = player.getItemInHand(hand); - if (!stack.is(PortalCubedItems.HAMMER)) - return InteractionResult.PASS; - // toggle - Boolean locked = !entityData.get(LOCKED); - entityData.set(LOCKED, locked); - - if (locked) { - getHolderUUID().ifPresent(uuid -> { - Player holder = level().getPlayerByUUID(uuid); - if (holder != null) { - PortalCubedComponents.HOLDER_COMPONENT.get(holder).stopHolding(); - } - }); - } - - player.displayClientMessage(Component.translatable("portalcubed.physics_entity.locked." + locked), true); - return InteractionResult.SUCCESS; - } - - @Override - public boolean shouldShowName() { - return false; - } - - @Override - public boolean isCustomNameVisible() { - return false; - } - - @Override - @NotNull - public Component getDisplayName() { - return super.getDisplayName().plainCopy(); - } - - @Nullable - @Override - public ItemStack getPickResult() { - ItemStack stack = super.getPickResult(); - if (stack != null && this.hasCustomName()) - stack.setHoverName(getDisplayName()); - return stack; - } - - @Override - public void recreateFromPacket(ClientboundAddEntityPacket packet) { - super.recreateFromPacket(packet); - this.setDiscardFriction(true); - } - - private static final EntityDataAccessor> HOLDER_UUID = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.OPTIONAL_UUID); - private static final EntityDataAccessor ON_BUTTON = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.BOOLEAN); - public static final EntityDataAccessor LOCKED = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.BOOLEAN); - - @Override - protected void defineSynchedData() { - super.defineSynchedData(); - this.getEntityData().define(HOLDER_UUID, Optional.empty()); - this.getEntityData().define(ON_BUTTON, false); - this.getEntityData().define(LOCKED, false); - } - - @Override - public void onSyncedDataUpdated(EntityDataAccessor key) { - super.onSyncedDataUpdated(key); - if (LOCKED.equals(key)) { - this.locked = entityData.get(LOCKED); - } else if (ON_BUTTON.equals(key)) { - this.onButton = entityData.get(ON_BUTTON); - } else if (HOLDER_UUID.equals(key)) { - this.holder = entityData.get(HOLDER_UUID); - } - } - - public Optional getHolderUUID() { - return holder; - } - - public void setHolderUUID(Optional uuid) { - entityData.set(HOLDER_UUID, uuid); - } - - public boolean isOnButton() { - return onButton; - } - - public void setOnButton(boolean on) { - entityData.set(ON_BUTTON, on); - } - - public boolean isLocked() { - return locked; - } - - public void setRotYaw(float yaw) { - this.yBodyRot = yaw; - } - - @Override - public boolean canChangeDimensions() { - return canUsePortals; - } - - @Override - public void tick() { - super.tick(); - UUID holder = this.holder.orElse(null); - final boolean isBeingHeld = holder != null && !fizzling; - timeSinceLastSound++; - this.hasImpulse = true; - canUsePortals = holder == null; - this.lastPos = this.position(); - this.setDiscardFriction(!this.onGround() && !((EntityExt) this).isInFunnel()); - if (isBeingHeld) { - Player player = (Player) ((LevelExt) level()).getEntityByUuid(holder); - if (player != null && player.isAlive()) { - Vec3 eyes = player.getEyePosition(0); - double distance = 1.5; - canUsePortals = false; - Vec3 rotation = this.getPlayerRotationVector(player.getXRot(), player.getYRot()); - Vec3 rotatedOffset = RotationUtil.vecPlayerToWorld(offsetHeight, GravityChangerAPI.getGravityDirection(this)); - Vec3 target = eyes.add( - (rotation.x * distance) - rotatedOffset.x, - (rotation.y * distance) - rotatedOffset.y, - (rotation.z * distance) - rotatedOffset.z - ); - final AdvancedEntityRaycast.Result raycastResult = PortalDirectionUtils.raycast(level(), new ClipContext( - eyes, target, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, this - )); - final Vec3 holdPos = raycastResult.finalHit().getLocation(); - if (!level().isClientSide) { - GravityChangerAPI.addGravity(this, new Gravity(GravityChangerAPI.getGravityDirection(player), 10, 1, "player_interaction")); - } - this.fallDistance = 0; - if (RayonIntegration.INSTANCE.isPresent()) { - final float destYaw = Mth.wrapDegrees(player.yHeadRot + 180); - final float multiplier = (destYaw > 120 || destYaw < 0) ? -1 : 1; - final float yawDelta = Mth.wrapDegrees( - Mth.wrapDegrees(RayonIntegration.INSTANCE.getYaw(this) * multiplier) - destYaw - ); - RayonIntegration.INSTANCE.rotateYaw(this, yawDelta); - RayonIntegration.INSTANCE.setAngularVelocityYaw(this, new Vector3f(0, yawDelta, 0)); - } else { - setYRot(player.yHeadRot); - setYHeadRot(player.yHeadRot); - setYBodyRot(player.yHeadRot); - } - final List portals = raycastResult.rays() - .stream() - .map(AdvancedEntityRaycast.Result.Ray::hit) - .filter(h -> h instanceof EntityHitResult) - .map(h -> ((EntityHitResult)h).getEntity().getUUID()) - .toList(); - if (!portals.equals(intermediaryPortals)) { - intermediaryPortals = portals; - moveTo(holdPos); - } else { - final Vec3 movement = RotationUtil.vecWorldToPlayer(holdPos.subtract(position()), GravityChangerAPI.getGravityDirection(player)); - if (RayonIntegration.INSTANCE.isPresent()) { - RayonIntegration.INSTANCE.setVelocity(this, movement); - } - RayonIntegration.INSTANCE.simpleMove(this, MoverType.PLAYER, movement); - } - if (position().distanceToSqr(holdPos) > 2 * 2) { - PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding(); - } - } else { - if (player != null) { - setHolderUUID(Optional.empty()); - } - canUsePortals = true; - } - RayonIntegration.INSTANCE.setNoGravity(this, true); - } else if (this.isNoGravity() && !fizzling && !((EntityExt)this).isInFunnel()) { - RayonIntegration.INSTANCE.setNoGravity(this, false); - } - if (this.getDeltaMovement().y < -3.92) { - this.setDeltaMovement(this.getDeltaMovement().add(0, .81d, 0)); - } - if (fizzling) { - if (level().isClientSide) { - fizzleProgress += Minecraft.getInstance().getFrameTime(); - } else { - fizzleProgress += 0.05f; - if (fizzleProgress >= 1f) { - remove(RemovalReason.KILLED); - } - } - } - } - - @Override - public void aiStep() { - if (!isLocked()) { - super.aiStep(); - } - } - - @Override - public boolean isControlledByLocalInstance() { - return !level().isClientSide || getHolderUUID().isPresent(); - } - - @NotNull - @Override - public Iterable getArmorSlots() { - return Collections.emptyList(); - } - - @NotNull - @Override - public ItemStack getItemBySlot(EquipmentSlot slot) { - return ItemStack.EMPTY; - } - - @Override - public void setItemSlot(EquipmentSlot slot, ItemStack stack) { - } - - @NotNull - @Override - public HumanoidArm getMainArm() { - return HumanoidArm.RIGHT; - } - - @Override - public void startFizzlingProgress() { - fizzling = true; - } - - @Override - public void fizzle() { - if (fizzling) return; - fizzling = true; - level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.MATERIAL_EMANCIPATION_EVENT, SoundSource.NEUTRAL, 0.1f, 1f); - RayonIntegration.INSTANCE.setNoGravity(this, true); - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeVarInt(getId()); - final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.FIZZLE_PACKET, buf); - PlayerLookup.tracking(this).forEach(player -> player.connection.send(packet)); - } - - @Override - public float getFizzleProgress() { - return fizzleProgress; - } - - @Override - public boolean fizzling() { - return fizzling; - } - - @Override - public boolean fizzlesInGoo() { - return true; - } - - @Override - public FizzleType getFizzleType() { - return FizzleType.OBJECT; - } - - protected final Vec3 getPlayerRotationVector(float pitch, float yaw) { - float f = pitch * (float) (Math.PI / 180.0); - float g = -yaw * (float) (Math.PI / 180.0); - float h = Mth.cos(g); - float i = Mth.sin(g); - float j = Mth.cos(f); - float k = Mth.sin(f); - return RotationUtil.vecPlayerToWorld(new Vec3(i * j, -k, h * j), GravityChangerAPI.getGravityDirection(this)); - } - - @Override - public void move(MoverType movementType, Vec3 movement) { - super.move(movementType, movement); - if (horizontalCollision) { - if (!hasCollided) { - hasCollided = true; - if (!level().isClientSide && timeSinceLastSound >= 20) { - level().playSound(null, this, getCollisionSound(), SoundSource.NEUTRAL, 1f, 1f); - timeSinceLastSound = 0; - } - } - } else { - hasCollided = false; - } - } - - @Override - public void readAdditionalSaveData(CompoundTag compound) { - super.readAdditionalSaveData(compound); - entityData.set(LOCKED, compound.getBoolean("Locked")); - } - - @Override - public void addAdditionalSaveData(CompoundTag compound) { - super.addAdditionalSaveData(compound); - compound.putBoolean("Locked", isLocked()); - } - - protected SoundEvent getCollisionSound() { - return PortalCubedSounds.CUBE_LOW_HIT_EVENT; // TODO: implement for other physics objects (this requires a lot of assets) - } - - @Override - public void remove(RemovalReason reason) { - if (!level().isClientSide) //noinspection DataFlowIssue - getHolderUUID().ifPresent(value -> PortalCubedComponents.HOLDER_COMPONENT.get(((ServerLevel) level()).getEntity(value)).stopHolding()); - super.remove(reason); - } - - @Override - public void checkDespawn() { - } - - protected static AABB createFootBox(double x, double y, double z) { - return new AABB(-x / 2, 0, -z / 2, x / 2, y, z / 2); - } - - @NotNull - @Override - public Fallsounds getFallSounds() { - return new Fallsounds(PortalCubedSounds.GENERIC_PHYSICS_FALL_EVENT, PortalCubedSounds.GENERIC_PHYSICS_FALL_EVENT); - } - - @Override - protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { - if (onGround) { - if (state.isAir() && fallDistance > 0 && getType().is(PortalCubedEntities.P1_ENTITY)) { - final List collisions = level().getEntitiesOfClass(Entity.class, getBoundingBox().expandTowards(0, -0.1, 0), this::canCollideWith); - for (final Entity collision : collisions) { - collision.hurt(pcSources(level()).cube(), fallDistance * 1.5f); - } - } - fallDistance = 0; - } else { - fallDistance -= y; - } - } + private float fizzleProgress = 0f; + private boolean fizzling = false; + + public CorePhysicsEntity(EntityType type, Level world) { + super(type, world); + } + + private boolean canUsePortals = true; + private boolean hasCollided; + private int timeSinceLastSound; + + private List intermediaryPortals = List.of(); + + public Vec3 lastPos = this.position(); + + private final Vec3 offsetHeight = new Vec3(0, this.getBbHeight() / 2, 0); + + private boolean locked = false; + private boolean onButton = false; + private Optional holder = Optional.empty(); + + @Override + public boolean canBeCollidedWith() { + return canUsePortals; + } + + @Override + public boolean canCollideWith(Entity other) { + return other != this && canBeCollidedWith() && other instanceof LivingEntity && other.isAlive(); + } + + @Override + public boolean isPushable() { + return false; + } + + @Override + public boolean isInvulnerableTo(DamageSource source) { + if (source.isCreativePlayer() || source.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) + return false; + if (!(source.getEntity() instanceof Player player)) + return true; + return !player.getItemInHand(InteractionHand.MAIN_HAND).is(PortalCubedItems.WRENCHES); + } + + @Override + public boolean hurt(DamageSource source, float amount) { + if (!level().isClientSide && !isInvulnerableTo(source) && !isRemoved()) { + if (!source.isCreativePlayer()) { + dropAllDeathLoot(source); + } + discard(); + return true; + } + return false; + } + + @Override + @NotNull + protected InteractionResult mobInteract(Player player, InteractionHand hand) { + return player.isShiftKeyDown() ? toggleLock(player, hand) : physicsEntityInteraction(player, hand); + } + + protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { + return InteractionResult.PASS; + } + + private InteractionResult toggleLock(Player player, InteractionHand hand) { + if (level().isClientSide() || !player.isCreative()) + return InteractionResult.PASS; + ItemStack stack = player.getItemInHand(hand); + if (!stack.is(PortalCubedItems.HAMMER)) + return InteractionResult.PASS; + // toggle + Boolean locked = !entityData.get(LOCKED); + entityData.set(LOCKED, locked); + + if (locked) { + getHolderUUID().ifPresent(uuid -> { + Player holder = level().getPlayerByUUID(uuid); + if (holder != null) { + PortalCubedComponents.HOLDER_COMPONENT.get(holder).stopHolding(); + } + }); + } + + player.displayClientMessage(Component.translatable("portalcubed.physics_entity.locked." + locked), true); + return InteractionResult.SUCCESS; + } + + @Override + public boolean shouldShowName() { + return false; + } + + @Override + public boolean isCustomNameVisible() { + return false; + } + + @Override + @NotNull + public Component getDisplayName() { + return super.getDisplayName().plainCopy(); + } + + @Nullable + @Override + public ItemStack getPickResult() { + ItemStack stack = super.getPickResult(); + if (stack != null && this.hasCustomName()) + stack.setHoverName(getDisplayName()); + return stack; + } + + @Override + public void recreateFromPacket(ClientboundAddEntityPacket packet) { + super.recreateFromPacket(packet); + this.setDiscardFriction(true); + } + + private static final EntityDataAccessor> HOLDER_UUID = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.OPTIONAL_UUID); + private static final EntityDataAccessor ON_BUTTON = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.BOOLEAN); + public static final EntityDataAccessor LOCKED = SynchedEntityData.defineId(CorePhysicsEntity.class, EntityDataSerializers.BOOLEAN); + + @Override + protected void defineSynchedData() { + super.defineSynchedData(); + this.getEntityData().define(HOLDER_UUID, Optional.empty()); + this.getEntityData().define(ON_BUTTON, false); + this.getEntityData().define(LOCKED, false); + } + + @Override + public void onSyncedDataUpdated(EntityDataAccessor key) { + super.onSyncedDataUpdated(key); + if (LOCKED.equals(key)) { + this.locked = entityData.get(LOCKED); + } else if (ON_BUTTON.equals(key)) { + this.onButton = entityData.get(ON_BUTTON); + } else if (HOLDER_UUID.equals(key)) { + this.holder = entityData.get(HOLDER_UUID); + } + } + + public Optional getHolderUUID() { + return holder; + } + + public void setHolderUUID(Optional uuid) { + entityData.set(HOLDER_UUID, uuid); + } + + public boolean isOnButton() { + return onButton; + } + + public void setOnButton(boolean on) { + entityData.set(ON_BUTTON, on); + } + + public boolean isLocked() { + return locked; + } + + public void setRotYaw(float yaw) { + this.yBodyRot = yaw; + } + + @Override + public boolean canChangeDimensions() { + return canUsePortals; + } + + @Override + public void tick() { + super.tick(); + UUID holder = this.holder.orElse(null); + final boolean isBeingHeld = holder != null && !fizzling; + timeSinceLastSound++; + this.hasImpulse = true; + canUsePortals = holder == null; + this.lastPos = this.position(); + this.setDiscardFriction(!this.onGround() && !((EntityExt) this).isInFunnel()); + if (isBeingHeld) { + Player player = (Player) ((LevelExt) level()).getEntityByUuid(holder); + if (player != null && player.isAlive()) { + Vec3 eyes = player.getEyePosition(0); + double distance = 1.5; + canUsePortals = false; + Vec3 rotation = this.getPlayerRotationVector(player.getXRot(), player.getYRot()); + Vec3 rotatedOffset = RotationUtil.vecPlayerToWorld(offsetHeight, GravityChangerAPI.getGravityDirection(this)); + Vec3 target = eyes.add( + (rotation.x * distance) - rotatedOffset.x, + (rotation.y * distance) - rotatedOffset.y, + (rotation.z * distance) - rotatedOffset.z + ); + final AdvancedEntityRaycast.Result raycastResult = PortalDirectionUtils.raycast(level(), new ClipContext( + eyes, target, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, this + )); + final Vec3 holdPos = raycastResult.finalHit().getLocation(); + if (!level().isClientSide) { + GravityChangerAPI.addGravity(this, new Gravity(GravityChangerAPI.getGravityDirection(player), 10, 1, "player_interaction")); + } + this.fallDistance = 0; + if (RayonIntegration.INSTANCE.isPresent()) { + final float destYaw = Mth.wrapDegrees(player.yHeadRot + 180); + final float multiplier = (destYaw > 120 || destYaw < 0) ? -1 : 1; + final float yawDelta = Mth.wrapDegrees( + Mth.wrapDegrees(RayonIntegration.INSTANCE.getYaw(this) * multiplier) - destYaw + ); + RayonIntegration.INSTANCE.rotateYaw(this, yawDelta); + RayonIntegration.INSTANCE.setAngularVelocityYaw(this, new Vector3f(0, yawDelta, 0)); + } else { + setYRot(player.yHeadRot); + setYHeadRot(player.yHeadRot); + setYBodyRot(player.yHeadRot); + } + final List portals = raycastResult.rays() + .stream() + .map(AdvancedEntityRaycast.Result.Ray::hit) + .filter(h -> h instanceof EntityHitResult) + .map(h -> ((EntityHitResult)h).getEntity().getUUID()) + .toList(); + if (!portals.equals(intermediaryPortals)) { + intermediaryPortals = portals; + moveTo(holdPos); + } else { + final Vec3 movement = RotationUtil.vecWorldToPlayer(holdPos.subtract(position()), GravityChangerAPI.getGravityDirection(player)); + if (RayonIntegration.INSTANCE.isPresent()) { + RayonIntegration.INSTANCE.setVelocity(this, movement); + } + RayonIntegration.INSTANCE.simpleMove(this, MoverType.PLAYER, movement); + } + if (position().distanceToSqr(holdPos) > 2 * 2) { + PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding(); + } + } else { + if (player != null) { + setHolderUUID(Optional.empty()); + } + canUsePortals = true; + } + RayonIntegration.INSTANCE.setNoGravity(this, true); + } else if (this.isNoGravity() && !fizzling && !((EntityExt)this).isInFunnel()) { + RayonIntegration.INSTANCE.setNoGravity(this, false); + } + if (this.getDeltaMovement().y < -3.92) { + this.setDeltaMovement(this.getDeltaMovement().add(0, .81d, 0)); + } + if (fizzling) { + if (level().isClientSide) { + fizzleProgress += Minecraft.getInstance().getFrameTime(); + } else { + fizzleProgress += 0.05f; + if (fizzleProgress >= 1f) { + remove(RemovalReason.KILLED); + } + } + } + } + + @Override + public void aiStep() { + if (!isLocked()) { + super.aiStep(); + } + } + + @Override + public boolean isControlledByLocalInstance() { + return !level().isClientSide || getHolderUUID().isPresent(); + } + + @NotNull + @Override + public Iterable getArmorSlots() { + return Collections.emptyList(); + } + + @NotNull + @Override + public ItemStack getItemBySlot(EquipmentSlot slot) { + return ItemStack.EMPTY; + } + + @Override + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + } + + @NotNull + @Override + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + @Override + public void startFizzlingProgress() { + fizzling = true; + } + + @Override + public void fizzle() { + if (fizzling) return; + fizzling = true; + level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.MATERIAL_EMANCIPATION_EVENT, SoundSource.NEUTRAL, 0.1f, 1f); + RayonIntegration.INSTANCE.setNoGravity(this, true); + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeVarInt(getId()); + final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.FIZZLE_PACKET, buf); + PlayerLookup.tracking(this).forEach(player -> player.connection.send(packet)); + } + + @Override + public float getFizzleProgress() { + return fizzleProgress; + } + + @Override + public boolean fizzling() { + return fizzling; + } + + @Override + public boolean fizzlesInGoo() { + return true; + } + + @Override + public FizzleType getFizzleType() { + return FizzleType.OBJECT; + } + + protected final Vec3 getPlayerRotationVector(float pitch, float yaw) { + float f = pitch * (float) (Math.PI / 180.0); + float g = -yaw * (float) (Math.PI / 180.0); + float h = Mth.cos(g); + float i = Mth.sin(g); + float j = Mth.cos(f); + float k = Mth.sin(f); + return RotationUtil.vecPlayerToWorld(new Vec3(i * j, -k, h * j), GravityChangerAPI.getGravityDirection(this)); + } + + @Override + public void move(MoverType movementType, Vec3 movement) { + super.move(movementType, movement); + if (horizontalCollision) { + if (!hasCollided) { + hasCollided = true; + if (!level().isClientSide && timeSinceLastSound >= 20) { + level().playSound(null, this, getCollisionSound(), SoundSource.NEUTRAL, 1f, 1f); + timeSinceLastSound = 0; + } + } + } else { + hasCollided = false; + } + } + + @Override + public void readAdditionalSaveData(CompoundTag compound) { + super.readAdditionalSaveData(compound); + entityData.set(LOCKED, compound.getBoolean("Locked")); + } + + @Override + public void addAdditionalSaveData(CompoundTag compound) { + super.addAdditionalSaveData(compound); + compound.putBoolean("Locked", isLocked()); + } + + protected SoundEvent getCollisionSound() { + return PortalCubedSounds.CUBE_LOW_HIT_EVENT; // TODO: implement for other physics objects (this requires a lot of assets) + } + + @Override + public void remove(RemovalReason reason) { + if (!level().isClientSide) //noinspection DataFlowIssue + getHolderUUID().ifPresent(value -> PortalCubedComponents.HOLDER_COMPONENT.get(((ServerLevel) level()).getEntity(value)).stopHolding()); + super.remove(reason); + } + + @Override + public void checkDespawn() { + } + + protected static AABB createFootBox(double x, double y, double z) { + return new AABB(-x / 2, 0, -z / 2, x / 2, y, z / 2); + } + + @NotNull + @Override + public Fallsounds getFallSounds() { + return new Fallsounds(PortalCubedSounds.GENERIC_PHYSICS_FALL_EVENT, PortalCubedSounds.GENERIC_PHYSICS_FALL_EVENT); + } + + @Override + protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { + if (onGround) { + if (state.isAir() && fallDistance > 0 && getType().is(PortalCubedEntities.P1_ENTITY)) { + final List collisions = level().getEntitiesOfClass(Entity.class, getBoundingBox().expandTowards(0, -0.1, 0), this::canCollideWith); + for (final Entity collision : collisions) { + collision.hurt(pcSources(level()).cube(), fallDistance * 1.5f); + } + } + fallDistance = 0; + } else { + fallDistance -= y; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/CuriosityCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/CuriosityCoreEntity.java index 10fb6e1b..9398ec80 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/CuriosityCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/CuriosityCoreEntity.java @@ -7,21 +7,21 @@ public class CuriosityCoreEntity extends CorePhysicsEntity { - public CuriosityCoreEntity(EntityType type, Level world) { - super(type, world); - } + public CuriosityCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.CURIOSITY_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 346; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.CURIOSITY_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 346; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/EnergyPellet.java b/src/main/java/com/fusionflux/portalcubed/entity/EnergyPellet.java index ad97c6a3..6cbc0e00 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/EnergyPellet.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/EnergyPellet.java @@ -41,218 +41,218 @@ import static com.fusionflux.portalcubed.mechanics.PortalCubedDamageSources.pcSources; public class EnergyPellet extends Entity implements ItemSupplier, WentThroughPortalListener { - private static final EntityDataAccessor STARTING_LIFE = SynchedEntityData.defineId(EnergyPellet.class, EntityDataSerializers.INT); - private static final EntityDataAccessor LIFE = SynchedEntityData.defineId(EnergyPellet.class, EntityDataSerializers.INT); + private static final EntityDataAccessor STARTING_LIFE = SynchedEntityData.defineId(EnergyPellet.class, EntityDataSerializers.INT); + private static final EntityDataAccessor LIFE = SynchedEntityData.defineId(EnergyPellet.class, EntityDataSerializers.INT); - private int bounces; - private UUID thrower = Util.NIL_UUID; + private int bounces; + private UUID thrower = Util.NIL_UUID; - public EnergyPellet(EntityType type, Level world) { - super(type, world); - } + public EnergyPellet(EntityType type, Level world) { + super(type, world); + } - @Override - protected void defineSynchedData() { - entityData.define(STARTING_LIFE, 220); - entityData.define(LIFE, 220); - } + @Override + protected void defineSynchedData() { + entityData.define(STARTING_LIFE, 220); + entityData.define(LIFE, 220); + } - @Override - protected void readAdditionalSaveData(CompoundTag nbt) { - setStartingLife(nbt.getInt("StartingLife")); - setLife(nbt.getInt("Life")); - bounces = nbt.getInt("Bounces"); - thrower = nbt.getUUID("Thrower"); - } + @Override + protected void readAdditionalSaveData(CompoundTag nbt) { + setStartingLife(nbt.getInt("StartingLife")); + setLife(nbt.getInt("Life")); + bounces = nbt.getInt("Bounces"); + thrower = nbt.getUUID("Thrower"); + } - @Override - protected void addAdditionalSaveData(CompoundTag nbt) { - nbt.putInt("StartingLife", getStartingLife()); - nbt.putInt("Life", getLife()); - nbt.putInt("Bounces", bounces); - nbt.putUUID("Thrower", thrower); - } + @Override + protected void addAdditionalSaveData(CompoundTag nbt) { + nbt.putInt("StartingLife", getStartingLife()); + nbt.putInt("Life", getLife()); + nbt.putInt("Bounces", bounces); + nbt.putUUID("Thrower", thrower); + } - public int getStartingLife() { - return entityData.get(STARTING_LIFE); - } + public int getStartingLife() { + return entityData.get(STARTING_LIFE); + } - public void setStartingLife(int ticks) { - entityData.set(STARTING_LIFE, ticks); - } + public void setStartingLife(int ticks) { + entityData.set(STARTING_LIFE, ticks); + } - public int getLife() { - return entityData.get(LIFE); - } + public int getLife() { + return entityData.get(LIFE); + } - public void setLife(int ticks) { - entityData.set(LIFE, ticks); - } + public void setLife(int ticks) { + entityData.set(LIFE, ticks); + } - public void resetLife(int startingLife) { - setStartingLife(startingLife); - resetLife(); - } + public void resetLife(int startingLife) { + setStartingLife(startingLife); + resetLife(); + } - public void resetLife() { - setLife(getStartingLife()); - } + public void resetLife() { + setLife(getStartingLife()); + } - @Override - public void tick() { - super.tick(); - if (level().isClientSide) return; - Vec3 vel = getDeltaMovement(); - { - final var catapult = level().getBlockEntity(blockPosition(), PortalCubedBlocks.CATAPULT_BLOCK_ENTITY); - if (catapult.isPresent()) { - ((EntityExt)this).collidedWithCatapult(catapult.get()); - vel = getDeltaMovement(); - } - } - move(MoverType.SELF, vel); - hasImpulse = true; - int life = getLife(); - if (life > 0) { - setLife(--life); - } else if (life == 0) { - kill(null); - } // life < 0 means green pellet - if (tickCount == 1) { - level().playSound(null, position().x, position().y, position().z, PortalCubedSounds.PELLET_SPAWN_EVENT, SoundSource.HOSTILE, 1f, 1f); - } - Direction bouncedDir = null; - if (verticalCollision) { - vel = vel.with(Direction.Axis.Y, -vel.y); - bouncedDir = vel.y < 0 ? Direction.DOWN : Direction.UP; - } - if (horizontalCollision) { - if (getDeltaMovement().x == 0) { - vel = vel.with(Direction.Axis.X, -vel.x); - bouncedDir = vel.x < 0 ? Direction.WEST : Direction.EAST; - } - if (getDeltaMovement().z == 0) { - vel = vel.with(Direction.Axis.Z, -vel.z); - bouncedDir = vel.z < 0 ? Direction.NORTH : Direction.SOUTH; - } - } - setDeltaMovement(vel); - if (bouncedDir != null) { - bounced(); - if (level() instanceof ServerLevel serverLevel) { - final Vec3 spawnPos = serverLevel.clip(new ClipContext( - position(), - position().add(vel.with(bouncedDir.getAxis(), -vel.get(bouncedDir.getAxis()))), - ClipContext.Block.COLLIDER, - ClipContext.Fluid.NONE, - this - )).getLocation().add(Vec3.atLowerCornerOf(bouncedDir.getNormal()).scale(0.01)); - serverLevel.sendParticles( - new DecalParticleOption(DecalParticleOption.SCORCH, bouncedDir), - spawnPos.x, spawnPos.y, spawnPos.z, - 0, 0, 0, 0, 0 - ); - } - } - if ((tickCount - 1) % 34 == 0) { - level().playSound(null, this, PortalCubedSounds.PELLET_TRAVEL_EVENT, SoundSource.HOSTILE, 0.4f, 1f); - } - final HitResult hit = ProjectileUtil.getHitResultOnMoveVector(this, this::canHit); - if (hit.getType() == HitResult.Type.ENTITY) { - bounceOrKill((LivingEntity)((EntityHitResult)hit).getEntity()); - } else { - final LivingEntity hit2 = level().getNearestEntity( - LivingEntity.class, - TargetingConditions.forNonCombat().selector(this::canHit), - null, getX(), getY(), getZ(), - getBoundingBox() - ); - if (hit2 != null) { - bounceOrKill(hit2); - } - } - } + @Override + public void tick() { + super.tick(); + if (level().isClientSide) return; + Vec3 vel = getDeltaMovement(); + { + final var catapult = level().getBlockEntity(blockPosition(), PortalCubedBlocks.CATAPULT_BLOCK_ENTITY); + if (catapult.isPresent()) { + ((EntityExt)this).collidedWithCatapult(catapult.get()); + vel = getDeltaMovement(); + } + } + move(MoverType.SELF, vel); + hasImpulse = true; + int life = getLife(); + if (life > 0) { + setLife(--life); + } else if (life == 0) { + kill(null); + } // life < 0 means green pellet + if (tickCount == 1) { + level().playSound(null, position().x, position().y, position().z, PortalCubedSounds.PELLET_SPAWN_EVENT, SoundSource.HOSTILE, 1f, 1f); + } + Direction bouncedDir = null; + if (verticalCollision) { + vel = vel.with(Direction.Axis.Y, -vel.y); + bouncedDir = vel.y < 0 ? Direction.DOWN : Direction.UP; + } + if (horizontalCollision) { + if (getDeltaMovement().x == 0) { + vel = vel.with(Direction.Axis.X, -vel.x); + bouncedDir = vel.x < 0 ? Direction.WEST : Direction.EAST; + } + if (getDeltaMovement().z == 0) { + vel = vel.with(Direction.Axis.Z, -vel.z); + bouncedDir = vel.z < 0 ? Direction.NORTH : Direction.SOUTH; + } + } + setDeltaMovement(vel); + if (bouncedDir != null) { + bounced(); + if (level() instanceof ServerLevel serverLevel) { + final Vec3 spawnPos = serverLevel.clip(new ClipContext( + position(), + position().add(vel.with(bouncedDir.getAxis(), -vel.get(bouncedDir.getAxis()))), + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + this + )).getLocation().add(Vec3.atLowerCornerOf(bouncedDir.getNormal()).scale(0.01)); + serverLevel.sendParticles( + new DecalParticleOption(DecalParticleOption.SCORCH, bouncedDir), + spawnPos.x, spawnPos.y, spawnPos.z, + 0, 0, 0, 0, 0 + ); + } + } + if ((tickCount - 1) % 34 == 0) { + level().playSound(null, this, PortalCubedSounds.PELLET_TRAVEL_EVENT, SoundSource.HOSTILE, 0.4f, 1f); + } + final HitResult hit = ProjectileUtil.getHitResultOnMoveVector(this, this::canHit); + if (hit.getType() == HitResult.Type.ENTITY) { + bounceOrKill((LivingEntity)((EntityHitResult)hit).getEntity()); + } else { + final LivingEntity hit2 = level().getNearestEntity( + LivingEntity.class, + TargetingConditions.forNonCombat().selector(this::canHit), + null, getX(), getY(), getZ(), + getBoundingBox() + ); + if (hit2 != null) { + bounceOrKill(hit2); + } + } + } - protected boolean canHit(Entity entity) { - return entity instanceof LivingEntity && !entity.isSpectator() && entity.isAlive() && entity.isPickable(); - } + protected boolean canHit(Entity entity) { + return entity instanceof LivingEntity && !entity.isSpectator() && entity.isAlive() && entity.isPickable(); + } - private static double getBounceAngle(double inAngle, double propAngle) { - // -(a - b) - 180 + b - // Simplifies to - // -a + b - 180 + b - // -a - 180 + 2b - return Mth.wrapDegrees(-inAngle - 180 + 2 * propAngle); - } + private static double getBounceAngle(double inAngle, double propAngle) { + // -(a - b) - 180 + b + // Simplifies to + // -a + b - 180 + b + // -a - 180 + 2b + return Mth.wrapDegrees(-inAngle - 180 + 2 * propAngle); + } - private void bounceOrKill(LivingEntity entity) { - if (entity instanceof CorePhysicsEntity) { - final Vec3 vel = getDeltaMovement(); - final double newAngle = Math.toRadians(getBounceAngle( - Math.toDegrees(Math.atan2(vel.z, vel.x)), - Mth.wrapDegrees(entity.getYRot() + 90) - )); - final double mag = vel.length(); - setDeltaMovement(Math.cos(newAngle) * mag, vel.y, Math.sin(newAngle) * mag); - level().playSound(null, this, PortalCubedSounds.PELLET_BOUNCE_EVENT, SoundSource.HOSTILE, 0.4f, 1f); - bounced(); - } else { - kill(entity); - } - } + private void bounceOrKill(LivingEntity entity) { + if (entity instanceof CorePhysicsEntity) { + final Vec3 vel = getDeltaMovement(); + final double newAngle = Math.toRadians(getBounceAngle( + Math.toDegrees(Math.atan2(vel.z, vel.x)), + Mth.wrapDegrees(entity.getYRot() + 90) + )); + final double mag = vel.length(); + setDeltaMovement(Math.cos(newAngle) * mag, vel.y, Math.sin(newAngle) * mag); + level().playSound(null, this, PortalCubedSounds.PELLET_BOUNCE_EVENT, SoundSource.HOSTILE, 0.4f, 1f); + bounced(); + } else { + kill(entity); + } + } - private void bounced() { - level().playSound(null, this, PortalCubedSounds.PELLET_BOUNCE_EVENT, SoundSource.HOSTILE, 0.4f, 1f); - bounces++; - if (level() instanceof ServerLevel serverLevel && thrower != Util.NIL_UUID) { - final ServerPlayer player = (ServerPlayer)serverLevel.getPlayerByUUID(thrower); - if (player != null) { - PortalCubedTriggers.BOUNCE.trigger(player, this); - } - } - } + private void bounced() { + level().playSound(null, this, PortalCubedSounds.PELLET_BOUNCE_EVENT, SoundSource.HOSTILE, 0.4f, 1f); + bounces++; + if (level() instanceof ServerLevel serverLevel && thrower != Util.NIL_UUID) { + final ServerPlayer player = (ServerPlayer)serverLevel.getPlayerByUUID(thrower); + if (player != null) { + PortalCubedTriggers.BOUNCE.trigger(player, this); + } + } + } - private void kill(@Nullable LivingEntity entity) { - level().playSound(null, position().x, position().y, position().z, PortalCubedSounds.PELLET_EXPLODE_EVENT, SoundSource.HOSTILE, 0.8f, 1f); - if (entity != null) { - entity.hurt(pcSources(level()).vaporization(this, getThrower()), PortalCubedConfig.pelletDamage); - } - kill(); - } + private void kill(@Nullable LivingEntity entity) { + level().playSound(null, position().x, position().y, position().z, PortalCubedSounds.PELLET_EXPLODE_EVENT, SoundSource.HOSTILE, 0.8f, 1f); + if (entity != null) { + entity.hurt(pcSources(level()).vaporization(this, getThrower()), PortalCubedConfig.pelletDamage); + } + kill(); + } - @Override - public boolean shouldRenderAtSqrDistance(double distance) { - return true; - } + @Override + public boolean shouldRenderAtSqrDistance(double distance) { + return true; + } - @NotNull - @Override - public ItemStack getItem() { - return new ItemStack(getLife() < 0 ? PortalCubedItems.SUPER_PELLET : PortalCubedItems.ENERGY_PELLET); - } + @NotNull + @Override + public ItemStack getItem() { + return new ItemStack(getLife() < 0 ? PortalCubedItems.SUPER_PELLET : PortalCubedItems.ENERGY_PELLET); + } - @Override - public void wentThroughPortal(Portal portal) { - setLife(getStartingLife()); - } + @Override + public void wentThroughPortal(Portal portal) { + setLife(getStartingLife()); + } - public int getBounces() { - return bounces; - } + public int getBounces() { + return bounces; + } - public UUID getThrowerUUID() { - return thrower; - } + public UUID getThrowerUUID() { + return thrower; + } - @Nullable - public Entity getThrower() { - if (thrower == Util.NIL_UUID) { - return null; - } - return ((LevelExt)level()).getEntityByUuid(thrower); - } + @Nullable + public Entity getThrower() { + if (thrower == Util.NIL_UUID) { + return null; + } + return ((LevelExt)level()).getEntityByUuid(thrower); + } - public void setThrower(Entity thrower) { - this.thrower = thrower.getUUID(); - } + public void setThrower(Entity thrower) { + this.thrower = thrower.getUUID(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/FactCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/FactCoreEntity.java index 5c2afba9..72b3e4c8 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/FactCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/FactCoreEntity.java @@ -7,21 +7,21 @@ public class FactCoreEntity extends CorePhysicsEntity { - public FactCoreEntity(EntityType type, Level world) { - super(type, world); - } + public FactCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.FACT_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 5500; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.FACT_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 5500; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/Fizzleable.java b/src/main/java/com/fusionflux/portalcubed/entity/Fizzleable.java index a2c59fb6..c7d29c89 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/Fizzleable.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/Fizzleable.java @@ -1,19 +1,19 @@ package com.fusionflux.portalcubed.entity; public interface Fizzleable { - void startFizzlingProgress(); + void startFizzlingProgress(); - void fizzle(); + void fizzle(); - float getFizzleProgress(); + float getFizzleProgress(); - boolean fizzling(); + boolean fizzling(); - boolean fizzlesInGoo(); + boolean fizzlesInGoo(); - FizzleType getFizzleType(); + FizzleType getFizzleType(); - enum FizzleType { - NOT, OBJECT, LIVING - } + enum FizzleType { + NOT, OBJECT, LIVING + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/GelBlobEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/GelBlobEntity.java index 864d9cbd..f7af34bb 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/GelBlobEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/GelBlobEntity.java @@ -35,224 +35,224 @@ import java.util.Set; public abstract class GelBlobEntity extends Projectile { - private static final Vec3[] ANGLES; - private static final EntityDataAccessor SIZE = SynchedEntityData.defineId(GelBlobEntity.class, EntityDataSerializers.INT); + private static final Vec3[] ANGLES; + private static final EntityDataAccessor SIZE = SynchedEntityData.defineId(GelBlobEntity.class, EntityDataSerializers.INT); - static { - final Set angles = new HashSet<>(); - for (int x = 0; x < 128; x++) { - for (int y = 0; y < 128; y++) { - angles.add(Vec3.directionFromRotation(360 / 128f * x, 360 / 128f * y - 128)); - } - } - ANGLES = angles.toArray(new Vec3[0]); - } + static { + final Set angles = new HashSet<>(); + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { + angles.add(Vec3.directionFromRotation(360 / 128f * x, 360 / 128f * y - 128)); + } + } + ANGLES = angles.toArray(new Vec3[0]); + } - public GelBlobEntity(EntityType entityType, Level world) { - super(entityType, world); - } + public GelBlobEntity(EntityType entityType, Level world) { + super(entityType, world); + } - @Override - protected void defineSynchedData() { - entityData.define(SIZE, 1); - } + @Override + protected void defineSynchedData() { + entityData.define(SIZE, 1); + } - @Override - public void readAdditionalSaveData(CompoundTag nbt) { - super.readAdditionalSaveData(nbt); - if (nbt.contains("Size", Tag.TAG_INT)) { - setSize(nbt.getInt("Size")); - } - } + @Override + public void readAdditionalSaveData(CompoundTag nbt) { + super.readAdditionalSaveData(nbt); + if (nbt.contains("Size", Tag.TAG_INT)) { + setSize(nbt.getInt("Size")); + } + } - @Override - public void addAdditionalSaveData(CompoundTag nbt) { - super.addAdditionalSaveData(nbt); - nbt.putInt("Size", getSize()); - } + @Override + public void addAdditionalSaveData(CompoundTag nbt) { + super.addAdditionalSaveData(nbt); + nbt.putInt("Size", getSize()); + } - public int getSize() { - return entityData.get(SIZE); - } + public int getSize() { + return entityData.get(SIZE); + } - public void setSize(int size) { - entityData.set(SIZE, size); - } + public void setSize(int size) { + entityData.set(SIZE, size); + } - public float getScale() { - final int size = getSize(); - return (6 * (size + 1) - size) / 16f; - } + public float getScale() { + final int size = getSize(); + return (6 * (size + 1) - size) / 16f; + } - public int getExplosionRadius() { - return 2 * getSize(); - } + public int getExplosionRadius() { + return 2 * getSize(); + } - @Override - public void tick() { - super.tick(); - if (fluidHeight.values().doubleStream().anyMatch(d -> d != 0)) { - kill(); - } - boolean bl = this.noPhysics; - Vec3 vec3d = this.getDeltaMovement(); + @Override + public void tick() { + super.tick(); + if (fluidHeight.values().doubleStream().anyMatch(d -> d != 0)) { + kill(); + } + boolean bl = this.noPhysics; + Vec3 vec3d = this.getDeltaMovement(); - Vec3 vec3d3 = this.position(); - Vec3 vec3d2 = vec3d3.add(vec3d); - HitResult hitResult = this.level().clip(new ClipContext(vec3d3, vec3d2, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, this)); - if (hitResult.getType() != HitResult.Type.MISS) { - vec3d2 = hitResult.getLocation(); - } + Vec3 vec3d3 = this.position(); + Vec3 vec3d2 = vec3d3.add(vec3d); + HitResult hitResult = this.level().clip(new ClipContext(vec3d3, vec3d2, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, this)); + if (hitResult.getType() != HitResult.Type.MISS) { + vec3d2 = hitResult.getLocation(); + } - EntityHitResult entityHitResult = this.getEntityCollision(vec3d3, vec3d2); - if (entityHitResult != null) { - hitResult = entityHitResult; - } + EntityHitResult entityHitResult = this.getEntityCollision(vec3d3, vec3d2); + if (entityHitResult != null) { + hitResult = entityHitResult; + } - if (hitResult.getType() == HitResult.Type.ENTITY) { - //noinspection DataFlowIssue - Entity entity = ((EntityHitResult)hitResult).getEntity(); - Entity entity2 = this.getOwner(); - if (entity instanceof Player && entity2 instanceof Player && !((Player)entity2).canHarmPlayer((Player)entity)) { - hitResult = null; - } - } + if (hitResult.getType() == HitResult.Type.ENTITY) { + //noinspection DataFlowIssue + Entity entity = ((EntityHitResult)hitResult).getEntity(); + Entity entity2 = this.getOwner(); + if (entity instanceof Player && entity2 instanceof Player && !((Player)entity2).canHarmPlayer((Player)entity)) { + hitResult = null; + } + } - if (hitResult != null && !bl) { - this.onHit(hitResult); - this.hasImpulse = true; - } + if (hitResult != null && !bl) { + this.onHit(hitResult); + this.hasImpulse = true; + } - vec3d = this.getDeltaMovement(); - double e = vec3d.x; - double f = vec3d.y; - double g = vec3d.z; + vec3d = this.getDeltaMovement(); + double e = vec3d.x; + double f = vec3d.y; + double g = vec3d.z; - double h = this.getX() + e; - double j = this.getY() + f; - double k = this.getZ() + g; + double h = this.getX() + e; + double j = this.getY() + f; + double k = this.getZ() + g; - float m = 0.99F; - if (this.isInWater()) { - kill(); - } + float m = 0.99F; + if (this.isInWater()) { + kill(); + } - this.setDeltaMovement(vec3d.scale(m)); - if (!this.isNoGravity() && !bl) { - Vec3 vec3d4 = this.getDeltaMovement(); - this.setDeltaMovement(vec3d4.x, vec3d4.y - 0.05F, vec3d4.z); - } + this.setDeltaMovement(vec3d.scale(m)); + if (!this.isNoGravity() && !bl) { + Vec3 vec3d4 = this.getDeltaMovement(); + this.setDeltaMovement(vec3d4.x, vec3d4.y - 0.05F, vec3d4.z); + } - this.setPos(h, j, k); - this.checkInsideBlocks(); - } + this.setPos(h, j, k); + this.checkInsideBlocks(); + } - @Nullable - protected EntityHitResult getEntityCollision(Vec3 currentPosition, Vec3 nextPosition) { - return ProjectileUtil.getEntityHitResult( - this.level(), this, currentPosition, nextPosition, this.getBoundingBox().expandTowards(this.getDeltaMovement()).inflate(1.0), this::canHitEntity - ); - } + @Nullable + protected EntityHitResult getEntityCollision(Vec3 currentPosition, Vec3 nextPosition) { + return ProjectileUtil.getEntityHitResult( + this.level(), this, currentPosition, nextPosition, this.getBoundingBox().expandTowards(this.getDeltaMovement()).inflate(1.0), this::canHitEntity + ); + } - @Override - protected void onHit(HitResult hitResult) { - if (hitResult.getType() == HitResult.Type.MISS) return; - kill(); - if (!level().isClientSide) { - if (hitResult instanceof EntityHitResult ehr && ehr.getEntity() instanceof ServerPlayer serverPlayer) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeResourceLocation(BuiltInRegistries.BLOCK.getKey(getGel())); - ServerPlayNetworking.send( - serverPlayer, - PortalCubedClientPackets.GEL_OVERLAY_PACKET, - buf - ); - } - explode(); - } - } + @Override + protected void onHit(HitResult hitResult) { + if (hitResult.getType() == HitResult.Type.MISS) return; + kill(); + if (!level().isClientSide) { + if (hitResult instanceof EntityHitResult ehr && ehr.getEntity() instanceof ServerPlayer serverPlayer) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeResourceLocation(BuiltInRegistries.BLOCK.getKey(getGel())); + ServerPlayNetworking.send( + serverPlayer, + PortalCubedClientPackets.GEL_OVERLAY_PACKET, + buf + ); + } + explode(); + } + } - @Override - protected void checkFallDamage(double heightDifference, boolean onGround, BlockState landedState, BlockPos landedPosition) { - super.checkFallDamage(heightDifference, onGround, landedState, landedPosition); - kill(); - if (!level().isClientSide) { - explode(); - } - } + @Override + protected void checkFallDamage(double heightDifference, boolean onGround, BlockState landedState, BlockPos landedPosition) { + super.checkFallDamage(heightDifference, onGround, landedState, landedPosition); + kill(); + if (!level().isClientSide) { + explode(); + } + } - public void explode() { - level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.GEL_SPLAT_EVENT, SoundSource.NEUTRAL, 0.5f, 1f); - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeResourceLocation(BuiltInRegistries.BLOCK.getKey(getGel())); - final int overlayDiameter = getSize() + 1; - level().getEntities( - EntityType.PLAYER, - AABB.ofSize(position(), overlayDiameter, overlayDiameter, overlayDiameter), - p -> p instanceof ServerPlayer - ).forEach(p -> ServerPlayNetworking.send( - (ServerPlayer)p, - PortalCubedClientPackets.GEL_OVERLAY_PACKET, - buf - )); - final int radius = getExplosionRadius(); - final Vec3 origin = getBoundingBox().getCenter(); - if (radius == 0) { - final BlockPos originPos = BlockPos.containing(origin); - for (final Direction dir : Direction.values()) { - maybeExplodeAt(new BlockHitResult( - origin.add(Vec3.atLowerCornerOf(dir.getNormal())), - dir.getOpposite(), - originPos.relative(dir), - false - )); - } - return; - } - for (final Vec3 angle : ANGLES) { - final BlockHitResult hit = level().clip(new ClipContext( - origin, origin.add(angle.scale(radius)), - ClipContext.Block.COLLIDER, - ClipContext.Fluid.NONE, - this - )); - if (hit.getType() != HitResult.Type.BLOCK) continue; - maybeExplodeAt(hit); - } - } + public void explode() { + level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.GEL_SPLAT_EVENT, SoundSource.NEUTRAL, 0.5f, 1f); + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeResourceLocation(BuiltInRegistries.BLOCK.getKey(getGel())); + final int overlayDiameter = getSize() + 1; + level().getEntities( + EntityType.PLAYER, + AABB.ofSize(position(), overlayDiameter, overlayDiameter, overlayDiameter), + p -> p instanceof ServerPlayer + ).forEach(p -> ServerPlayNetworking.send( + (ServerPlayer)p, + PortalCubedClientPackets.GEL_OVERLAY_PACKET, + buf + )); + final int radius = getExplosionRadius(); + final Vec3 origin = getBoundingBox().getCenter(); + if (radius == 0) { + final BlockPos originPos = BlockPos.containing(origin); + for (final Direction dir : Direction.values()) { + maybeExplodeAt(new BlockHitResult( + origin.add(Vec3.atLowerCornerOf(dir.getNormal())), + dir.getOpposite(), + originPos.relative(dir), + false + )); + } + return; + } + for (final Vec3 angle : ANGLES) { + final BlockHitResult hit = level().clip(new ClipContext( + origin, origin.add(angle.scale(radius)), + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + this + )); + if (hit.getType() != HitResult.Type.BLOCK) continue; + maybeExplodeAt(hit); + } + } - private void maybeExplodeAt(BlockHitResult hit) { - final BlockState hitState = level().getBlockState(hit.getBlockPos()); - if (!hitState.isFaceSturdy(level(), hit.getBlockPos(), hit.getDirection())) return; - final BlockPos sidePos = hit.getBlockPos().relative(hit.getDirection()); - final BlockState sideState = level().getBlockState(sidePos); - final BooleanProperty property = MultifaceBlock.getFaceProperty(hit.getDirection().getOpposite()); - if (sideState.is(getGel())) { - level().setBlockAndUpdate(sidePos, sideState.setValue(property, true)); - } else if (sideState.canBeReplaced() || sideState.getBlock() instanceof BaseGel) { - level().setBlockAndUpdate(sidePos, getGel().defaultBlockState().setValue(property, true)); - } - } + private void maybeExplodeAt(BlockHitResult hit) { + final BlockState hitState = level().getBlockState(hit.getBlockPos()); + if (!hitState.isFaceSturdy(level(), hit.getBlockPos(), hit.getDirection())) return; + final BlockPos sidePos = hit.getBlockPos().relative(hit.getDirection()); + final BlockState sideState = level().getBlockState(sidePos); + final BooleanProperty property = MultifaceBlock.getFaceProperty(hit.getDirection().getOpposite()); + if (sideState.is(getGel())) { + level().setBlockAndUpdate(sidePos, sideState.setValue(property, true)); + } else if (sideState.canBeReplaced() || sideState.getBlock() instanceof BaseGel) { + level().setBlockAndUpdate(sidePos, getGel().defaultBlockState().setValue(property, true)); + } + } - @Override - public boolean hurt(DamageSource source, float amount) { -// if (amount != 0 && -// (!(source instanceof EntityDamageSource eds) || -// (eds.getEntity() instanceof Player player && -// player.isCreative())) -// ) { - if ( - amount != 0 && - (source.getDirectEntity() == null || - (source.getDirectEntity() instanceof Player player && - player.isCreative())) - ) { - remove(RemovalReason.KILLED); - } - return false; - } + @Override + public boolean hurt(DamageSource source, float amount) { +// if (amount != 0 && +// (!(source instanceof EntityDamageSource eds) || +// (eds.getEntity() instanceof Player player && +// player.isCreative())) +// ) { + if ( + amount != 0 && + (source.getDirectEntity() == null || + (source.getDirectEntity() instanceof Player player && + player.isCreative())) + ) { + remove(RemovalReason.KILLED); + } + return false; + } - public abstract ResourceLocation getTexture(); + public abstract ResourceLocation getTexture(); - public abstract BaseGel getGel(); + public abstract BaseGel getGel(); } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/HoopyEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/HoopyEntity.java index e4ae0aae..2a02878e 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/HoopyEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/HoopyEntity.java @@ -6,7 +6,7 @@ public class HoopyEntity extends CorePhysicsEntity { - public HoopyEntity(EntityType type, Level world) { - super(type, world); - } + public HoopyEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/JugEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/JugEntity.java index c72ec49d..bef7883a 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/JugEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/JugEntity.java @@ -5,9 +5,9 @@ import net.minecraft.world.level.Level; public class JugEntity extends CorePhysicsEntity { - public JugEntity(EntityType type, Level world) { - super(type, world); - } + public JugEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/LilPineappleEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/LilPineappleEntity.java index 8cbfdfbb..4a274290 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/LilPineappleEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/LilPineappleEntity.java @@ -5,9 +5,9 @@ import net.minecraft.world.level.Level; public class LilPineappleEntity extends CorePhysicsEntity { - public LilPineappleEntity(EntityType type, Level world) { - super(type, world); - } + public LilPineappleEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/MoralityCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/MoralityCoreEntity.java index da7c9139..e7b52fd1 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/MoralityCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/MoralityCoreEntity.java @@ -6,7 +6,7 @@ public class MoralityCoreEntity extends CorePhysicsEntity { - public MoralityCoreEntity(EntityType type, Level world) { - super(type, world); - } + public MoralityCoreEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/MugEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/MugEntity.java index aa8c2317..0d9d72d6 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/MugEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/MugEntity.java @@ -13,44 +13,44 @@ public class MugEntity extends CorePhysicsEntity { - public MugEntity(EntityType type, Level world) { - super(type, world); - } - final Random rand = new Random(); - - @Override - public void addAdditionalSaveData(CompoundTag compoundTag) { - } - - @Override - public void readAdditionalSaveData(CompoundTag compoundTag) { - } - - public int getMugType() { - return getEntityData().get(MUG_TYPE); - } - - public void genMugType() { - setMugType(rand.nextInt(4)); - } - - public void setMugType(Integer type) { - this.getEntityData().set(MUG_TYPE, type); - } - - public static final EntityDataAccessor MUG_TYPE = SynchedEntityData.defineId(MugEntity.class, EntityDataSerializers.INT); - - @Override - protected void defineSynchedData() { - super.defineSynchedData(); - this.getEntityData().define(MUG_TYPE, 20); - } - - @Override - public void recreateFromPacket(ClientboundAddEntityPacket packet) { - if (this.getMugType() == 20) { - setMugType(rand.nextInt(4)); - } - super.recreateFromPacket(packet); - } + public MugEntity(EntityType type, Level world) { + super(type, world); + } + final Random rand = new Random(); + + @Override + public void addAdditionalSaveData(CompoundTag compoundTag) { + } + + @Override + public void readAdditionalSaveData(CompoundTag compoundTag) { + } + + public int getMugType() { + return getEntityData().get(MUG_TYPE); + } + + public void genMugType() { + setMugType(rand.nextInt(4)); + } + + public void setMugType(Integer type) { + this.getEntityData().set(MUG_TYPE, type); + } + + public static final EntityDataAccessor MUG_TYPE = SynchedEntityData.defineId(MugEntity.class, EntityDataSerializers.INT); + + @Override + protected void defineSynchedData() { + super.defineSynchedData(); + this.getEntityData().define(MUG_TYPE, 20); + } + + @Override + public void recreateFromPacket(ClientboundAddEntityPacket packet) { + if (this.getMugType() == 20) { + setMugType(rand.nextInt(4)); + } + super.recreateFromPacket(packet); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/OldApCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/OldApCubeEntity.java index cac323be..afc0f995 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/OldApCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/OldApCubeEntity.java @@ -5,9 +5,9 @@ import net.minecraft.world.level.Level; public class OldApCubeEntity extends CorePhysicsEntity { - public OldApCubeEntity(EntityType type, Level world) { - super(type, world); - } + public OldApCubeEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/Portal.java b/src/main/java/com/fusionflux/portalcubed/entity/Portal.java index b7c867e7..1a136cc7 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/Portal.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/Portal.java @@ -47,677 +47,677 @@ public class Portal extends Entity { - public static final Supplier NOT_INIT = - () -> new IllegalStateException("Portal data accessed before initialized"); - - private static final IPQuaternion FLIP_AXIS_W = IPQuaternion.rotationByDegrees( - new Vec3(0, 1, 0), 180 - ).fixFloatingPointErrorAccumulation(); - - public static final AABB NULL_BOX = new AABB(0, 0, 0, 0, 0, 0); - - public static final double SURFACE_OFFSET = 0.01; - - private static final double WIDTH = 0.9, HEIGHT = 1.9; - private static final double EPSILON = 1.0E-7; - - private static final Vec3 AXIS_W = new Vec3(1, 0, 0); - private static final Vec3 AXIS_H = new Vec3(0, -1, 0); - private static final Vec3 NORMAL = new Vec3(0, 0, -1); - - private AABB cutoutBoundingBox = NULL_BOX; - - private static final EntityDataAccessor ROTATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.LERPED_QUAT); - private static final EntityDataAccessor> OTHER_ROTATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.OPTIONAL_QUAT); - public static final EntityDataAccessor> LINKED_PORTAL_UUID = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.OPTIONAL_UUID); - public static final EntityDataAccessor IS_ACTIVE = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.BOOLEAN); - public static final EntityDataAccessor COLOR = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.INT); - public static final EntityDataAccessor> DESTINATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.OPTIONAL_VEC3D); - public static final EntityDataAccessor> OWNER_UUID = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.OPTIONAL_UUID); - - private boolean disableValidation = false; - private Vec3 axisW, axisH, normal; - private Optional otherAxisW = Optional.empty(), otherAxisH = Optional.empty(), otherNormal = Optional.empty(); - private IPQuaternion transformQuat; - - private final List> listeningEntities = new ArrayList<>(); - - public Portal(EntityType entityType, Level world) { - super(entityType, world); - } - - @Override - protected void defineSynchedData() { - this.getEntityData().define(ROTATION, new LerpedQuaternion(new Quaternionf()).withUpdateCallback(this::onRotationUpdate)); - this.getEntityData().define(OTHER_ROTATION, Optional.empty()); - this.getEntityData().define(LINKED_PORTAL_UUID, Optional.empty()); - this.getEntityData().define(IS_ACTIVE, false); - this.getEntityData().define(COLOR, 0); - this.getEntityData().define(DESTINATION, Optional.empty()); - this.getEntityData().define(OWNER_UUID, Optional.empty()); - } - - @Override - protected void readAdditionalSaveData(CompoundTag nbt) { - this.setColor(nbt.getInt("color")); - setRotation(LerpedQuaternion.fromNbt(nbt.getCompound("PortalRotation"))); - if (nbt.contains("OtherRotation")) { - setOtherRotation(Optional.of(NbtHelper.getQuaternion(nbt, "OtherRotation"))); - } else { - setOtherRotation(Optional.empty()); - } - if (nbt.hasUUID("linkedPortalUUID")) this.setLinkedPortalUUID(Optional.of(nbt.getUUID("linkedPortalUUID"))); - if (nbt.contains("destination")) this.setDestination(Optional.of(NbtHelper.getVec3d(nbt, "destination"))); - if (nbt.hasUUID("ownerUUID")) this.setOwnerUUID(Optional.of(nbt.getUUID("ownerUUID"))); - disableValidation = nbt.getBoolean("DisableValidation"); - if (level() instanceof ServerLevel level) { - listeningEntities.clear(); - int sources = nbt.getInt("Listeners"); - for (int i = 0; i < sources; i++) { - UUID id = nbt.getUUID("Listener" + i); - listeningEntities.add(new EntityReference<>(level, id, PortalListeningEntity.class)); - } - } - } - - @Override - protected void addAdditionalSaveData(CompoundTag nbt) { - nbt.putFloat("color", this.getColor()); - nbt.put("PortalRotation", getRotation().toNbt()); - getOtherRotation().ifPresent(r -> NbtHelper.putQuaternion(nbt, "OtherRotation", r)); - this.getLinkedPortalUUID().ifPresent(uuid -> nbt.putUUID("linkedPortalUUID", uuid)); - this.getDestination().ifPresent(destination -> NbtHelper.putVec3d(nbt, "destination", destination)); - this.getOwnerUUID().ifPresent(uuid -> nbt.putUUID("ownerUUID", uuid)); - nbt.putBoolean("DisableValidation", disableValidation); - listeningEntities.removeIf(EntityReference::isUnloaded); - nbt.putInt("Listeners", listeningEntities.size()); - for (int i = 0; i < listeningEntities.size(); i++) { - nbt.putUUID("Listener" + i, listeningEntities.get(i).uuid); - } - } - - public int getColor() { - return getEntityData().get(COLOR); - } - - public void setColor(int color) { - this.getEntityData().set(COLOR, color); - } - - public Optional getLinkedPortalUUID() { - return getEntityData().get(LINKED_PORTAL_UUID); - } - - public void setLinkedPortalUUID(Optional uuid) { - this.getEntityData().set(LINKED_PORTAL_UUID, uuid); - } - - public Optional getOwnerUUID() { - return getEntityData().get(OWNER_UUID); - } - - public void setOwnerUUID(Optional uuid) { - this.getEntityData().set(OWNER_UUID, uuid); - } - - public boolean getActive() { - return getEntityData().get(IS_ACTIVE); - } - - private void setActive(boolean active) { - this.getEntityData().set(IS_ACTIVE, active); - } - - /** - * Unless you need axis alignment, this method should be avoided, and methods based off of - * {@link #getRotation()} or {@link #getNormal()} should be used instead. - * @return The closest direction to the portal's rotation - * @see #getRotation() - * @see #getNormal() - */ - public Direction getFacingDirection() { - final Vec3 normal = getNormal(); - final double x = normal.x, y = normal.y, z = normal.z; - final Direction result = Direction.fromDelta((int)x, (int)y, (int)z); - return result != null ? result : Direction.getNearest(x, y, z); - } - - public LerpedQuaternion getRotation() { - return getEntityData().get(ROTATION); - } - - public void setRotation(Quaternionf rotation) { - setRotation(new LerpedQuaternion(rotation)); - } - - public void setRotation(LerpedQuaternion rotation) { - getEntityData().set(ROTATION, rotation.withUpdateCallback(this::onRotationUpdate)); - } - - public Optional getOtherRotation() { - return getEntityData().get(OTHER_ROTATION); - } - - public void setOtherRotation(Optional rotation) { - getEntityData().set(OTHER_ROTATION, rotation); - } - - private Vec3 applyAxis(Vec3 axis) { - return IPQuaternion.fromQuaternionf(getRotation().get()).rotate(axis, true); - } - - public Vec3 getAxisW() { - return axisW == null ? (axisW = applyAxis(AXIS_W)) : axisW; - } - - public Vec3 getAxisH() { - return axisH == null ? (axisH = applyAxis(AXIS_H)) : axisH; - } - - public Vec3 getNormal() { - return normal == null ? (normal = applyAxis(NORMAL)) : normal; - } - - private Optional applyOtherAxis(Vec3 axis) { - return getOtherRotation().map(r -> IPQuaternion.fromQuaternionf(r).rotate(axis, true)); - } - - public Optional getOtherAxisW() { - return otherAxisW.isEmpty() ? (otherAxisW = applyOtherAxis(AXIS_W)) : otherAxisW; - } - - public Optional getOtherAxisH() { - return otherAxisH.isEmpty() ? (otherAxisH = applyOtherAxis(AXIS_H)) : otherAxisH; - } - - public Optional getOtherNormal() { - return otherNormal.isEmpty() ? (otherNormal = applyOtherAxis(NORMAL)) : otherNormal; - } - - public Optional getDestination() { - return getEntityData().get(DESTINATION); - } - - public void setDestination(Optional destination) { - this.getEntityData().set(DESTINATION, destination); - } - - @Nullable - public Portal findLinkedPortal() { - if (!(level() instanceof ServerLevel level)) - return null; - Optional linkedId = getLinkedPortalUUID(); - if (linkedId.isEmpty()) - return null; - Entity linkedEntity = level.getEntity(linkedId.get()); - return linkedEntity instanceof Portal linked && linked.isAlive() ? linked : null; - } - - @Override - public void kill() { - super.kill(); - notifyListeners(true); - if (level() instanceof ServerLevel level) { - getOwnerUUID().ifPresent(uuid -> { - Entity player = level.getEntity(uuid); - CalledValues.removePortals(player, this.getUUID()); - }); - forEachListeningEntity(entity -> entity.onPortalRemove(this)); - } - } - - @Override - public void tick() { - final ProfilerFiller profiler = level().getProfiler(); - profiler.push("portalTick"); - - this.makeBoundingBox(); - this.calculateCutoutBox(); - - getRotation().tick(); - - if (!this.level().isClientSide) { - final ServerLevel serverLevel = (ServerLevel)level(); - serverLevel.getChunkSource().addRegionTicket(TicketType.PORTAL, chunkPosition(), 2, blockPosition()); - - getOwnerUUID().ifPresent(uuid -> { - Entity player = serverLevel.getEntity(uuid); - if (player == null || !player.isAlive() && tickCount > 5) { // tickCount: slight delay on world load for listeners to load - this.kill(); - } - }); - - Portal otherPortal = - this.getLinkedPortalUUID().isPresent() - ? (Portal)serverLevel.getEntity(this.getLinkedPortalUUID().get()) - : null; - - setActive(otherPortal != null); - setDestination(Optional.of(Objects.requireNonNullElse(otherPortal, this).getOriginPos())); - - if (!validate()) { - this.kill(); - level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ENTITY_PORTAL_CLOSE, SoundSource.NEUTRAL, .1F, 1F); - } - - } - - profiler.pop(); - super.tick(); - } - - @Override - public void onSyncedDataUpdated(EntityDataAccessor key) { - super.onSyncedDataUpdated(key); - if (ROTATION.equals(key)) { - axisW = axisH = normal = null; - transformQuat = null; - makeBoundingBox(); - } else if (OTHER_ROTATION.equals(key)) { - otherAxisW = otherAxisH = otherNormal = Optional.empty(); - transformQuat = null; - } - } - - public void setDisableValidation(boolean disableValidation) { - this.disableValidation = disableValidation; - } - - public boolean validate() { - if (disableValidation) { - return true; - } - return validateCommon() && validateBehind() && validateFront(); - } - - private boolean validateCommon() { - return insideWorldBorder(getBoundingBox(), level().getWorldBorder()); - } - - private static boolean insideWorldBorder(AABB bb, WorldBorder border) { - return - bb.minX >= Math.floor(border.getMinX()) && - bb.maxX <= Math.ceil(border.getMaxX()) && - bb.minZ >= Math.floor(border.getMinZ()) && - bb.maxZ <= Math.ceil(border.getMaxZ()); - } - - private boolean validateBehind() { - final AABB portalBox = new AABB( - getPointInPlane(width() / 2, height() / 2) - .add(getNormal().scale(-0.01)), - getPointInPlane(-width() / 2, -height() / 2) - .add(getNormal().scale(-0.2)) - ).minmax(new AABB( - getPointInPlane(-width() / 2, height() / 2) - .add(getNormal().scale(-0.01)), - getPointInPlane(width() / 2, -height() / 2) - .add(getNormal().scale(-0.2)) - )); - final Cursor3D iter = new Cursor3D( - Mth.floor(portalBox.minX - EPSILON) - 1, - Mth.floor(portalBox.minY - EPSILON) - 1, - Mth.floor(portalBox.minZ - EPSILON) - 1, - Mth.floor(portalBox.maxX + EPSILON) + 1, - Mth.floor(portalBox.maxY + EPSILON) + 1, - Mth.floor(portalBox.maxZ + EPSILON) + 1 - ); - Direction forward = getFacingDirection(); - BooleanProperty coveringWall = MultifaceBlock.getFaceProperty(forward.getOpposite()); - Player owner = getOwnerUUID().map(level()::getPlayerByUUID).orElse(null); - while (iter.advance()) { - final BlockPos pos = new BlockPos(iter.nextX(), iter.nextY(), iter.nextZ()); - if (!AABB.of(BoundingBox.fromCorners(pos, pos)).intersects(portalBox)) continue; - - BlockState wall = level().getBlockState(pos); - BlockState facade = level().getBlockState(pos.relative(forward)); - BlockState portalSurface; - if (!facade.is(PortalCubedBlocks.PORTAL_NONSOLID) && // non-solids fallback to the wall - facade.getOptionalValue(coveringWall).orElse(Boolean.FALSE)) { // if property is present and true, facade covers the wall - if (!facade.is(PortalCubedBlocks.PORTALABLE_GELS)) - return false; // cannot support portals - portalSurface = facade; - } else { // no facade, check the wall directly - if (wall.is(PortalCubedBlocks.PORTAL_NONSOLID) || wall.is(PortalCubedBlocks.CANT_PLACE_PORTAL_ON)) - return false; // cannot support portals - portalSurface = wall; - } - if (owner != null && !owner.getAbilities().mayBuild && !owner.isSpectator()) { // finally, check if the surface is valid in adventure mode - if (!portalSurface.is(PortalCubedBlocks.PORTALABLE_IN_ADVENTURE)) - return false; - } - - final VoxelShape shape = wall.getCollisionShape(level(), pos, CollisionContext.of(this)); - if ( - shape.move(pos.getX(), pos.getY(), pos.getZ()) - .toAabbs() - .stream() - .noneMatch(portalBox::intersects) - ) return false; - } - return true; - } - - private boolean validateFront() { - final AABB portalBox = new AABB( - getPointInPlane(width() / 2, height() / 2) - .add(getNormal().scale(0.2)), - getPointInPlane(-width() / 2, -height() / 2) - ).minmax(new AABB( - getPointInPlane(-width() / 2, height() / 2) - .add(getNormal().scale(0.2)), - getPointInPlane(width() / 2, -height() / 2) - )); - final Cursor3D iter = new Cursor3D( - Mth.floor(portalBox.minX - EPSILON) - 1, - Mth.floor(portalBox.minY - EPSILON) - 1, - Mth.floor(portalBox.minZ - EPSILON) - 1, - Mth.floor(portalBox.maxX + EPSILON) + 1, - Mth.floor(portalBox.maxY + EPSILON) + 1, - Mth.floor(portalBox.maxZ + EPSILON) + 1 - ); - while (iter.advance()) { - final BlockPos pos = new BlockPos(iter.nextX(), iter.nextY(), iter.nextZ()); - if (!AABB.of(BoundingBox.fromCorners(pos, pos)).intersects(portalBox)) continue; - final BlockState state = level().getBlockState(pos); - if (state.is(PortalCubedBlocks.PORTAL_NONSOLID)) continue; - if (state.is(PortalCubedBlocks.PORTAL_SOLID)) { - return false; - } - final VoxelShape shape = state.getCollisionShape(level(), pos, CollisionContext.of(this)); - if ( - shape.move(pos.getX(), pos.getY(), pos.getZ()) - .toAabbs() - .stream() - .anyMatch(portalBox::intersects) - ) return false; - } - return true; - } - - private void onRotationUpdate(LerpedQuaternion quaternion) { - getEntityData().set(ROTATION, quaternion.copy()); // update on the other side, server/client - } - - public boolean isGridAligned() { - return position().subtract(getGridAlignedPos()).lengthSqr() < EPSILON; - } - - public boolean snapToGrid() { - Vec3 newPos = getGridAlignedPos(); - Vec3 offset = newPos.subtract(position()); - if (offset.lengthSqr() < EPSILON) - return true; - AABB movedBounds = getBoundingBox().move(offset); - List intersecting = level().getEntitiesOfClass(Portal.class, movedBounds.inflate(0.1), portal -> portal != this); - if (!intersecting.isEmpty()) - return false; - setPos(newPos); - return true; - } - - private Vec3 getGridAlignedPos() { - Direction facing = getFacingDirection(); - - Axis forwards = facing.getAxis(); - Vec3 down = getRelativeDown(); - Axis vertical = Direction.getNearest(down.x, down.y, down.z).getAxis(); - Axis horizontal = Axis.X; - // just find whichever hasn't been chosen yet - for (Axis axis : Axis.VALUES) { - if (axis != forwards && axis != vertical) { - horizontal = axis; - break; - } - } - - Vec3 pos = position(); - MutableVec3 newPos = new MutableVec3(); - for (Axis axis : Axis.VALUES) { - if (axis == forwards) { // forwards axis: leave alone, same offset from wall - newPos.set(axis, pos.get(axis)); - } else if (axis == vertical) { // vertical axis: round to 0 - newPos.set(axis, Math.floor(pos.get(axis))); - } else if (axis == horizontal) { // horizontal axis: round to 0.5 - newPos.set(axis, Math.floor(pos.get(axis)) + 0.5); - } - } - return new Vec3(newPos.x, newPos.y, newPos.z); - } - - public Vec3 getRelativeDown() { - Vector3f transformed = getRotation().get().transform(new Vector3f(0, -1, 0)); - return new Vec3(transformed); - } - - @Deprecated(forRemoval = true) // removing this once light bridges are ported to entities - public void notifyListeners(boolean removed) { - if (level() instanceof ServerLevel level) { - Vec3 offset = Vec3.atBottomCenterOf(getFacingDirection().getNormal()).scale(0.5); - AABB bounds = getBoundingBox().move(offset).inflate(-0.1); - BlockPos.betweenClosedStream(bounds).forEach(pos -> { - BlockState state = level.getBlockState(pos); - if (state.getBlock() instanceof PortalMoveListeningBlock listener) { - if (removed) { - listener.beforePortalRemove(level, state, pos, this); - } else { - listener.onPortalCreate(level, state, pos, this); - } - } - }); - } - } - - @NotNull - @Override - protected AABB makeBoundingBox() { - AABB portalBox = new AABB( - getPointInPlane(width() / 2, height() / 2) - .add(getNormal().scale(.0)), - getPointInPlane(-width() / 2, -height() / 2) - .add(getNormal().scale(-.2)) - ).minmax(new AABB( - getPointInPlane(-width() / 2, height() / 2) - .add(getNormal().scale(.0)), - getPointInPlane(width() / 2, -height() / 2) - .add(getNormal().scale(-.2)) - )); - setBoundingBox(portalBox); - return portalBox; - } - - public AABB calculateCutoutBox() { - AABB portalBox = new AABB( - getCutoutPointInPlane(width() / 2, height() / 2) - .add(getNormal().scale(5)), - getCutoutPointInPlane(-width() / 2, -height() / 2) - .add(getNormal().scale(-5)) - ).minmax(new AABB( - getCutoutPointInPlane(-width() / 2, height() / 2) - .add(getNormal().scale(5)), - getCutoutPointInPlane(width() / 2, -height() / 2) - .add(getNormal().scale(-5)) - )); - setCutoutBoundingBox(portalBox); - return portalBox; - } - - - public AABB calculateBoundsCheckBox() { - return new AABB( - getBoundsCheckPointInPlane(width() / 2, height() / 2) - .add(getNormal().scale(2.5)), - getBoundsCheckPointInPlane(-width() / 2, -height() / 2) - .add(getNormal().scale(-2.5)) - ).minmax(new AABB( - getBoundsCheckPointInPlane(-width() / 2, height() / 2) - .add(getNormal().scale(2.5)), - getBoundsCheckPointInPlane(width() / 2, -height() / 2) - .add(getNormal().scale(-2.5)) - )); - } - - public final AABB getCutoutBoundingBox() { - return this.cutoutBoundingBox; - } - - public final void setCutoutBoundingBox(AABB boundingBox) { - this.cutoutBoundingBox = boundingBox; - } - - public VoxelShape getCrossPortalCollisionShapeOther(Entity context) { - // getActive() returning true asserts that these parameters return present Optionals - //noinspection OptionalGetWithoutIsPresent - return getActive() - ? calculateCrossPortalCollisionShape(getOtherNormal().get(), getDestination().get(), getOtherRotation().get(), context) - : Shapes.empty(); - } - - private VoxelShape calculateCrossPortalCollisionShape(Vec3 normal, Vec3 origin, Quaternionf otherRotation, Entity context) { - origin = origin.subtract(normal.scale(SURFACE_OFFSET)); - final Direction facing = Direction.getNearest(normal.x, normal.y, normal.z); - final AABB clipping = GeneralUtil.capAABBAt( - origin.subtract(2, 2, 2), - origin.add(2, 2, 2), - facing, origin - ); - final VoxelShape clippingShape = Shapes.create(clipping); - final List shapes = new ArrayList<>(); - for (final VoxelShape shape : level().getBlockCollisions(context, clipping)) { - final VoxelShape clippedShape = - clipping.contains(shape.min(Axis.X), shape.min(Axis.Y), shape.min(Axis.Z)) && - clipping.contains(shape.max(Axis.X), shape.max(Axis.Y), shape.max(Axis.Z)) - ? shape : Shapes.joinUnoptimized(shape, clippingShape, BooleanOp.AND); - shapes.add(clippedShape); - } - if (!shapes.isEmpty() /* Empty shapes don't need to be translated */) { - final Vec3 scaledNormalOffset = getNormal().scale(SURFACE_OFFSET); - if (facing != getFacingDirection().getOpposite()) { - final IPQuaternion transform = getTransformQuat().getConjugated(); - final MutableObject result = new MutableObject<>(Shapes.empty()); - final double originX = origin.x; - final double originY = origin.y; - final double originZ = origin.z; - final double ox = getX() - scaledNormalOffset.x; - final double oy = getY() - scaledNormalOffset.y; - final double oz = getZ() - scaledNormalOffset.z; - for (VoxelShape shape : shapes) { - shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> { - final Vec3 minT = transform.rotate(new Vec3(x1 - originX, y1 - originY, z1 - originZ), false); - final Vec3 maxT = transform.rotate(new Vec3(x2 - originX, y2 - originY, z2 - originZ), false); - result.setValue(Shapes.joinUnoptimized( - result.getValue(), - Shapes.box( - Math.min(minT.x, maxT.x) + ox, - Math.min(minT.y, maxT.y) + oy, - Math.min(minT.z, maxT.z) + oz, - Math.max(minT.x, maxT.x) + ox, - Math.max(minT.y, maxT.y) + oy, - Math.max(minT.z, maxT.z) + oz - ), - BooleanOp.OR - )); - }); - } - return result.getValue(); - } else { - VoxelShape result = Shapes.empty(); - final double ox = getX() - origin.x - scaledNormalOffset.x; - final double oy = getY() - origin.y - scaledNormalOffset.y; - final double oz = getZ() - origin.z - scaledNormalOffset.z; - for (VoxelShape shape : shapes) { - result = Shapes.joinUnoptimized(result, shape.move(ox, oy, oz), BooleanOp.OR); - } - return result; - } - } - return Shapes.empty(); - } - - public Vec3 getCutoutPointInPlane(double xInPlane, double yInPlane) { - return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)).add(getFacingDirection().step().x() * -5, getFacingDirection().step().y() * -5, getFacingDirection().step().z() * -5); - } - - public Vec3 getBoundsCheckPointInPlane(double xInPlane, double yInPlane) { - return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)).add(getFacingDirection().step().x() * 2.5, getFacingDirection().step().y() * 2.5, getFacingDirection().step().z() * 2.5); - } - - public Vec3 getPointInPlane(double xInPlane, double yInPlane) { - return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)); - } - - public Vec3 getPointInPlaneLocal(double xInPlane, double yInPlane) { - return getAxisW().scale(xInPlane).add(getAxisH().scale(yInPlane)); - } - - public Vector2d getLocalPlaneCoords(Vec3 vec) { - Axis facingAxis = getFacingDirection().getAxis(); - Vec3 pos = position(); - Vec3 inPlane = vec.with(facingAxis, pos.get(facingAxis)); - Vec3 relative = inPlane.subtract(pos); - Axis horizontal = axisOf(getAxisW()); - Axis vertical = axisOf(getAxisH()); - return new Vector2d(horizontal.choose(relative.x, relative.y, relative.z), vertical.choose(relative.x, relative.y, relative.z)); - } - - public Vec3 getOriginPos() { - return position(); - } - - public void setOriginPos(Vec3 pos) { - setPos(pos); - } - - private double width() { - return WIDTH * PehkuiScaleTypes.HITBOX_WIDTH.getScaleData(this).getScale(); - } - - private double height() { - return HEIGHT * PehkuiScaleTypes.HITBOX_HEIGHT.getScaleData(this).getScale(); - } - - public IPQuaternion getTransformQuat() { - if (transformQuat != null) { - return transformQuat; - } - final IPQuaternion myRotation = IPQuaternion.fromQuaternionf(getRotation().get()); - final IPQuaternion otherRotation = IPQuaternion.fromQuaternionf(getOtherRotation().orElseThrow(NOT_INIT)); - return transformQuat = otherRotation - .hamiltonProduct(FLIP_AXIS_W) - .hamiltonProduct(myRotation.getConjugated()); - } - - public void addListener(PortalListeningEntity source) { - if (level() instanceof ServerLevel level) { - this.listeningEntities.add(new EntityReference<>(level, source)); - } - } - - public void forEachListeningEntity(Consumer consumer) { - Iterator> itr = listeningEntities.iterator(); - while (itr.hasNext()) { - EntityReference entity = itr.next(); - if (entity.isLoaded()) { - consumer.accept(entity.get()); - } else { - itr.remove(); - } - } - } - - public void notifyListenersOfCreation() { - if (level() instanceof ServerLevel level) { - for (PortalListeningEntity entity : level.getEntities(PortalListeningEntity.TYPE_TEST, Entity::isAlive)) { - entity.onPortalCreate(this); - } - } - } - - private static Axis axisOf(Vec3 axisVec) { - for (Axis axis : Axis.VALUES) { - if (axisVec.get(axis) != 0) - return axis; - } - throw new IllegalArgumentException("axisVec is ZERO"); - } + public static final Supplier NOT_INIT = + () -> new IllegalStateException("Portal data accessed before initialized"); + + private static final IPQuaternion FLIP_AXIS_W = IPQuaternion.rotationByDegrees( + new Vec3(0, 1, 0), 180 + ).fixFloatingPointErrorAccumulation(); + + public static final AABB NULL_BOX = new AABB(0, 0, 0, 0, 0, 0); + + public static final double SURFACE_OFFSET = 0.01; + + private static final double WIDTH = 0.9, HEIGHT = 1.9; + private static final double EPSILON = 1.0E-7; + + private static final Vec3 AXIS_W = new Vec3(1, 0, 0); + private static final Vec3 AXIS_H = new Vec3(0, -1, 0); + private static final Vec3 NORMAL = new Vec3(0, 0, -1); + + private AABB cutoutBoundingBox = NULL_BOX; + + private static final EntityDataAccessor ROTATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.LERPED_QUAT); + private static final EntityDataAccessor> OTHER_ROTATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.OPTIONAL_QUAT); + public static final EntityDataAccessor> LINKED_PORTAL_UUID = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.OPTIONAL_UUID); + public static final EntityDataAccessor IS_ACTIVE = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.BOOLEAN); + public static final EntityDataAccessor COLOR = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.INT); + public static final EntityDataAccessor> DESTINATION = SynchedEntityData.defineId(Portal.class, PortalCubedTrackedDataHandlers.OPTIONAL_VEC3D); + public static final EntityDataAccessor> OWNER_UUID = SynchedEntityData.defineId(Portal.class, EntityDataSerializers.OPTIONAL_UUID); + + private boolean disableValidation = false; + private Vec3 axisW, axisH, normal; + private Optional otherAxisW = Optional.empty(), otherAxisH = Optional.empty(), otherNormal = Optional.empty(); + private IPQuaternion transformQuat; + + private final List> listeningEntities = new ArrayList<>(); + + public Portal(EntityType entityType, Level world) { + super(entityType, world); + } + + @Override + protected void defineSynchedData() { + this.getEntityData().define(ROTATION, new LerpedQuaternion(new Quaternionf()).withUpdateCallback(this::onRotationUpdate)); + this.getEntityData().define(OTHER_ROTATION, Optional.empty()); + this.getEntityData().define(LINKED_PORTAL_UUID, Optional.empty()); + this.getEntityData().define(IS_ACTIVE, false); + this.getEntityData().define(COLOR, 0); + this.getEntityData().define(DESTINATION, Optional.empty()); + this.getEntityData().define(OWNER_UUID, Optional.empty()); + } + + @Override + protected void readAdditionalSaveData(CompoundTag nbt) { + this.setColor(nbt.getInt("color")); + setRotation(LerpedQuaternion.fromNbt(nbt.getCompound("PortalRotation"))); + if (nbt.contains("OtherRotation")) { + setOtherRotation(Optional.of(NbtHelper.getQuaternion(nbt, "OtherRotation"))); + } else { + setOtherRotation(Optional.empty()); + } + if (nbt.hasUUID("linkedPortalUUID")) this.setLinkedPortalUUID(Optional.of(nbt.getUUID("linkedPortalUUID"))); + if (nbt.contains("destination")) this.setDestination(Optional.of(NbtHelper.getVec3d(nbt, "destination"))); + if (nbt.hasUUID("ownerUUID")) this.setOwnerUUID(Optional.of(nbt.getUUID("ownerUUID"))); + disableValidation = nbt.getBoolean("DisableValidation"); + if (level() instanceof ServerLevel level) { + listeningEntities.clear(); + int sources = nbt.getInt("Listeners"); + for (int i = 0; i < sources; i++) { + UUID id = nbt.getUUID("Listener" + i); + listeningEntities.add(new EntityReference<>(level, id, PortalListeningEntity.class)); + } + } + } + + @Override + protected void addAdditionalSaveData(CompoundTag nbt) { + nbt.putFloat("color", this.getColor()); + nbt.put("PortalRotation", getRotation().toNbt()); + getOtherRotation().ifPresent(r -> NbtHelper.putQuaternion(nbt, "OtherRotation", r)); + this.getLinkedPortalUUID().ifPresent(uuid -> nbt.putUUID("linkedPortalUUID", uuid)); + this.getDestination().ifPresent(destination -> NbtHelper.putVec3d(nbt, "destination", destination)); + this.getOwnerUUID().ifPresent(uuid -> nbt.putUUID("ownerUUID", uuid)); + nbt.putBoolean("DisableValidation", disableValidation); + listeningEntities.removeIf(EntityReference::isUnloaded); + nbt.putInt("Listeners", listeningEntities.size()); + for (int i = 0; i < listeningEntities.size(); i++) { + nbt.putUUID("Listener" + i, listeningEntities.get(i).uuid); + } + } + + public int getColor() { + return getEntityData().get(COLOR); + } + + public void setColor(int color) { + this.getEntityData().set(COLOR, color); + } + + public Optional getLinkedPortalUUID() { + return getEntityData().get(LINKED_PORTAL_UUID); + } + + public void setLinkedPortalUUID(Optional uuid) { + this.getEntityData().set(LINKED_PORTAL_UUID, uuid); + } + + public Optional getOwnerUUID() { + return getEntityData().get(OWNER_UUID); + } + + public void setOwnerUUID(Optional uuid) { + this.getEntityData().set(OWNER_UUID, uuid); + } + + public boolean getActive() { + return getEntityData().get(IS_ACTIVE); + } + + private void setActive(boolean active) { + this.getEntityData().set(IS_ACTIVE, active); + } + + /** + * Unless you need axis alignment, this method should be avoided, and methods based off of + * {@link #getRotation()} or {@link #getNormal()} should be used instead. + * @return The closest direction to the portal's rotation + * @see #getRotation() + * @see #getNormal() + */ + public Direction getFacingDirection() { + final Vec3 normal = getNormal(); + final double x = normal.x, y = normal.y, z = normal.z; + final Direction result = Direction.fromDelta((int)x, (int)y, (int)z); + return result != null ? result : Direction.getNearest(x, y, z); + } + + public LerpedQuaternion getRotation() { + return getEntityData().get(ROTATION); + } + + public void setRotation(Quaternionf rotation) { + setRotation(new LerpedQuaternion(rotation)); + } + + public void setRotation(LerpedQuaternion rotation) { + getEntityData().set(ROTATION, rotation.withUpdateCallback(this::onRotationUpdate)); + } + + public Optional getOtherRotation() { + return getEntityData().get(OTHER_ROTATION); + } + + public void setOtherRotation(Optional rotation) { + getEntityData().set(OTHER_ROTATION, rotation); + } + + private Vec3 applyAxis(Vec3 axis) { + return IPQuaternion.fromQuaternionf(getRotation().get()).rotate(axis, true); + } + + public Vec3 getAxisW() { + return axisW == null ? (axisW = applyAxis(AXIS_W)) : axisW; + } + + public Vec3 getAxisH() { + return axisH == null ? (axisH = applyAxis(AXIS_H)) : axisH; + } + + public Vec3 getNormal() { + return normal == null ? (normal = applyAxis(NORMAL)) : normal; + } + + private Optional applyOtherAxis(Vec3 axis) { + return getOtherRotation().map(r -> IPQuaternion.fromQuaternionf(r).rotate(axis, true)); + } + + public Optional getOtherAxisW() { + return otherAxisW.isEmpty() ? (otherAxisW = applyOtherAxis(AXIS_W)) : otherAxisW; + } + + public Optional getOtherAxisH() { + return otherAxisH.isEmpty() ? (otherAxisH = applyOtherAxis(AXIS_H)) : otherAxisH; + } + + public Optional getOtherNormal() { + return otherNormal.isEmpty() ? (otherNormal = applyOtherAxis(NORMAL)) : otherNormal; + } + + public Optional getDestination() { + return getEntityData().get(DESTINATION); + } + + public void setDestination(Optional destination) { + this.getEntityData().set(DESTINATION, destination); + } + + @Nullable + public Portal findLinkedPortal() { + if (!(level() instanceof ServerLevel level)) + return null; + Optional linkedId = getLinkedPortalUUID(); + if (linkedId.isEmpty()) + return null; + Entity linkedEntity = level.getEntity(linkedId.get()); + return linkedEntity instanceof Portal linked && linked.isAlive() ? linked : null; + } + + @Override + public void kill() { + super.kill(); + notifyListeners(true); + if (level() instanceof ServerLevel level) { + getOwnerUUID().ifPresent(uuid -> { + Entity player = level.getEntity(uuid); + CalledValues.removePortals(player, this.getUUID()); + }); + forEachListeningEntity(entity -> entity.onPortalRemove(this)); + } + } + + @Override + public void tick() { + final ProfilerFiller profiler = level().getProfiler(); + profiler.push("portalTick"); + + this.makeBoundingBox(); + this.calculateCutoutBox(); + + getRotation().tick(); + + if (!this.level().isClientSide) { + final ServerLevel serverLevel = (ServerLevel)level(); + serverLevel.getChunkSource().addRegionTicket(TicketType.PORTAL, chunkPosition(), 2, blockPosition()); + + getOwnerUUID().ifPresent(uuid -> { + Entity player = serverLevel.getEntity(uuid); + if (player == null || !player.isAlive() && tickCount > 5) { // tickCount: slight delay on world load for listeners to load + this.kill(); + } + }); + + Portal otherPortal = + this.getLinkedPortalUUID().isPresent() + ? (Portal)serverLevel.getEntity(this.getLinkedPortalUUID().get()) + : null; + + setActive(otherPortal != null); + setDestination(Optional.of(Objects.requireNonNullElse(otherPortal, this).getOriginPos())); + + if (!validate()) { + this.kill(); + level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ENTITY_PORTAL_CLOSE, SoundSource.NEUTRAL, .1F, 1F); + } + + } + + profiler.pop(); + super.tick(); + } + + @Override + public void onSyncedDataUpdated(EntityDataAccessor key) { + super.onSyncedDataUpdated(key); + if (ROTATION.equals(key)) { + axisW = axisH = normal = null; + transformQuat = null; + makeBoundingBox(); + } else if (OTHER_ROTATION.equals(key)) { + otherAxisW = otherAxisH = otherNormal = Optional.empty(); + transformQuat = null; + } + } + + public void setDisableValidation(boolean disableValidation) { + this.disableValidation = disableValidation; + } + + public boolean validate() { + if (disableValidation) { + return true; + } + return validateCommon() && validateBehind() && validateFront(); + } + + private boolean validateCommon() { + return insideWorldBorder(getBoundingBox(), level().getWorldBorder()); + } + + private static boolean insideWorldBorder(AABB bb, WorldBorder border) { + return + bb.minX >= Math.floor(border.getMinX()) && + bb.maxX <= Math.ceil(border.getMaxX()) && + bb.minZ >= Math.floor(border.getMinZ()) && + bb.maxZ <= Math.ceil(border.getMaxZ()); + } + + private boolean validateBehind() { + final AABB portalBox = new AABB( + getPointInPlane(width() / 2, height() / 2) + .add(getNormal().scale(-0.01)), + getPointInPlane(-width() / 2, -height() / 2) + .add(getNormal().scale(-0.2)) + ).minmax(new AABB( + getPointInPlane(-width() / 2, height() / 2) + .add(getNormal().scale(-0.01)), + getPointInPlane(width() / 2, -height() / 2) + .add(getNormal().scale(-0.2)) + )); + final Cursor3D iter = new Cursor3D( + Mth.floor(portalBox.minX - EPSILON) - 1, + Mth.floor(portalBox.minY - EPSILON) - 1, + Mth.floor(portalBox.minZ - EPSILON) - 1, + Mth.floor(portalBox.maxX + EPSILON) + 1, + Mth.floor(portalBox.maxY + EPSILON) + 1, + Mth.floor(portalBox.maxZ + EPSILON) + 1 + ); + Direction forward = getFacingDirection(); + BooleanProperty coveringWall = MultifaceBlock.getFaceProperty(forward.getOpposite()); + Player owner = getOwnerUUID().map(level()::getPlayerByUUID).orElse(null); + while (iter.advance()) { + final BlockPos pos = new BlockPos(iter.nextX(), iter.nextY(), iter.nextZ()); + if (!AABB.of(BoundingBox.fromCorners(pos, pos)).intersects(portalBox)) continue; + + BlockState wall = level().getBlockState(pos); + BlockState facade = level().getBlockState(pos.relative(forward)); + BlockState portalSurface; + if (!facade.is(PortalCubedBlocks.PORTAL_NONSOLID) && // non-solids fallback to the wall + facade.getOptionalValue(coveringWall).orElse(Boolean.FALSE)) { // if property is present and true, facade covers the wall + if (!facade.is(PortalCubedBlocks.PORTALABLE_GELS)) + return false; // cannot support portals + portalSurface = facade; + } else { // no facade, check the wall directly + if (wall.is(PortalCubedBlocks.PORTAL_NONSOLID) || wall.is(PortalCubedBlocks.CANT_PLACE_PORTAL_ON)) + return false; // cannot support portals + portalSurface = wall; + } + if (owner != null && !owner.getAbilities().mayBuild && !owner.isSpectator()) { // finally, check if the surface is valid in adventure mode + if (!portalSurface.is(PortalCubedBlocks.PORTALABLE_IN_ADVENTURE)) + return false; + } + + final VoxelShape shape = wall.getCollisionShape(level(), pos, CollisionContext.of(this)); + if ( + shape.move(pos.getX(), pos.getY(), pos.getZ()) + .toAabbs() + .stream() + .noneMatch(portalBox::intersects) + ) return false; + } + return true; + } + + private boolean validateFront() { + final AABB portalBox = new AABB( + getPointInPlane(width() / 2, height() / 2) + .add(getNormal().scale(0.2)), + getPointInPlane(-width() / 2, -height() / 2) + ).minmax(new AABB( + getPointInPlane(-width() / 2, height() / 2) + .add(getNormal().scale(0.2)), + getPointInPlane(width() / 2, -height() / 2) + )); + final Cursor3D iter = new Cursor3D( + Mth.floor(portalBox.minX - EPSILON) - 1, + Mth.floor(portalBox.minY - EPSILON) - 1, + Mth.floor(portalBox.minZ - EPSILON) - 1, + Mth.floor(portalBox.maxX + EPSILON) + 1, + Mth.floor(portalBox.maxY + EPSILON) + 1, + Mth.floor(portalBox.maxZ + EPSILON) + 1 + ); + while (iter.advance()) { + final BlockPos pos = new BlockPos(iter.nextX(), iter.nextY(), iter.nextZ()); + if (!AABB.of(BoundingBox.fromCorners(pos, pos)).intersects(portalBox)) continue; + final BlockState state = level().getBlockState(pos); + if (state.is(PortalCubedBlocks.PORTAL_NONSOLID)) continue; + if (state.is(PortalCubedBlocks.PORTAL_SOLID)) { + return false; + } + final VoxelShape shape = state.getCollisionShape(level(), pos, CollisionContext.of(this)); + if ( + shape.move(pos.getX(), pos.getY(), pos.getZ()) + .toAabbs() + .stream() + .anyMatch(portalBox::intersects) + ) return false; + } + return true; + } + + private void onRotationUpdate(LerpedQuaternion quaternion) { + getEntityData().set(ROTATION, quaternion.copy()); // update on the other side, server/client + } + + public boolean isGridAligned() { + return position().subtract(getGridAlignedPos()).lengthSqr() < EPSILON; + } + + public boolean snapToGrid() { + Vec3 newPos = getGridAlignedPos(); + Vec3 offset = newPos.subtract(position()); + if (offset.lengthSqr() < EPSILON) + return true; + AABB movedBounds = getBoundingBox().move(offset); + List intersecting = level().getEntitiesOfClass(Portal.class, movedBounds.inflate(0.1), portal -> portal != this); + if (!intersecting.isEmpty()) + return false; + setPos(newPos); + return true; + } + + private Vec3 getGridAlignedPos() { + Direction facing = getFacingDirection(); + + Axis forwards = facing.getAxis(); + Vec3 down = getRelativeDown(); + Axis vertical = Direction.getNearest(down.x, down.y, down.z).getAxis(); + Axis horizontal = Axis.X; + // just find whichever hasn't been chosen yet + for (Axis axis : Axis.VALUES) { + if (axis != forwards && axis != vertical) { + horizontal = axis; + break; + } + } + + Vec3 pos = position(); + MutableVec3 newPos = new MutableVec3(); + for (Axis axis : Axis.VALUES) { + if (axis == forwards) { // forwards axis: leave alone, same offset from wall + newPos.set(axis, pos.get(axis)); + } else if (axis == vertical) { // vertical axis: round to 0 + newPos.set(axis, Math.floor(pos.get(axis))); + } else if (axis == horizontal) { // horizontal axis: round to 0.5 + newPos.set(axis, Math.floor(pos.get(axis)) + 0.5); + } + } + return new Vec3(newPos.x, newPos.y, newPos.z); + } + + public Vec3 getRelativeDown() { + Vector3f transformed = getRotation().get().transform(new Vector3f(0, -1, 0)); + return new Vec3(transformed); + } + + @Deprecated(forRemoval = true) // removing this once light bridges are ported to entities + public void notifyListeners(boolean removed) { + if (level() instanceof ServerLevel level) { + Vec3 offset = Vec3.atBottomCenterOf(getFacingDirection().getNormal()).scale(0.5); + AABB bounds = getBoundingBox().move(offset).inflate(-0.1); + BlockPos.betweenClosedStream(bounds).forEach(pos -> { + BlockState state = level.getBlockState(pos); + if (state.getBlock() instanceof PortalMoveListeningBlock listener) { + if (removed) { + listener.beforePortalRemove(level, state, pos, this); + } else { + listener.onPortalCreate(level, state, pos, this); + } + } + }); + } + } + + @NotNull + @Override + protected AABB makeBoundingBox() { + AABB portalBox = new AABB( + getPointInPlane(width() / 2, height() / 2) + .add(getNormal().scale(.0)), + getPointInPlane(-width() / 2, -height() / 2) + .add(getNormal().scale(-.2)) + ).minmax(new AABB( + getPointInPlane(-width() / 2, height() / 2) + .add(getNormal().scale(.0)), + getPointInPlane(width() / 2, -height() / 2) + .add(getNormal().scale(-.2)) + )); + setBoundingBox(portalBox); + return portalBox; + } + + public AABB calculateCutoutBox() { + AABB portalBox = new AABB( + getCutoutPointInPlane(width() / 2, height() / 2) + .add(getNormal().scale(5)), + getCutoutPointInPlane(-width() / 2, -height() / 2) + .add(getNormal().scale(-5)) + ).minmax(new AABB( + getCutoutPointInPlane(-width() / 2, height() / 2) + .add(getNormal().scale(5)), + getCutoutPointInPlane(width() / 2, -height() / 2) + .add(getNormal().scale(-5)) + )); + setCutoutBoundingBox(portalBox); + return portalBox; + } + + + public AABB calculateBoundsCheckBox() { + return new AABB( + getBoundsCheckPointInPlane(width() / 2, height() / 2) + .add(getNormal().scale(2.5)), + getBoundsCheckPointInPlane(-width() / 2, -height() / 2) + .add(getNormal().scale(-2.5)) + ).minmax(new AABB( + getBoundsCheckPointInPlane(-width() / 2, height() / 2) + .add(getNormal().scale(2.5)), + getBoundsCheckPointInPlane(width() / 2, -height() / 2) + .add(getNormal().scale(-2.5)) + )); + } + + public final AABB getCutoutBoundingBox() { + return this.cutoutBoundingBox; + } + + public final void setCutoutBoundingBox(AABB boundingBox) { + this.cutoutBoundingBox = boundingBox; + } + + public VoxelShape getCrossPortalCollisionShapeOther(Entity context) { + // getActive() returning true asserts that these parameters return present Optionals + //noinspection OptionalGetWithoutIsPresent + return getActive() + ? calculateCrossPortalCollisionShape(getOtherNormal().get(), getDestination().get(), getOtherRotation().get(), context) + : Shapes.empty(); + } + + private VoxelShape calculateCrossPortalCollisionShape(Vec3 normal, Vec3 origin, Quaternionf otherRotation, Entity context) { + origin = origin.subtract(normal.scale(SURFACE_OFFSET)); + final Direction facing = Direction.getNearest(normal.x, normal.y, normal.z); + final AABB clipping = GeneralUtil.capAABBAt( + origin.subtract(2, 2, 2), + origin.add(2, 2, 2), + facing, origin + ); + final VoxelShape clippingShape = Shapes.create(clipping); + final List shapes = new ArrayList<>(); + for (final VoxelShape shape : level().getBlockCollisions(context, clipping)) { + final VoxelShape clippedShape = + clipping.contains(shape.min(Axis.X), shape.min(Axis.Y), shape.min(Axis.Z)) && + clipping.contains(shape.max(Axis.X), shape.max(Axis.Y), shape.max(Axis.Z)) + ? shape : Shapes.joinUnoptimized(shape, clippingShape, BooleanOp.AND); + shapes.add(clippedShape); + } + if (!shapes.isEmpty() /* Empty shapes don't need to be translated */) { + final Vec3 scaledNormalOffset = getNormal().scale(SURFACE_OFFSET); + if (facing != getFacingDirection().getOpposite()) { + final IPQuaternion transform = getTransformQuat().getConjugated(); + final MutableObject result = new MutableObject<>(Shapes.empty()); + final double originX = origin.x; + final double originY = origin.y; + final double originZ = origin.z; + final double ox = getX() - scaledNormalOffset.x; + final double oy = getY() - scaledNormalOffset.y; + final double oz = getZ() - scaledNormalOffset.z; + for (VoxelShape shape : shapes) { + shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> { + final Vec3 minT = transform.rotate(new Vec3(x1 - originX, y1 - originY, z1 - originZ), false); + final Vec3 maxT = transform.rotate(new Vec3(x2 - originX, y2 - originY, z2 - originZ), false); + result.setValue(Shapes.joinUnoptimized( + result.getValue(), + Shapes.box( + Math.min(minT.x, maxT.x) + ox, + Math.min(minT.y, maxT.y) + oy, + Math.min(minT.z, maxT.z) + oz, + Math.max(minT.x, maxT.x) + ox, + Math.max(minT.y, maxT.y) + oy, + Math.max(minT.z, maxT.z) + oz + ), + BooleanOp.OR + )); + }); + } + return result.getValue(); + } else { + VoxelShape result = Shapes.empty(); + final double ox = getX() - origin.x - scaledNormalOffset.x; + final double oy = getY() - origin.y - scaledNormalOffset.y; + final double oz = getZ() - origin.z - scaledNormalOffset.z; + for (VoxelShape shape : shapes) { + result = Shapes.joinUnoptimized(result, shape.move(ox, oy, oz), BooleanOp.OR); + } + return result; + } + } + return Shapes.empty(); + } + + public Vec3 getCutoutPointInPlane(double xInPlane, double yInPlane) { + return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)).add(getFacingDirection().step().x() * -5, getFacingDirection().step().y() * -5, getFacingDirection().step().z() * -5); + } + + public Vec3 getBoundsCheckPointInPlane(double xInPlane, double yInPlane) { + return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)).add(getFacingDirection().step().x() * 2.5, getFacingDirection().step().y() * 2.5, getFacingDirection().step().z() * 2.5); + } + + public Vec3 getPointInPlane(double xInPlane, double yInPlane) { + return getOriginPos().add(getPointInPlaneLocal(xInPlane, yInPlane)); + } + + public Vec3 getPointInPlaneLocal(double xInPlane, double yInPlane) { + return getAxisW().scale(xInPlane).add(getAxisH().scale(yInPlane)); + } + + public Vector2d getLocalPlaneCoords(Vec3 vec) { + Axis facingAxis = getFacingDirection().getAxis(); + Vec3 pos = position(); + Vec3 inPlane = vec.with(facingAxis, pos.get(facingAxis)); + Vec3 relative = inPlane.subtract(pos); + Axis horizontal = axisOf(getAxisW()); + Axis vertical = axisOf(getAxisH()); + return new Vector2d(horizontal.choose(relative.x, relative.y, relative.z), vertical.choose(relative.x, relative.y, relative.z)); + } + + public Vec3 getOriginPos() { + return position(); + } + + public void setOriginPos(Vec3 pos) { + setPos(pos); + } + + private double width() { + return WIDTH * PehkuiScaleTypes.HITBOX_WIDTH.getScaleData(this).getScale(); + } + + private double height() { + return HEIGHT * PehkuiScaleTypes.HITBOX_HEIGHT.getScaleData(this).getScale(); + } + + public IPQuaternion getTransformQuat() { + if (transformQuat != null) { + return transformQuat; + } + final IPQuaternion myRotation = IPQuaternion.fromQuaternionf(getRotation().get()); + final IPQuaternion otherRotation = IPQuaternion.fromQuaternionf(getOtherRotation().orElseThrow(NOT_INIT)); + return transformQuat = otherRotation + .hamiltonProduct(FLIP_AXIS_W) + .hamiltonProduct(myRotation.getConjugated()); + } + + public void addListener(PortalListeningEntity source) { + if (level() instanceof ServerLevel level) { + this.listeningEntities.add(new EntityReference<>(level, source)); + } + } + + public void forEachListeningEntity(Consumer consumer) { + Iterator> itr = listeningEntities.iterator(); + while (itr.hasNext()) { + EntityReference entity = itr.next(); + if (entity.isLoaded()) { + consumer.accept(entity.get()); + } else { + itr.remove(); + } + } + } + + public void notifyListenersOfCreation() { + if (level() instanceof ServerLevel level) { + for (PortalListeningEntity entity : level.getEntities(PortalListeningEntity.TYPE_TEST, Entity::isAlive)) { + entity.onPortalCreate(this); + } + } + } + + private static Axis axisOf(Vec3 axisVec) { + for (Axis axis : Axis.VALUES) { + if (axisVec.get(axis) != 0) + return axis; + } + throw new IllegalArgumentException("axisVec is ZERO"); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/Portal1CompanionCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/Portal1CompanionCubeEntity.java index 1de2be05..990a8735 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/Portal1CompanionCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/Portal1CompanionCubeEntity.java @@ -5,8 +5,8 @@ import net.minecraft.world.level.Level; public class Portal1CompanionCubeEntity extends CorePhysicsEntity { - public Portal1CompanionCubeEntity(EntityType type, Level world) { - super(type, world); - } + public Portal1CompanionCubeEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/Portal1StorageCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/Portal1StorageCubeEntity.java index a1c3a1e1..6eeb620f 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/Portal1StorageCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/Portal1StorageCubeEntity.java @@ -5,8 +5,8 @@ import net.minecraft.world.level.Level; public class Portal1StorageCubeEntity extends CorePhysicsEntity { - public Portal1StorageCubeEntity(EntityType type, Level world) { - super(type, world); - } + public Portal1StorageCubeEntity(EntityType type, Level world) { + super(type, world); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedEntities.java b/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedEntities.java index 2204b6bc..a3aa8cf0 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedEntities.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedEntities.java @@ -18,214 +18,214 @@ public class PortalCubedEntities { - public static final EntityType PORTAL = QuiltEntityTypeBuilder.create(MobCategory.MISC, Portal::new) - .setDimensions(EntityDimensions.scalable(1F, 1F)) - .build(); - - public static final EntityType STORAGE_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, StorageCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - - public static final EntityType COMPANION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CompanionCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - public static final EntityType REDIRECTION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, RedirectionCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - public static final EntityType SCHRODINGER_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, SchrodingerCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - public static final EntityType RADIO = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, RadioEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.3125F)) - .build(); - - public static final EntityType OLD_AP_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, OldApCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - - public static final EntityType PORTAL_1_COMPANION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, Portal1CompanionCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - - public static final EntityType PORTAL_1_STORAGE_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, Portal1StorageCubeEntity::new) - .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) - .build(); - - public static final EntityType BEANS = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, BeansEntity::new) - .setDimensions(EntityDimensions.scalable(0.25F, 0.375F)) - .build(); - - public static final EntityType MUG = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, MugEntity::new) - .setDimensions(EntityDimensions.scalable(0.1875F, 0.25F)) - .build(); - - public static final EntityType JUG = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, JugEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.5F)) - .build(); - - public static final EntityType COMPUTER = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, ComputerEntity::new) - .setDimensions(EntityDimensions.scalable(0.5F, 0.1875F)) - .build(); - - public static final EntityType CHAIR = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, ChairEntity::new) - .setDimensions(EntityDimensions.scalable(0.4375F, 0.46875F)) - .build(); - - public static final EntityType LIL_PINEAPPLE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, LilPineappleEntity::new) - .setDimensions(EntityDimensions.scalable(0.5625F, 0.5F)) - .build(); - - public static final EntityType HOOPY = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, HoopyEntity::new) - .setDimensions(EntityDimensions.scalable(1.625F, 0.0625F)) - .build(); - - public static final EntityType CORE_FRAME = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CoreFrameEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - - public static final EntityType ANGER_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, AngerCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - public static final EntityType MORALITY_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, MoralityCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - public static final EntityType CAKE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CakeCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - public static final EntityType CURIOSITY_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CuriosityCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - - public static final EntityType SPACE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, SpaceCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - public static final EntityType FACT_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, FactCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - public static final EntityType ADVENTURE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, AdventureCoreEntity::new) - .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) - .build(); - - public static final EntityType PROPULSION_GEL_BLOB = createGelBlob( - PortalCubedBlocks.PROPULSION_GEL, id("textures/block/propulsion_gel.png") - ); - public static final EntityType REPULSION_GEL_BLOB = createGelBlob( - PortalCubedBlocks.REPULSION_GEL, id("textures/block/repulsion_gel.png") - ); - public static final EntityType ADHESION_GEL_BLOB = createGelBlob( - PortalCubedBlocks.ADHESION_GEL, id("textures/block/adhesion_gel.png") - ); - public static final EntityType CONVERSION_GEL_BLOB = createGelBlob( - PortalCubedBlocks.CONVERSION_GEL, id("textures/block/gel.png") - ); - public static final EntityType REFLECTION_GEL_BLOB = createGelBlob( - PortalCubedBlocks.REFLECTION_GEL, id("textures/block/reflection_gel.png") - ); - - public static final EntityType ROCKET = QuiltEntityTypeBuilder.create(MobCategory.MISC, RocketEntity::new) - .setDimensions(EntityDimensions.scalable(0.1875f, 0.1875f)) - .build(); - - public static final EntityType ENERGY_PELLET = QuiltEntityTypeBuilder.create(MobCategory.MISC, EnergyPellet::new) - .setDimensions(EntityDimensions.scalable(0.25f, 0.25f)) - .build(); - - public static final EntityType TURRET = QuiltEntityTypeBuilder.create(MobCategory.MISC, TurretEntity::new) - .setDimensions(EntityDimensions.scalable(0.75f * TurretEntity.MODEL_SCALE, 1.5f * TurretEntity.MODEL_SCALE)) - .build(); - - public static final EntityType EXCURSION_FUNNEL = QuiltEntityTypeBuilder.create(MobCategory.MISC, ExcursionFunnelEntity::new) - .setDimensions(EntityDimensions.scalable(1, 1)) - .maxChunkTrackingRange(64) - .disableSummon() - .build(); - - public static final TagKey> P1_ENTITY = TagKey.create(Registries.ENTITY_TYPE, id("p1_entity")); - public static final TagKey> PORTAL_BLACKLIST = TagKey.create(Registries.ENTITY_TYPE, id("portal_blacklist")); - - public static void registerEntities() { - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal"), PORTAL); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("storage_cube"), STORAGE_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("companion_cube"), COMPANION_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("radio"), RADIO); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("redirection_cube"), REDIRECTION_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("schrodinger_cube"), SCHRODINGER_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("old_ap_cube"), OLD_AP_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal_1_companion_cube"), PORTAL_1_COMPANION_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal_1_storage_cube"), PORTAL_1_STORAGE_CUBE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("beans"), BEANS); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("mug"), MUG); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("jug"), JUG); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("computer"), COMPUTER); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("chair"), CHAIR); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("lil_pineapple"), LIL_PINEAPPLE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("hoopy"), HOOPY); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("core_frame"), CORE_FRAME); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("anger_core"), ANGER_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("intelligence_core"), CAKE_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("curiosity_core"), CURIOSITY_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("morality_core"), MORALITY_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("space_core"), SPACE_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("adventure_core"), ADVENTURE_CORE); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("fact_core"), FACT_CORE); - - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("propulsion_gel_blob"), PROPULSION_GEL_BLOB); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("repulsion_gel_blob"), REPULSION_GEL_BLOB); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("adhesion_gel_blob"), ADHESION_GEL_BLOB); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("conversion_gel_blob"), CONVERSION_GEL_BLOB); - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("reflection_gel_blob"), REFLECTION_GEL_BLOB); - - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("rocket"), ROCKET); - - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("energy_pellet"), ENERGY_PELLET); - - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("turret"), TURRET); - - Registry.register(BuiltInRegistries.ENTITY_TYPE, id("excursion_funnel"), EXCURSION_FUNNEL); - - DefaultAttributes.SUPPLIERS.put(STORAGE_CUBE, StorageCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(COMPANION_CUBE, CompanionCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(RADIO, RadioEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(REDIRECTION_CUBE, RedirectionCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(SCHRODINGER_CUBE, SchrodingerCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(OLD_AP_CUBE, OldApCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(PORTAL_1_COMPANION_CUBE, Portal1CompanionCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(PORTAL_1_STORAGE_CUBE, Portal1StorageCubeEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(BEANS, BeansEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(MUG, MugEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(JUG, JugEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(COMPUTER, ComputerEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(CHAIR, ChairEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(LIL_PINEAPPLE, LilPineappleEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(HOOPY, HoopyEntity.createMobAttributes().build()); - - DefaultAttributes.SUPPLIERS.put(CORE_FRAME, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(ANGER_CORE, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(CAKE_CORE, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(CURIOSITY_CORE, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(MORALITY_CORE, HoopyEntity.createMobAttributes().build()); - - DefaultAttributes.SUPPLIERS.put(SPACE_CORE, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(ADVENTURE_CORE, HoopyEntity.createMobAttributes().build()); - DefaultAttributes.SUPPLIERS.put(FACT_CORE, HoopyEntity.createMobAttributes().build()); - - DefaultAttributes.SUPPLIERS.put(TURRET, TurretEntity.createMobAttributes().build()); - } - - public static EntityType createGelBlob(BaseGel gel, ResourceLocation texture) { - return QuiltEntityTypeBuilder.create() - .entityFactory((type, world) -> new GelBlobEntity(type, world) { - @Override - public ResourceLocation getTexture() { - return texture; - } - - @Override - public BaseGel getGel() { - return gel; - } - }) - .setDimensions(EntityDimensions.scalable(1, 1)) - .build(); - } + public static final EntityType PORTAL = QuiltEntityTypeBuilder.create(MobCategory.MISC, Portal::new) + .setDimensions(EntityDimensions.scalable(1F, 1F)) + .build(); + + public static final EntityType STORAGE_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, StorageCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + + public static final EntityType COMPANION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CompanionCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + public static final EntityType REDIRECTION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, RedirectionCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + public static final EntityType SCHRODINGER_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, SchrodingerCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + public static final EntityType RADIO = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, RadioEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.3125F)) + .build(); + + public static final EntityType OLD_AP_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, OldApCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + + public static final EntityType PORTAL_1_COMPANION_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, Portal1CompanionCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + + public static final EntityType PORTAL_1_STORAGE_CUBE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, Portal1StorageCubeEntity::new) + .setDimensions(EntityDimensions.scalable(0.625F, 0.625F)) + .build(); + + public static final EntityType BEANS = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, BeansEntity::new) + .setDimensions(EntityDimensions.scalable(0.25F, 0.375F)) + .build(); + + public static final EntityType MUG = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, MugEntity::new) + .setDimensions(EntityDimensions.scalable(0.1875F, 0.25F)) + .build(); + + public static final EntityType JUG = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, JugEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.5F)) + .build(); + + public static final EntityType COMPUTER = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, ComputerEntity::new) + .setDimensions(EntityDimensions.scalable(0.5F, 0.1875F)) + .build(); + + public static final EntityType CHAIR = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, ChairEntity::new) + .setDimensions(EntityDimensions.scalable(0.4375F, 0.46875F)) + .build(); + + public static final EntityType LIL_PINEAPPLE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, LilPineappleEntity::new) + .setDimensions(EntityDimensions.scalable(0.5625F, 0.5F)) + .build(); + + public static final EntityType HOOPY = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, HoopyEntity::new) + .setDimensions(EntityDimensions.scalable(1.625F, 0.0625F)) + .build(); + + public static final EntityType CORE_FRAME = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CoreFrameEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + + public static final EntityType ANGER_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, AngerCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + public static final EntityType MORALITY_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, MoralityCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + public static final EntityType CAKE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CakeCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + public static final EntityType CURIOSITY_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, CuriosityCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + + public static final EntityType SPACE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, SpaceCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + public static final EntityType FACT_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, FactCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + public static final EntityType ADVENTURE_CORE = QuiltEntityTypeBuilder.create(MobCategory.CREATURE, AdventureCoreEntity::new) + .setDimensions(EntityDimensions.scalable(0.375F, 0.375F)) + .build(); + + public static final EntityType PROPULSION_GEL_BLOB = createGelBlob( + PortalCubedBlocks.PROPULSION_GEL, id("textures/block/propulsion_gel.png") + ); + public static final EntityType REPULSION_GEL_BLOB = createGelBlob( + PortalCubedBlocks.REPULSION_GEL, id("textures/block/repulsion_gel.png") + ); + public static final EntityType ADHESION_GEL_BLOB = createGelBlob( + PortalCubedBlocks.ADHESION_GEL, id("textures/block/adhesion_gel.png") + ); + public static final EntityType CONVERSION_GEL_BLOB = createGelBlob( + PortalCubedBlocks.CONVERSION_GEL, id("textures/block/gel.png") + ); + public static final EntityType REFLECTION_GEL_BLOB = createGelBlob( + PortalCubedBlocks.REFLECTION_GEL, id("textures/block/reflection_gel.png") + ); + + public static final EntityType ROCKET = QuiltEntityTypeBuilder.create(MobCategory.MISC, RocketEntity::new) + .setDimensions(EntityDimensions.scalable(0.1875f, 0.1875f)) + .build(); + + public static final EntityType ENERGY_PELLET = QuiltEntityTypeBuilder.create(MobCategory.MISC, EnergyPellet::new) + .setDimensions(EntityDimensions.scalable(0.25f, 0.25f)) + .build(); + + public static final EntityType TURRET = QuiltEntityTypeBuilder.create(MobCategory.MISC, TurretEntity::new) + .setDimensions(EntityDimensions.scalable(0.75f * TurretEntity.MODEL_SCALE, 1.5f * TurretEntity.MODEL_SCALE)) + .build(); + + public static final EntityType EXCURSION_FUNNEL = QuiltEntityTypeBuilder.create(MobCategory.MISC, ExcursionFunnelEntity::new) + .setDimensions(EntityDimensions.scalable(1, 1)) + .maxChunkTrackingRange(64) + .disableSummon() + .build(); + + public static final TagKey> P1_ENTITY = TagKey.create(Registries.ENTITY_TYPE, id("p1_entity")); + public static final TagKey> PORTAL_BLACKLIST = TagKey.create(Registries.ENTITY_TYPE, id("portal_blacklist")); + + public static void registerEntities() { + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal"), PORTAL); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("storage_cube"), STORAGE_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("companion_cube"), COMPANION_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("radio"), RADIO); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("redirection_cube"), REDIRECTION_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("schrodinger_cube"), SCHRODINGER_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("old_ap_cube"), OLD_AP_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal_1_companion_cube"), PORTAL_1_COMPANION_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("portal_1_storage_cube"), PORTAL_1_STORAGE_CUBE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("beans"), BEANS); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("mug"), MUG); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("jug"), JUG); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("computer"), COMPUTER); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("chair"), CHAIR); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("lil_pineapple"), LIL_PINEAPPLE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("hoopy"), HOOPY); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("core_frame"), CORE_FRAME); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("anger_core"), ANGER_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("intelligence_core"), CAKE_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("curiosity_core"), CURIOSITY_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("morality_core"), MORALITY_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("space_core"), SPACE_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("adventure_core"), ADVENTURE_CORE); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("fact_core"), FACT_CORE); + + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("propulsion_gel_blob"), PROPULSION_GEL_BLOB); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("repulsion_gel_blob"), REPULSION_GEL_BLOB); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("adhesion_gel_blob"), ADHESION_GEL_BLOB); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("conversion_gel_blob"), CONVERSION_GEL_BLOB); + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("reflection_gel_blob"), REFLECTION_GEL_BLOB); + + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("rocket"), ROCKET); + + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("energy_pellet"), ENERGY_PELLET); + + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("turret"), TURRET); + + Registry.register(BuiltInRegistries.ENTITY_TYPE, id("excursion_funnel"), EXCURSION_FUNNEL); + + DefaultAttributes.SUPPLIERS.put(STORAGE_CUBE, StorageCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(COMPANION_CUBE, CompanionCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(RADIO, RadioEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(REDIRECTION_CUBE, RedirectionCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(SCHRODINGER_CUBE, SchrodingerCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(OLD_AP_CUBE, OldApCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(PORTAL_1_COMPANION_CUBE, Portal1CompanionCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(PORTAL_1_STORAGE_CUBE, Portal1StorageCubeEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(BEANS, BeansEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(MUG, MugEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(JUG, JugEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(COMPUTER, ComputerEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(CHAIR, ChairEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(LIL_PINEAPPLE, LilPineappleEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(HOOPY, HoopyEntity.createMobAttributes().build()); + + DefaultAttributes.SUPPLIERS.put(CORE_FRAME, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(ANGER_CORE, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(CAKE_CORE, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(CURIOSITY_CORE, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(MORALITY_CORE, HoopyEntity.createMobAttributes().build()); + + DefaultAttributes.SUPPLIERS.put(SPACE_CORE, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(ADVENTURE_CORE, HoopyEntity.createMobAttributes().build()); + DefaultAttributes.SUPPLIERS.put(FACT_CORE, HoopyEntity.createMobAttributes().build()); + + DefaultAttributes.SUPPLIERS.put(TURRET, TurretEntity.createMobAttributes().build()); + } + + public static EntityType createGelBlob(BaseGel gel, ResourceLocation texture) { + return QuiltEntityTypeBuilder.create() + .entityFactory((type, world) -> new GelBlobEntity(type, world) { + @Override + public ResourceLocation getTexture() { + return texture; + } + + @Override + public BaseGel getGel() { + return gel; + } + }) + .setDimensions(EntityDimensions.scalable(1, 1)) + .build(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedTrackedDataHandlers.java b/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedTrackedDataHandlers.java index cbf22d45..2ebbb6cd 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedTrackedDataHandlers.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/PortalCubedTrackedDataHandlers.java @@ -14,31 +14,31 @@ import static net.minecraft.network.syncher.EntityDataSerializers.QUATERNION; public class PortalCubedTrackedDataHandlers { - public static final EntityDataSerializer LERPED_QUAT = EntityDataSerializer.simple( - (buf, quat) -> quat.toNetwork(buf), - LerpedQuaternion::fromNetwork - ); - - public static final EntityDataSerializer VEC3D = EntityDataSerializer.simple( - (buf, value) -> { - buf.writeDouble(value.x); - buf.writeDouble(value.y); - buf.writeDouble(value.z); - }, - buf -> new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()) - ); - - public static final EntityDataSerializer> OPTIONAL_VEC3D = EntityDataSerializer.optional(VEC3D::write, VEC3D::read); - public static final EntityDataSerializer> OPTIONAL_QUAT = EntityDataSerializer.optional(QUATERNION::write, QUATERNION::read); - - public static final EntityDataSerializer IDENTIFIER = EntityDataSerializer.simple(FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::readResourceLocation); - - public static void register() { - QuiltTrackedDataHandlerRegistry.register(id("lerped_quaternion"), LERPED_QUAT); - QuiltTrackedDataHandlerRegistry.register(id("optional_quat"), OPTIONAL_QUAT); - QuiltTrackedDataHandlerRegistry.register(id("vec3d"), VEC3D); - QuiltTrackedDataHandlerRegistry.register(id("optional_vec3d"), OPTIONAL_VEC3D); - QuiltTrackedDataHandlerRegistry.register(id("identifier"), IDENTIFIER); - } + public static final EntityDataSerializer LERPED_QUAT = EntityDataSerializer.simple( + (buf, quat) -> quat.toNetwork(buf), + LerpedQuaternion::fromNetwork + ); + + public static final EntityDataSerializer VEC3D = EntityDataSerializer.simple( + (buf, value) -> { + buf.writeDouble(value.x); + buf.writeDouble(value.y); + buf.writeDouble(value.z); + }, + buf -> new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()) + ); + + public static final EntityDataSerializer> OPTIONAL_VEC3D = EntityDataSerializer.optional(VEC3D::write, VEC3D::read); + public static final EntityDataSerializer> OPTIONAL_QUAT = EntityDataSerializer.optional(QUATERNION::write, QUATERNION::read); + + public static final EntityDataSerializer IDENTIFIER = EntityDataSerializer.simple(FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::readResourceLocation); + + public static void register() { + QuiltTrackedDataHandlerRegistry.register(id("lerped_quaternion"), LERPED_QUAT); + QuiltTrackedDataHandlerRegistry.register(id("optional_quat"), OPTIONAL_QUAT); + QuiltTrackedDataHandlerRegistry.register(id("vec3d"), VEC3D); + QuiltTrackedDataHandlerRegistry.register(id("optional_vec3d"), OPTIONAL_VEC3D); + QuiltTrackedDataHandlerRegistry.register(id("identifier"), IDENTIFIER); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/PortalListeningEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/PortalListeningEntity.java index e0675d30..137a4c9f 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/PortalListeningEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/PortalListeningEntity.java @@ -9,24 +9,24 @@ * An entity that listens for placement and removal of portals near it. */ public abstract class PortalListeningEntity extends Entity { - public static final EntityTypeTest TYPE_TEST = EntityTypeTest.forClass(PortalListeningEntity.class); + public static final EntityTypeTest TYPE_TEST = EntityTypeTest.forClass(PortalListeningEntity.class); - public PortalListeningEntity(EntityType variant, Level world) { - super(variant, world); - } + public PortalListeningEntity(EntityType variant, Level world) { + super(variant, world); + } - /** - * Called when a portal is created anywhere in the world. Add listeners here. - */ - public void onPortalCreate(Portal portal) { - } + /** + * Called when a portal is created anywhere in the world. Add listeners here. + */ + public void onPortalCreate(Portal portal) { + } - // these methods are only fired for listeners registered to the portal. - // don't add listeners to the portal here, that should be queued for later. + // these methods are only fired for listeners registered to the portal. + // don't add listeners to the portal here, that should be queued for later. - public void onPortalRemove(Portal portal) { - } + public void onPortalRemove(Portal portal) { + } - public void onLinkedPortalCreate(Portal portal, Portal linked) { - } + public void onLinkedPortalCreate(Portal portal, Portal linked) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/RadioEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/RadioEntity.java index 1f244d9b..20e9eaa7 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/RadioEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/RadioEntity.java @@ -30,146 +30,146 @@ import java.util.UUID; public class RadioEntity extends CorePhysicsEntity { - private static final AABB BASE_BOX = createFootBox(0.4375, 0.3125, 0.1875); - - private static final EntityDataAccessor MUTED = SynchedEntityData.defineId(RadioEntity.class, EntityDataSerializers.BOOLEAN); - private static final EntityDataAccessor ALLOW_MUTE = SynchedEntityData.defineId(RadioEntity.class, EntityDataSerializers.BOOLEAN); - - @Nullable - private SoundEvent song = PortalCubedSounds.RADIO_MUSIC_EVENT; - @Nullable - private SoundEvent lastSong = song; - - public RadioEntity(EntityType type, Level world) { - super(type, world); - } - - @Override - protected void defineSynchedData() { - super.defineSynchedData(); - entityData.define(MUTED, false); - entityData.define(ALLOW_MUTE, true); - } - - @NotNull - @Override - protected AABB makeBoundingBox() { - return GeneralUtil.rotate(BASE_BOX, yHeadRot, Direction.Axis.Y).move(position()); - } - - public boolean isMuted() { - return entityData.get(MUTED); - } - - public void setMuted(boolean notPlaying) { - entityData.set(MUTED, notPlaying); - } - - public boolean isAllowMute() { - return entityData.get(ALLOW_MUTE); - } - - public void setAllowMute(boolean allowMute) { - entityData.set(ALLOW_MUTE, allowMute); - } - - @ClientOnly - private void performPlay() { - if (song == null) return; - Minecraft.getInstance().getSoundManager().play(new RadioSoundInstance(song)); - } - - @Override - public void recreateFromPacket(ClientboundAddEntityPacket packet) { - super.recreateFromPacket(packet); - performPlay(); - } - - @Override - public void setHolderUUID(Optional uuid) { - super.setHolderUUID(uuid); - if (uuid.isPresent() && isAllowMute()) { - setMuted(!isMuted()); - } - } - - @Override - public void tick() { - super.tick(); - if (getCustomName() != null) { - final String name = getCustomName().getString(); - if (name.equalsIgnoreCase("exile") || name.equalsIgnoreCase("vilify") || name.equalsIgnoreCase("exile vilify")) { - song = PortalCubedSounds.EXILE_MUSIC_EVENT; - } else if (name.equalsIgnoreCase("silent")) { - song = null; - } else { - song = PortalCubedSounds.RADIO_MUSIC_EVENT; - } - } else { - song = PortalCubedSounds.RADIO_MUSIC_EVENT; - } - if (song != lastSong) { - lastSong = song; - if (level().isClientSide) { - performPlay(); - } - } - } - - @Override - protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { - if (!level().isClientSide && player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { - setAllowMute(!isAllowMute()); - if (isAllowMute()) { - player.displayClientMessage(Component.translatable("portalcubed.radio.allow_mute"), true); - } else { - setMuted(false); - player.displayClientMessage(Component.translatable("portalcubed.radio.disallow_mute"), true); - } - return InteractionResult.SUCCESS; - } - return InteractionResult.PASS; - } - - @Override - public void addAdditionalSaveData(CompoundTag nbt) { - super.addAdditionalSaveData(nbt); - nbt.putBoolean("Muted", isMuted()); - nbt.putBoolean("AllowMute", isAllowMute()); - } - - @Override - public void readAdditionalSaveData(CompoundTag nbt) { - super.readAdditionalSaveData(nbt); - setMuted(nbt.getBoolean("Muted")); - setAllowMute(nbt.getBoolean("AllowMute")); - } - - @ClientOnly - private class RadioSoundInstance extends AbstractTickableSoundInstance { - private final SoundEvent song; - - RadioSoundInstance(SoundEvent song) { - super(song, SoundSource.RECORDS, SoundInstance.createUnseededRandom()); - this.song = song; - volume = 1f; - pitch = 1f; - looping = true; - x = RadioEntity.this.getX(); - y = RadioEntity.this.getY(); - z = RadioEntity.this.getZ(); - } - - @Override - public void tick() { - if (isRemoved() || song != RadioEntity.this.song) { - stop(); - return; - } - volume = isMuted() ? 0f : 1f; - x = RadioEntity.this.getX(); - y = RadioEntity.this.getY(); - z = RadioEntity.this.getZ(); - } - } + private static final AABB BASE_BOX = createFootBox(0.4375, 0.3125, 0.1875); + + private static final EntityDataAccessor MUTED = SynchedEntityData.defineId(RadioEntity.class, EntityDataSerializers.BOOLEAN); + private static final EntityDataAccessor ALLOW_MUTE = SynchedEntityData.defineId(RadioEntity.class, EntityDataSerializers.BOOLEAN); + + @Nullable + private SoundEvent song = PortalCubedSounds.RADIO_MUSIC_EVENT; + @Nullable + private SoundEvent lastSong = song; + + public RadioEntity(EntityType type, Level world) { + super(type, world); + } + + @Override + protected void defineSynchedData() { + super.defineSynchedData(); + entityData.define(MUTED, false); + entityData.define(ALLOW_MUTE, true); + } + + @NotNull + @Override + protected AABB makeBoundingBox() { + return GeneralUtil.rotate(BASE_BOX, yHeadRot, Direction.Axis.Y).move(position()); + } + + public boolean isMuted() { + return entityData.get(MUTED); + } + + public void setMuted(boolean notPlaying) { + entityData.set(MUTED, notPlaying); + } + + public boolean isAllowMute() { + return entityData.get(ALLOW_MUTE); + } + + public void setAllowMute(boolean allowMute) { + entityData.set(ALLOW_MUTE, allowMute); + } + + @ClientOnly + private void performPlay() { + if (song == null) return; + Minecraft.getInstance().getSoundManager().play(new RadioSoundInstance(song)); + } + + @Override + public void recreateFromPacket(ClientboundAddEntityPacket packet) { + super.recreateFromPacket(packet); + performPlay(); + } + + @Override + public void setHolderUUID(Optional uuid) { + super.setHolderUUID(uuid); + if (uuid.isPresent() && isAllowMute()) { + setMuted(!isMuted()); + } + } + + @Override + public void tick() { + super.tick(); + if (getCustomName() != null) { + final String name = getCustomName().getString(); + if (name.equalsIgnoreCase("exile") || name.equalsIgnoreCase("vilify") || name.equalsIgnoreCase("exile vilify")) { + song = PortalCubedSounds.EXILE_MUSIC_EVENT; + } else if (name.equalsIgnoreCase("silent")) { + song = null; + } else { + song = PortalCubedSounds.RADIO_MUSIC_EVENT; + } + } else { + song = PortalCubedSounds.RADIO_MUSIC_EVENT; + } + if (song != lastSong) { + lastSong = song; + if (level().isClientSide) { + performPlay(); + } + } + } + + @Override + protected InteractionResult physicsEntityInteraction(Player player, InteractionHand hand) { + if (!level().isClientSide && player.getItemInHand(hand).is(PortalCubedItems.WRENCHES)) { + setAllowMute(!isAllowMute()); + if (isAllowMute()) { + player.displayClientMessage(Component.translatable("portalcubed.radio.allow_mute"), true); + } else { + setMuted(false); + player.displayClientMessage(Component.translatable("portalcubed.radio.disallow_mute"), true); + } + return InteractionResult.SUCCESS; + } + return InteractionResult.PASS; + } + + @Override + public void addAdditionalSaveData(CompoundTag nbt) { + super.addAdditionalSaveData(nbt); + nbt.putBoolean("Muted", isMuted()); + nbt.putBoolean("AllowMute", isAllowMute()); + } + + @Override + public void readAdditionalSaveData(CompoundTag nbt) { + super.readAdditionalSaveData(nbt); + setMuted(nbt.getBoolean("Muted")); + setAllowMute(nbt.getBoolean("AllowMute")); + } + + @ClientOnly + private class RadioSoundInstance extends AbstractTickableSoundInstance { + private final SoundEvent song; + + RadioSoundInstance(SoundEvent song) { + super(song, SoundSource.RECORDS, SoundInstance.createUnseededRandom()); + this.song = song; + volume = 1f; + pitch = 1f; + looping = true; + x = RadioEntity.this.getX(); + y = RadioEntity.this.getY(); + z = RadioEntity.this.getZ(); + } + + @Override + public void tick() { + if (isRemoved() || song != RadioEntity.this.song) { + stop(); + return; + } + volume = isMuted() ? 0f : 1f; + x = RadioEntity.this.getX(); + y = RadioEntity.this.getY(); + z = RadioEntity.this.getZ(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/RedirectionCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/RedirectionCubeEntity.java index e6938844..e6fa7cde 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/RedirectionCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/RedirectionCubeEntity.java @@ -5,28 +5,28 @@ import net.minecraft.world.level.Level; public class RedirectionCubeEntity extends StorageCubeEntity { - private int activeTicks; + private int activeTicks; - public RedirectionCubeEntity(EntityType type, Level world) { - super(type, world); - } + public RedirectionCubeEntity(EntityType type, Level world) { + super(type, world); + } - public RedirectionCubeEntity getConnection() { - return this; - } + public RedirectionCubeEntity getConnection() { + return this; + } - @Override - public void tick() { - super.tick(); - activeTicks = Math.max(activeTicks - 1, 0); - } + @Override + public void tick() { + super.tick(); + activeTicks = Math.max(activeTicks - 1, 0); + } - public void markActive() { - activeTicks = 2; - } + public void markActive() { + activeTicks = 2; + } - public boolean isActive() { - return activeTicks > 0; - } + public boolean isActive() { + return activeTicks > 0; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/RocketEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/RocketEntity.java index 7c2bc54c..034cf5bd 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/RocketEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/RocketEntity.java @@ -30,161 +30,161 @@ import org.quiltmc.qsl.networking.api.ServerPlayNetworking; public class RocketEntity extends Entity implements Fizzleable { - private static final double SPEED = 1; - - private float fizzleProgress = 0f; - private boolean fizzling = false; - - public RocketEntity(EntityType type, Level world) { - super(type, world); - } - - @Override - protected void defineSynchedData() { - } - - @Override - protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { - } - - @Override - protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { - } - - @Override - public void tick() { - super.tick(); - if (fizzling) { - if (level().isClientSide) { - fizzleProgress += Minecraft.getInstance().getFrameTime(); - } else { - fizzleProgress += 0.05f; - if (fizzleProgress >= 1f) { - remove(RemovalReason.KILLED); - } - } - } else { - setDeltaMovement(Vec3.directionFromRotation(getXRot(), getYRot()).scale(SPEED)); - } - move(MoverType.SELF, getDeltaMovement()); - if (!level().isClientSide && tickCount > 0 && tickCount % 13 == 0) { - level().playSound(null, this, PortalCubedSounds.ROCKET_FLY_EVENT, SoundSource.HOSTILE, 1, 1); - } - if (fizzling) return; - if (level().isClientSide) { - level().addParticle( - ParticleTypes.SMOKE, - getX() + random.nextGaussian() * 0.1, - getY() + random.nextGaussian() * 0.1, - getZ() + random.nextGaussian() * 0.1, - 0, 0, 0 - ); - level().addParticle( - ParticleTypes.SMALL_FLAME, - getX() + random.nextGaussian() * 0.1, - getY() + random.nextGaussian() * 0.1, - getZ() + random.nextGaussian() * 0.1, - 0, 0, 0 - ); - return; - } - final HitResult hit = ProjectileUtil.getHitResultOnMoveVector(this, this::canHit); - if (hit.getType() == HitResult.Type.ENTITY) { - explode((LivingEntity)((EntityHitResult)hit).getEntity()); - } else { - final LivingEntity hit2 = level().getNearestEntity( - LivingEntity.class, - TargetingConditions.forNonCombat().selector(this::canHit), - null, getX(), getY(), getZ(), - getBoundingBox() - ); - if (hit2 != null) { - explode(hit2); - } else if (horizontalCollision || verticalCollision) { - explode(null); - } - } - if (tickCount > 200) { - explode(null); - } - } - - @Override - protected void onInsideBlock(BlockState state) { - if ( - state.getFluidState().is(PortalCubedFluids.TOXIC_GOO.still) || - state.getFluidState().is(PortalCubedFluids.TOXIC_GOO.flowing) - ) { - level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ROCKET_GOO_EVENT, SoundSource.HOSTILE, 1, 1); - kill(); - } - } - - protected boolean canHit(Entity entity) { - return entity instanceof LivingEntity && !entity.isSpectator() && entity.isAlive() && entity.isPickable(); - } - - public void explode(@Nullable LivingEntity entity) { - if (entity != null) { - entity.hurt( - damageSources().source(DamageTypes.FIREWORKS, this), - PortalCubedConfig.rocketDamage - ); - } - level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ROCKET_EXPLODE_EVENT, SoundSource.HOSTILE, 1, 1); - if (level() instanceof ServerLevel serverLevel) { - serverLevel.sendParticles( - ParticleTypes.EXPLOSION, - getX(), getY(), getZ(), - 8, - 0.5, 0.5, 0.5, - 0 - ); - } - kill(); - } - - @Override - public void startFizzlingProgress() { - fizzling = true; - setDeltaMovement(getDeltaMovement().scale(0.2)); - } - - @Override - public void fizzle() { - if (fizzling) return; - startFizzlingProgress(); - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeVarInt(getId()); - final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.FIZZLE_PACKET, buf); - PlayerLookup.tracking(this).forEach(player -> player.connection.send(packet)); - } - - @Override - public float getFizzleProgress() { - return fizzleProgress; - } - - @Override - public boolean fizzling() { - return fizzling; - } - - @Override - public boolean fizzlesInGoo() { - return false; - } - - @Override - public FizzleType getFizzleType() { - return FizzleType.OBJECT; - } - - @Override - public void remove(@NotNull RemovalReason reason) { - if (reason == RemovalReason.UNLOADED_TO_CHUNK) { - reason = RemovalReason.DISCARDED; - } - super.remove(reason); - } + private static final double SPEED = 1; + + private float fizzleProgress = 0f; + private boolean fizzling = false; + + public RocketEntity(EntityType type, Level world) { + super(type, world); + } + + @Override + protected void defineSynchedData() { + } + + @Override + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + @Override + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + @Override + public void tick() { + super.tick(); + if (fizzling) { + if (level().isClientSide) { + fizzleProgress += Minecraft.getInstance().getFrameTime(); + } else { + fizzleProgress += 0.05f; + if (fizzleProgress >= 1f) { + remove(RemovalReason.KILLED); + } + } + } else { + setDeltaMovement(Vec3.directionFromRotation(getXRot(), getYRot()).scale(SPEED)); + } + move(MoverType.SELF, getDeltaMovement()); + if (!level().isClientSide && tickCount > 0 && tickCount % 13 == 0) { + level().playSound(null, this, PortalCubedSounds.ROCKET_FLY_EVENT, SoundSource.HOSTILE, 1, 1); + } + if (fizzling) return; + if (level().isClientSide) { + level().addParticle( + ParticleTypes.SMOKE, + getX() + random.nextGaussian() * 0.1, + getY() + random.nextGaussian() * 0.1, + getZ() + random.nextGaussian() * 0.1, + 0, 0, 0 + ); + level().addParticle( + ParticleTypes.SMALL_FLAME, + getX() + random.nextGaussian() * 0.1, + getY() + random.nextGaussian() * 0.1, + getZ() + random.nextGaussian() * 0.1, + 0, 0, 0 + ); + return; + } + final HitResult hit = ProjectileUtil.getHitResultOnMoveVector(this, this::canHit); + if (hit.getType() == HitResult.Type.ENTITY) { + explode((LivingEntity)((EntityHitResult)hit).getEntity()); + } else { + final LivingEntity hit2 = level().getNearestEntity( + LivingEntity.class, + TargetingConditions.forNonCombat().selector(this::canHit), + null, getX(), getY(), getZ(), + getBoundingBox() + ); + if (hit2 != null) { + explode(hit2); + } else if (horizontalCollision || verticalCollision) { + explode(null); + } + } + if (tickCount > 200) { + explode(null); + } + } + + @Override + protected void onInsideBlock(BlockState state) { + if ( + state.getFluidState().is(PortalCubedFluids.TOXIC_GOO.still) || + state.getFluidState().is(PortalCubedFluids.TOXIC_GOO.flowing) + ) { + level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ROCKET_GOO_EVENT, SoundSource.HOSTILE, 1, 1); + kill(); + } + } + + protected boolean canHit(Entity entity) { + return entity instanceof LivingEntity && !entity.isSpectator() && entity.isAlive() && entity.isPickable(); + } + + public void explode(@Nullable LivingEntity entity) { + if (entity != null) { + entity.hurt( + damageSources().source(DamageTypes.FIREWORKS, this), + PortalCubedConfig.rocketDamage + ); + } + level().playSound(null, getX(), getY(), getZ(), PortalCubedSounds.ROCKET_EXPLODE_EVENT, SoundSource.HOSTILE, 1, 1); + if (level() instanceof ServerLevel serverLevel) { + serverLevel.sendParticles( + ParticleTypes.EXPLOSION, + getX(), getY(), getZ(), + 8, + 0.5, 0.5, 0.5, + 0 + ); + } + kill(); + } + + @Override + public void startFizzlingProgress() { + fizzling = true; + setDeltaMovement(getDeltaMovement().scale(0.2)); + } + + @Override + public void fizzle() { + if (fizzling) return; + startFizzlingProgress(); + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeVarInt(getId()); + final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.FIZZLE_PACKET, buf); + PlayerLookup.tracking(this).forEach(player -> player.connection.send(packet)); + } + + @Override + public float getFizzleProgress() { + return fizzleProgress; + } + + @Override + public boolean fizzling() { + return fizzling; + } + + @Override + public boolean fizzlesInGoo() { + return false; + } + + @Override + public FizzleType getFizzleType() { + return FizzleType.OBJECT; + } + + @Override + public void remove(@NotNull RemovalReason reason) { + if (reason == RemovalReason.UNLOADED_TO_CHUNK) { + reason = RemovalReason.DISCARDED; + } + super.remove(reason); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/SchrodingerCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/SchrodingerCubeEntity.java index a19e6194..4ca9da48 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/SchrodingerCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/SchrodingerCubeEntity.java @@ -10,22 +10,22 @@ public class SchrodingerCubeEntity extends RedirectionCubeEntity { - public SchrodingerCubeEntity(EntityType type, Level world) { - super(type, world); - } + public SchrodingerCubeEntity(EntityType type, Level world) { + super(type, world); + } - @Override - public SchrodingerCubeEntity getConnection() { - return Objects.requireNonNullElse(level().getNearestEntity( - SchrodingerCubeEntity.class, - TargetingConditions.forNonCombat() - .selector(e -> Objects.equals(e.getCustomName(), getCustomName())) - .ignoreLineOfSight() - .ignoreInvisibilityTesting(), - this, - getX(), getY(), getZ(), - AABB.ofSize(position(), 256, 256, 256) - ), this); - } + @Override + public SchrodingerCubeEntity getConnection() { + return Objects.requireNonNullElse(level().getNearestEntity( + SchrodingerCubeEntity.class, + TargetingConditions.forNonCombat() + .selector(e -> Objects.equals(e.getCustomName(), getCustomName())) + .ignoreLineOfSight() + .ignoreInvisibilityTesting(), + this, + getX(), getY(), getZ(), + AABB.ofSize(position(), 256, 256, 256) + ), this); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/SpaceCoreEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/SpaceCoreEntity.java index ed344660..f810236f 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/SpaceCoreEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/SpaceCoreEntity.java @@ -7,21 +7,21 @@ public class SpaceCoreEntity extends CorePhysicsEntity { - public SpaceCoreEntity(EntityType type, Level world) { - super(type, world); - } + public SpaceCoreEntity(EntityType type, Level world) { + super(type, world); + } - private int t = 0; + private int t = 0; - @Override - public void tick() { - if (!this.level().isClientSide) { - if (t == 0) { - level().playSound(null, this, PortalCubedSounds.SPACE_CORE_EVENT, this.getSoundSource(), 1f, 1f); - t = 2765; - } - t--; - } - super.tick(); - } + @Override + public void tick() { + if (!this.level().isClientSide) { + if (t == 0) { + level().playSound(null, this, PortalCubedSounds.SPACE_CORE_EVENT, this.getSoundSource(), 1f, 1f); + t = 2765; + } + t--; + } + super.tick(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/StorageCubeEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/StorageCubeEntity.java index ee1240ea..d12ed288 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/StorageCubeEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/StorageCubeEntity.java @@ -9,32 +9,32 @@ public class StorageCubeEntity extends CorePhysicsEntity { - public StorageCubeEntity(EntityType type, Level world) { - super(type, world); - } - - @Override - public LivingEntity.@NotNull Fallsounds getFallSounds() { - return new LivingEntity.Fallsounds(PortalCubedSounds.CUBE_LOW_HIT_EVENT, PortalCubedSounds.CUBE_HIGH_HIT_EVENT); - } - - private int buttonTimer = 0; - - public void setButtonTimer(int time) { - buttonTimer = time; - } - - @Override - public void tick() { - super.tick(); - if (!level().isClientSide) { - if (buttonTimer <= 0) { - setOnButton(false); - } else { - setOnButton(true); - buttonTimer -= 1; - } - } - } + public StorageCubeEntity(EntityType type, Level world) { + super(type, world); + } + + @Override + public LivingEntity.@NotNull Fallsounds getFallSounds() { + return new LivingEntity.Fallsounds(PortalCubedSounds.CUBE_LOW_HIT_EVENT, PortalCubedSounds.CUBE_HIGH_HIT_EVENT); + } + + private int buttonTimer = 0; + + public void setButtonTimer(int time) { + buttonTimer = time; + } + + @Override + public void tick() { + super.tick(); + if (!level().isClientSide) { + if (buttonTimer <= 0) { + setOnButton(false); + } else { + setOnButton(true); + buttonTimer -= 1; + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/TurretEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/TurretEntity.java index 2c124b36..a46a4ed0 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/TurretEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/TurretEntity.java @@ -28,115 +28,115 @@ import org.jetbrains.annotations.NotNull; public class TurretEntity extends CorePhysicsEntity { - private static final EntityDataAccessor PITCH_SPEED = SynchedEntityData.defineId(TurretEntity.class, EntityDataSerializers.FLOAT); + private static final EntityDataAccessor PITCH_SPEED = SynchedEntityData.defineId(TurretEntity.class, EntityDataSerializers.FLOAT); - public static final float MODEL_SCALE = Mth.lerp(0.875f, 1 / 1.62f, 1f); - private static final AABB BASE_BOX = createFootBox(0.5f * MODEL_SCALE, 1.5f * MODEL_SCALE, MODEL_SCALE); - private static final float FALL_SPEED = 0.3f; + public static final float MODEL_SCALE = Mth.lerp(0.875f, 1 / 1.62f, 1f); + private static final AABB BASE_BOX = createFootBox(0.5f * MODEL_SCALE, 1.5f * MODEL_SCALE, MODEL_SCALE); + private static final float FALL_SPEED = 0.3f; - public TurretEntity(EntityType type, Level world) { - super(type, world); - } + public TurretEntity(EntityType type, Level world) { + super(type, world); + } - @Override - protected void defineSynchedData() { - super.defineSynchedData(); - getEntityData().define(PITCH_SPEED, 0f); - } + @Override + protected void defineSynchedData() { + super.defineSynchedData(); + getEntityData().define(PITCH_SPEED, 0f); + } - @NotNull - @Override - protected AABB makeBoundingBox() { - AABB fallenBox = GeneralUtil.rotate(BASE_BOX, getXRot(), Direction.Axis.X); - if (fallenBox != BASE_BOX) { - fallenBox = fallenBox.move(0, MODEL_SCALE / 2, 0); - } - final float yaw = Mth.wrapDegrees(yHeadRot); - AABB result = GeneralUtil.rotate(fallenBox, yaw, Direction.Axis.Y); - if (yaw >= 45 || yaw < -135) { - result = new AABB(-result.minX, result.minY, -result.minZ, -result.maxX, result.maxY, -result.maxZ); - } - return result.move(position()); - } + @NotNull + @Override + protected AABB makeBoundingBox() { + AABB fallenBox = GeneralUtil.rotate(BASE_BOX, getXRot(), Direction.Axis.X); + if (fallenBox != BASE_BOX) { + fallenBox = fallenBox.move(0, MODEL_SCALE / 2, 0); + } + final float yaw = Mth.wrapDegrees(yHeadRot); + AABB result = GeneralUtil.rotate(fallenBox, yaw, Direction.Axis.Y); + if (yaw >= 45 || yaw < -135) { + result = new AABB(-result.minX, result.minY, -result.minZ, -result.maxX, result.maxY, -result.maxZ); + } + return result.move(position()); + } - @Override - public void tick() { - float pitchSpeed = getPitchSpeed(); - float pitch = getXRot(); - if (!RayonIntegration.INSTANCE.isPresent()) { - if (pitchSpeed > 90) { - pitchSpeed = 90; - } else if (pitchSpeed < -90) { - pitchSpeed = -90; - } - } - super.tick(); - if (!RayonIntegration.INSTANCE.isPresent()) { - setXRot(Mth.wrapDegrees(pitch + pitchSpeed)); - if (getXRot() > 90) { - setXRot(90); - pitchSpeed = 0; - } else if (getXRot() < -90) { - setXRot(-90); - pitchSpeed = 0; - } - pitchSpeed += FALL_SPEED * Mth.sign(pitchSpeed) * Math.sqrt(Math.abs(pitch)); - setPitchSpeed(pitchSpeed); - } - } + @Override + public void tick() { + float pitchSpeed = getPitchSpeed(); + float pitch = getXRot(); + if (!RayonIntegration.INSTANCE.isPresent()) { + if (pitchSpeed > 90) { + pitchSpeed = 90; + } else if (pitchSpeed < -90) { + pitchSpeed = -90; + } + } + super.tick(); + if (!RayonIntegration.INSTANCE.isPresent()) { + setXRot(Mth.wrapDegrees(pitch + pitchSpeed)); + if (getXRot() > 90) { + setXRot(90); + pitchSpeed = 0; + } else if (getXRot() < -90) { + setXRot(-90); + pitchSpeed = 0; + } + pitchSpeed += FALL_SPEED * Mth.sign(pitchSpeed) * Math.sqrt(Math.abs(pitch)); + setPitchSpeed(pitchSpeed); + } + } - @Override - public void addAdditionalSaveData(CompoundTag nbt) { - super.addAdditionalSaveData(nbt); - nbt.putFloat("PitchSpeed", getPitchSpeed()); - } + @Override + public void addAdditionalSaveData(CompoundTag nbt) { + super.addAdditionalSaveData(nbt); + nbt.putFloat("PitchSpeed", getPitchSpeed()); + } - @Override - public void readAdditionalSaveData(CompoundTag nbt) { - super.readAdditionalSaveData(nbt); - setPitchSpeed(nbt.getFloat("PitchSpeed")); - } + @Override + public void readAdditionalSaveData(CompoundTag nbt) { + super.readAdditionalSaveData(nbt); + setPitchSpeed(nbt.getFloat("PitchSpeed")); + } - public float getPitchSpeed() { - return getEntityData().get(PITCH_SPEED); - } + public float getPitchSpeed() { + return getEntityData().get(PITCH_SPEED); + } - public void setPitchSpeed(float pitchSpeed) { - getEntityData().set(PITCH_SPEED, pitchSpeed); - } + public void setPitchSpeed(float pitchSpeed) { + getEntityData().set(PITCH_SPEED, pitchSpeed); + } - public static void makeBulletHole(ServerLevel level, BlockHitResult hit, SoundSource soundCategory) { - final BlockState block = level.getBlockState(hit.getBlockPos()); - final Vec3 pos = hit.getLocation().add(Vec3.atLowerCornerOf(hit.getDirection().getNormal()).scale(0.01)); - final SoundEvent soundEffect; - final ResourceLocation particleTexture; - boolean multiplyTexture = true; - if (block.is(PortalCubedBlocks.BULLET_HOLE_CONCRETE)) { - soundEffect = PortalCubedSounds.BULLET_CONCRETE_EVENT; - particleTexture = DecalParticleOption.BULLET_HOLE_CONCRETE; - level.sendParticles( - new BlockParticleOption(ParticleTypes.BLOCK, block), - pos.x, pos.y, pos.z, 3, 0.1, 0.1, 0.1, 1 - ); - } else if (block.is(PortalCubedBlocks.BULLET_HOLE_GLASS)) { - soundEffect = PortalCubedSounds.BULLET_GLASS_EVENT; - particleTexture = DecalParticleOption.BULLET_HOLE_GLASS; - multiplyTexture = false; - } else if (block.is(PortalCubedBlocks.BULLET_HOLE_METAL)) { - soundEffect = PortalCubedSounds.BULLET_METAL_EVENT; - particleTexture = DecalParticleOption.BULLET_HOLE_METAL; - } else { - soundEffect = null; - particleTexture = null; - } - if (soundEffect != null) { - level.playSound(null, pos.x, pos.y, pos.z, soundEffect, soundCategory, 0.3f, 1f); - } - if (particleTexture != null) { - level.sendParticles( - new DecalParticleOption(particleTexture, hit.getDirection(), multiplyTexture), - pos.x, pos.y, pos.z, 0, 0, 0, 0, 0 - ); - } - } + public static void makeBulletHole(ServerLevel level, BlockHitResult hit, SoundSource soundCategory) { + final BlockState block = level.getBlockState(hit.getBlockPos()); + final Vec3 pos = hit.getLocation().add(Vec3.atLowerCornerOf(hit.getDirection().getNormal()).scale(0.01)); + final SoundEvent soundEffect; + final ResourceLocation particleTexture; + boolean multiplyTexture = true; + if (block.is(PortalCubedBlocks.BULLET_HOLE_CONCRETE)) { + soundEffect = PortalCubedSounds.BULLET_CONCRETE_EVENT; + particleTexture = DecalParticleOption.BULLET_HOLE_CONCRETE; + level.sendParticles( + new BlockParticleOption(ParticleTypes.BLOCK, block), + pos.x, pos.y, pos.z, 3, 0.1, 0.1, 0.1, 1 + ); + } else if (block.is(PortalCubedBlocks.BULLET_HOLE_GLASS)) { + soundEffect = PortalCubedSounds.BULLET_GLASS_EVENT; + particleTexture = DecalParticleOption.BULLET_HOLE_GLASS; + multiplyTexture = false; + } else if (block.is(PortalCubedBlocks.BULLET_HOLE_METAL)) { + soundEffect = PortalCubedSounds.BULLET_METAL_EVENT; + particleTexture = DecalParticleOption.BULLET_HOLE_METAL; + } else { + soundEffect = null; + particleTexture = null; + } + if (soundEffect != null) { + level.playSound(null, pos.x, pos.y, pos.z, soundEffect, soundCategory, 0.3f, 1f); + } + if (particleTexture != null) { + level.sendParticles( + new DecalParticleOption(particleTexture, hit.getDirection(), multiplyTexture), + pos.x, pos.y, pos.z, 0, 0, 0, 0, 0 + ); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/beams/EmittedEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/beams/EmittedEntity.java index 8dfa957f..d38d2f03 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/beams/EmittedEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/beams/EmittedEntity.java @@ -33,261 +33,261 @@ import java.util.function.Consumer; public abstract class EmittedEntity extends PortalListeningEntity implements QuiltExtendedSpawnDataEntity { - public static final int DEFAULT_MAX_LENGTH = 100; - public static final EntityDataAccessor FACING = SynchedEntityData.defineId(EmittedEntity.class, EntityDataSerializers.DIRECTION); - public static final EntityDataAccessor LENGTH = SynchedEntityData.defineId(EmittedEntity.class, EntityDataSerializers.FLOAT); - - private Direction facing = Direction.NORTH; - private float length = 1; - private float targetLength = 1; - private Vec3 center = Vec3.ZERO; - private AABB listeningArea = new AABB(BlockPos.ZERO); - private int reEmitTimer; - private AABB cachedBounds; - - // UUID of next in line. resolving this will always work, since the first entity - // is the only one that can be unloaded (others are chunk loaded by portals) - @Nullable private UUID next; - // portal this is being emitted from - @Nullable private UUID sourcePortal; - - public Consumer modelUpdater = entity -> {}; - - public EmittedEntity(EntityType entityType, Level level) { - super(entityType, level); - setBoundingBox(makeBoundingBox()); - } - - public void setFacing(Direction facing) { - entityData.set(FACING, facing); - } - - public Direction getFacing() { - // null on initial load during super call - return facing == null ? Direction.NORTH : facing; - } - - public void setLength(float length) { - entityData.set(LENGTH, length); - } - - public float getLength() { - return length; - } - - public Vec3 getCenter() { - return center; - } - - public boolean listensTo(BlockPos pos) { - return isAlive() && listeningArea.contains(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); - } - - protected abstract AABB makeBaseBoundingBox(); - - protected abstract EmittedEntity createNext(); - - @Override - @NotNull - protected AABB makeBoundingBox() { - // updating bounds is expensive, minecraft calls this method constantly because of setPos - if (cachedBounds == null) - cachedBounds = actuallyMakeBoundingBox(); - return cachedBounds; - } - - protected AABB actuallyMakeBoundingBox() { - AABB base = makeBaseBoundingBox(); - Vec3 pos = position(); - Vec3 offset = pos.relative(getFacing(), getLength()).subtract(pos); // relative offset along facing by length - this.center = base.getCenter(); - AABB bounds = base.expandTowards(offset); - - Direction facing = getFacing(); - Vec3 facingNormal = Vec3.ZERO.with(facing.getAxis(), facing.getAxisDirection().getStep()); - - if (listeningArea != null) - stopListeningToArea(listeningArea); - this.listeningArea = bounds.expandTowards(facingNormal); - startListeningToArea(listeningArea); - - return bounds; - } - - public void reEmit() { - reEmit(targetLength); - } - - public void reEmit(float maxLength) { - removeNextEntity(); // remove existing emitted entities - this.targetLength = maxLength; - Level level = level(); - Direction facing = getFacing(); - Axis facingAxis = facing.getAxis(); - AABB bounds = makeBaseBoundingBox(); - // relative offset along facing by maxLength - Vec3 offset = Vec3.ZERO.with(facingAxis, maxLength * facing.getAxisDirection().getStep()); - // how far the hitbox can actually move - Vec3 actualOffset = Entity.collideBoundingBox(null, offset, bounds, level, List.of()); - double size = facingAxis.choose(bounds.getXsize(), bounds.getYsize(), bounds.getZsize()); - float length = (float) (actualOffset.length() + size / 2); - setLength(length); - - if (maxLength - length > 0.1) { // don't bother with going through portals if too short - AABB portalArea = bounds.move(actualOffset).expandTowards(actualOffset.normalize().scale(0.25)); - List portals = level.getEntities(PortalCubedEntities.PORTAL, portalArea, this::isPortalAligned); - if (!portals.isEmpty()) { - if (portals.size() != 1) { // prefer nearest portal when multiple present - portals.sort(Comparator.comparingDouble(this::distanceToSqr)); - } - - Portal portal = portals.get(0); - portal.addListener(this); - - Portal linked = portal.findLinkedPortal(); - if (linked != null) { // if already active, emit through - Vector2d planeCoords = portal.getLocalPlaneCoords(position()); - Vec3 otherSidePos = linked.getPointInPlane(-planeCoords.x, planeCoords.y); // -x: mirror - Direction otherFacing = linked.getFacingDirection(); - - EmittedEntity nextEntity = createNext(); - nextEntity.setPos(otherSidePos); - nextEntity.setFacing(otherFacing); - nextEntity.reEmit(maxLength - length); - nextEntity.sourcePortal = linked.getUUID(); - linked.addListener(nextEntity); - level.addFreshEntity(nextEntity); - - this.next = nextEntity.getUUID(); - } - } - } - } - - @Override - public void tick() { - super.tick(); - reEmitTimer--; - if (reEmitTimer == 0) { - reEmit(); - } - } - - @Override - public void remove(RemovalReason reason) { - super.remove(reason); - stopListeningToArea(listeningArea); - if (reason.shouldDestroy()) - removeNextEntity(); - } - - private void removeNextEntity() { - if (next != null && level() instanceof ServerLevel level) { - Entity next = level.getEntity(this.next); - if (next != null) { - next.remove(RemovalReason.DISCARDED); - } - this.next = null; - } - } - - @Override - protected void defineSynchedData() { - entityData.define(FACING, Direction.NORTH); - entityData.define(LENGTH, 1f); - } - - @Override - public void onSyncedDataUpdated(EntityDataAccessor key) { - super.onSyncedDataUpdated(key); - if (FACING.equals(key)) { - this.facing = entityData.get(FACING); - updateBounds(); - } else if (LENGTH.equals(key)) { - this.length = entityData.get(LENGTH); - updateBounds(); - } - } - - @Override - public void writeAdditionalSpawnData(FriendlyByteBuf buf) { - buf.writeEnum(facing); - buf.writeFloat(length); - } - - @Override - public void readAdditionalSpawnData(FriendlyByteBuf buf) { - this.facing = buf.readEnum(Direction.class); - this.length = buf.readFloat(); - } - - @Override - protected void addAdditionalSaveData(CompoundTag tag) { - tag.putString("facing", facing.getSerializedName()); - tag.putFloat("length", length); - tag.putFloat("targetLength", targetLength); - if (sourcePortal != null) - tag.putUUID("sourcePortal", sourcePortal); - } - - @Override - protected void readAdditionalSaveData(CompoundTag tag) { - setFacing(NbtHelper.readEnum(tag, "facing", Direction.NORTH)); - if (tag.contains("length", Tag.TAG_FLOAT)) - setLength(tag.getFloat("length")); - if (tag.contains("targetLength", Tag.TAG_FLOAT)) - this.targetLength = tag.getFloat("targetLength"); - if (tag.contains("sourcePortal", Tag.TAG_INT_ARRAY)) - this.sourcePortal = tag.getUUID("sourcePortal"); - } - - private void updateBounds() { - this.cachedBounds = actuallyMakeBoundingBox(); - setBoundingBox(makeBoundingBox()); - modelUpdater.accept(this); - } - - public boolean isPortalAligned(Portal portal) { - return portal.isAlive() && getFacing().getOpposite() == portal.getFacingDirection(); - } - - @Override - public void onPortalCreate(Portal portal) { - if (getFacing().getOpposite() == portal.getFacingDirection()) - reEmitTimer = 3; // direction aligns, try to emit through (next tick, portal not ready) - } - - @Override - public void onPortalRemove(Portal portal) { - if (Objects.equals(sourcePortal, portal.getUUID())) { - discard(); // source removed - } else { - removeNextEntity(); // going into the portal, remove on other side - } - } - - @Override - public void onLinkedPortalCreate(Portal portal, Portal linked) { - reEmitTimer = 3; - } - - public void startListeningToArea(AABB area) { - if (level() instanceof ServerLevel level) { - forEachSection(area, section -> ((LevelExt) level).pc$addBlockChangeListener(section.asLong(), this)); - } - } - - public void stopListeningToArea(AABB area) { - if (level() instanceof ServerLevel level) { - forEachSection(area, section -> ((LevelExt) level).pc$removeBlockChangeListener(section.asLong(), this)); - } - } - - public static void forEachSection(AABB bounds, Consumer consumer) { - BlockPos minBlock = BlockPos.containing(bounds.minX, bounds.minY, bounds.minZ); - BlockPos maxBlock = BlockPos.containing(bounds.maxX, bounds.maxY, bounds.maxZ); - SectionPos min = SectionPos.of(minBlock); - SectionPos max = SectionPos.of(maxBlock); - SectionPos.betweenClosedStream(min.x(), min.y(), min.z(), max.x(), max.y(), max.z()).forEach(consumer); - } + public static final int DEFAULT_MAX_LENGTH = 100; + public static final EntityDataAccessor FACING = SynchedEntityData.defineId(EmittedEntity.class, EntityDataSerializers.DIRECTION); + public static final EntityDataAccessor LENGTH = SynchedEntityData.defineId(EmittedEntity.class, EntityDataSerializers.FLOAT); + + private Direction facing = Direction.NORTH; + private float length = 1; + private float targetLength = 1; + private Vec3 center = Vec3.ZERO; + private AABB listeningArea = new AABB(BlockPos.ZERO); + private int reEmitTimer; + private AABB cachedBounds; + + // UUID of next in line. resolving this will always work, since the first entity + // is the only one that can be unloaded (others are chunk loaded by portals) + @Nullable private UUID next; + // portal this is being emitted from + @Nullable private UUID sourcePortal; + + public Consumer modelUpdater = entity -> {}; + + public EmittedEntity(EntityType entityType, Level level) { + super(entityType, level); + setBoundingBox(makeBoundingBox()); + } + + public void setFacing(Direction facing) { + entityData.set(FACING, facing); + } + + public Direction getFacing() { + // null on initial load during super call + return facing == null ? Direction.NORTH : facing; + } + + public void setLength(float length) { + entityData.set(LENGTH, length); + } + + public float getLength() { + return length; + } + + public Vec3 getCenter() { + return center; + } + + public boolean listensTo(BlockPos pos) { + return isAlive() && listeningArea.contains(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); + } + + protected abstract AABB makeBaseBoundingBox(); + + protected abstract EmittedEntity createNext(); + + @Override + @NotNull + protected AABB makeBoundingBox() { + // updating bounds is expensive, minecraft calls this method constantly because of setPos + if (cachedBounds == null) + cachedBounds = actuallyMakeBoundingBox(); + return cachedBounds; + } + + protected AABB actuallyMakeBoundingBox() { + AABB base = makeBaseBoundingBox(); + Vec3 pos = position(); + Vec3 offset = pos.relative(getFacing(), getLength()).subtract(pos); // relative offset along facing by length + this.center = base.getCenter(); + AABB bounds = base.expandTowards(offset); + + Direction facing = getFacing(); + Vec3 facingNormal = Vec3.ZERO.with(facing.getAxis(), facing.getAxisDirection().getStep()); + + if (listeningArea != null) + stopListeningToArea(listeningArea); + this.listeningArea = bounds.expandTowards(facingNormal); + startListeningToArea(listeningArea); + + return bounds; + } + + public void reEmit() { + reEmit(targetLength); + } + + public void reEmit(float maxLength) { + removeNextEntity(); // remove existing emitted entities + this.targetLength = maxLength; + Level level = level(); + Direction facing = getFacing(); + Axis facingAxis = facing.getAxis(); + AABB bounds = makeBaseBoundingBox(); + // relative offset along facing by maxLength + Vec3 offset = Vec3.ZERO.with(facingAxis, maxLength * facing.getAxisDirection().getStep()); + // how far the hitbox can actually move + Vec3 actualOffset = Entity.collideBoundingBox(null, offset, bounds, level, List.of()); + double size = facingAxis.choose(bounds.getXsize(), bounds.getYsize(), bounds.getZsize()); + float length = (float) (actualOffset.length() + size / 2); + setLength(length); + + if (maxLength - length > 0.1) { // don't bother with going through portals if too short + AABB portalArea = bounds.move(actualOffset).expandTowards(actualOffset.normalize().scale(0.25)); + List portals = level.getEntities(PortalCubedEntities.PORTAL, portalArea, this::isPortalAligned); + if (!portals.isEmpty()) { + if (portals.size() != 1) { // prefer nearest portal when multiple present + portals.sort(Comparator.comparingDouble(this::distanceToSqr)); + } + + Portal portal = portals.get(0); + portal.addListener(this); + + Portal linked = portal.findLinkedPortal(); + if (linked != null) { // if already active, emit through + Vector2d planeCoords = portal.getLocalPlaneCoords(position()); + Vec3 otherSidePos = linked.getPointInPlane(-planeCoords.x, planeCoords.y); // -x: mirror + Direction otherFacing = linked.getFacingDirection(); + + EmittedEntity nextEntity = createNext(); + nextEntity.setPos(otherSidePos); + nextEntity.setFacing(otherFacing); + nextEntity.reEmit(maxLength - length); + nextEntity.sourcePortal = linked.getUUID(); + linked.addListener(nextEntity); + level.addFreshEntity(nextEntity); + + this.next = nextEntity.getUUID(); + } + } + } + } + + @Override + public void tick() { + super.tick(); + reEmitTimer--; + if (reEmitTimer == 0) { + reEmit(); + } + } + + @Override + public void remove(RemovalReason reason) { + super.remove(reason); + stopListeningToArea(listeningArea); + if (reason.shouldDestroy()) + removeNextEntity(); + } + + private void removeNextEntity() { + if (next != null && level() instanceof ServerLevel level) { + Entity next = level.getEntity(this.next); + if (next != null) { + next.remove(RemovalReason.DISCARDED); + } + this.next = null; + } + } + + @Override + protected void defineSynchedData() { + entityData.define(FACING, Direction.NORTH); + entityData.define(LENGTH, 1f); + } + + @Override + public void onSyncedDataUpdated(EntityDataAccessor key) { + super.onSyncedDataUpdated(key); + if (FACING.equals(key)) { + this.facing = entityData.get(FACING); + updateBounds(); + } else if (LENGTH.equals(key)) { + this.length = entityData.get(LENGTH); + updateBounds(); + } + } + + @Override + public void writeAdditionalSpawnData(FriendlyByteBuf buf) { + buf.writeEnum(facing); + buf.writeFloat(length); + } + + @Override + public void readAdditionalSpawnData(FriendlyByteBuf buf) { + this.facing = buf.readEnum(Direction.class); + this.length = buf.readFloat(); + } + + @Override + protected void addAdditionalSaveData(CompoundTag tag) { + tag.putString("facing", facing.getSerializedName()); + tag.putFloat("length", length); + tag.putFloat("targetLength", targetLength); + if (sourcePortal != null) + tag.putUUID("sourcePortal", sourcePortal); + } + + @Override + protected void readAdditionalSaveData(CompoundTag tag) { + setFacing(NbtHelper.readEnum(tag, "facing", Direction.NORTH)); + if (tag.contains("length", Tag.TAG_FLOAT)) + setLength(tag.getFloat("length")); + if (tag.contains("targetLength", Tag.TAG_FLOAT)) + this.targetLength = tag.getFloat("targetLength"); + if (tag.contains("sourcePortal", Tag.TAG_INT_ARRAY)) + this.sourcePortal = tag.getUUID("sourcePortal"); + } + + private void updateBounds() { + this.cachedBounds = actuallyMakeBoundingBox(); + setBoundingBox(makeBoundingBox()); + modelUpdater.accept(this); + } + + public boolean isPortalAligned(Portal portal) { + return portal.isAlive() && getFacing().getOpposite() == portal.getFacingDirection(); + } + + @Override + public void onPortalCreate(Portal portal) { + if (getFacing().getOpposite() == portal.getFacingDirection()) + reEmitTimer = 3; // direction aligns, try to emit through (next tick, portal not ready) + } + + @Override + public void onPortalRemove(Portal portal) { + if (Objects.equals(sourcePortal, portal.getUUID())) { + discard(); // source removed + } else { + removeNextEntity(); // going into the portal, remove on other side + } + } + + @Override + public void onLinkedPortalCreate(Portal portal, Portal linked) { + reEmitTimer = 3; + } + + public void startListeningToArea(AABB area) { + if (level() instanceof ServerLevel level) { + forEachSection(area, section -> ((LevelExt) level).pc$addBlockChangeListener(section.asLong(), this)); + } + } + + public void stopListeningToArea(AABB area) { + if (level() instanceof ServerLevel level) { + forEachSection(area, section -> ((LevelExt) level).pc$removeBlockChangeListener(section.asLong(), this)); + } + } + + public static void forEachSection(AABB bounds, Consumer consumer) { + BlockPos minBlock = BlockPos.containing(bounds.minX, bounds.minY, bounds.minZ); + BlockPos maxBlock = BlockPos.containing(bounds.maxX, bounds.maxY, bounds.maxZ); + SectionPos min = SectionPos.of(minBlock); + SectionPos max = SectionPos.of(maxBlock); + SectionPos.betweenClosedStream(min.x(), min.y(), min.z(), max.x(), max.y(), max.z()).forEach(consumer); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/entity/beams/ExcursionFunnelEntity.java b/src/main/java/com/fusionflux/portalcubed/entity/beams/ExcursionFunnelEntity.java index 484e9059..a3623a12 100644 --- a/src/main/java/com/fusionflux/portalcubed/entity/beams/ExcursionFunnelEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/entity/beams/ExcursionFunnelEntity.java @@ -27,156 +27,156 @@ import java.util.List; public class ExcursionFunnelEntity extends EmittedEntity implements LateRenderedEntity { - public static final EntityDataAccessor REVERSED = SynchedEntityData.defineId(ExcursionFunnelEntity.class, EntityDataSerializers.BOOLEAN); - - public static final float SIZE = (30 / 32f) * 2; - - private boolean reversed; - - @ClientOnly - public ExcursionFunnelModel model; - - public ExcursionFunnelEntity(EntityType entityType, Level level) { - super(entityType, level); - } - - public static ExcursionFunnelEntity spawnAndEmit(Level level, Vec3 pos, Direction facing, boolean reversed, float length) { - ExcursionFunnelEntity entity = new ExcursionFunnelEntity(PortalCubedEntities.EXCURSION_FUNNEL, level); - entity.setPos(pos); - entity.setFacing(facing); - entity.setReversed(reversed); - - entity.reEmit(length); - level.addFreshEntity(entity); - return entity; - } - - @Override - protected EmittedEntity createNext() { - ExcursionFunnelEntity entity = new ExcursionFunnelEntity(PortalCubedEntities.EXCURSION_FUNNEL, level()); - entity.setReversed(isReversed()); - return entity; - } - - public boolean isReversed() { - return reversed; - } - - public void setReversed(boolean reversed) { - entityData.set(REVERSED, reversed); - } - - @Override - protected void defineSynchedData() { - super.defineSynchedData(); - entityData.define(REVERSED, false); - } - - @Override - public void onSyncedDataUpdated(EntityDataAccessor key) { - super.onSyncedDataUpdated(key); - if (key.equals(REVERSED)) { - this.reversed = entityData.get(REVERSED); - } - } - - @Override - public void writeAdditionalSpawnData(FriendlyByteBuf buf) { - super.writeAdditionalSpawnData(buf); - buf.writeBoolean(reversed); - } - - @Override - public void readAdditionalSpawnData(FriendlyByteBuf buf) { - super.readAdditionalSpawnData(buf); - this.reversed = buf.readBoolean(); - } - - @Override - protected void addAdditionalSaveData(CompoundTag tag) { - super.addAdditionalSaveData(tag); - tag.putBoolean("reversed", reversed); - } - - @Override - protected void readAdditionalSaveData(CompoundTag tag) { - super.readAdditionalSaveData(tag); - setReversed(tag.getBoolean("reversed")); - } - - @Override - protected AABB makeBaseBoundingBox() { - Direction facing = this.getFacing(); - Axis axis = facing.getAxis(); - Vec3 pos = position(); - return AABB.ofSize(pos, axis.choose(0, SIZE, SIZE), axis.choose(SIZE, 0, SIZE), axis.choose(SIZE, SIZE, 0)); - } - - @Override - public void tick() { - super.tick(); - Level level = level(); - List colliding = level.getEntitiesOfClass(LivingEntity.class, getBoundingBox(), Entity::isAlive); - if (!colliding.isEmpty()) { - Direction facing = getFacing(); - Direction motion = isReversed() ? facing.getOpposite() : facing; - Vec3 center = getCenter(); - for (LivingEntity entity : colliding) { - applyEffects(entity, center, motion); - } - } - } - - public static void applyEffects(Entity entity, Vec3 tubeCenter, Direction motionDirection) { - if (entity instanceof Player player && player.getAbilities().flying) - return; - Vec3 entityCenter = entity.getBoundingBox().getCenter(); - Vec3 motion = Vec3.atLowerCornerOf(motionDirection.getNormal()).scale(0.125); - - RayonIntegration.INSTANCE.setNoGravity(entity, true); - entity.resetFallDistance(); - - EntityExt entityEx = (EntityExt) entity; - if (!entityEx.isInFunnel()) { - entityEx.setInFunnel(true); - entity.setDeltaMovement(0, 0, 0); - if (entity instanceof Player player && player.isLocalPlayer()) - playEnterSound(); - } - entityEx.setFunnelTimer(2); - - Vec3 velocity = entity.getDeltaMovement(); - // check for inputs - if (entity instanceof HasMovementInputAccessor inputProvider && inputProvider.hasMovementInputPublic()) { - if (motion.x == 0) - motion = motion.add(velocity.x, 0, 0); - if (motion.y == 0) - motion = motion.add(0, velocity.y, 0); - if (motion.z == 0) - motion = motion.add(0, 0, velocity.z); - } - - // move entity towards center - double dx = entityCenter.x - tubeCenter.x + velocity.x; - double dy = entityCenter.y - tubeCenter.y + velocity.y; - double dz = entityCenter.z - tubeCenter.z + velocity.z; - - if (motion.x == 0) - motion = motion.add(-Math.copySign(Math.sqrt(Math.abs(dx)), dx) / 20, 0, 0); - if (motion.y == 0) - motion = motion.add(0, -Math.copySign(Math.sqrt(Math.abs(dy)), dy) / 20, 0); - if (motion.z == 0) - motion = motion.add(0, 0, -Math.copySign(Math.sqrt(Math.abs(dz)), dz) / 20); - - entity.setDeltaMovement(motion); - - if (entity.isShiftKeyDown() && motion.lengthSqr() < 0.15 * 0.15 && !entity.isFree(motion.x, motion.y, motion.z)) { - entityEx.setCFG(); - } - } - - @ClientOnly - private static void playEnterSound() { - Minecraft.getInstance().getSoundManager().play(new ExcursionFunnelEnterSoundInstance()); - } + public static final EntityDataAccessor REVERSED = SynchedEntityData.defineId(ExcursionFunnelEntity.class, EntityDataSerializers.BOOLEAN); + + public static final float SIZE = (30 / 32f) * 2; + + private boolean reversed; + + @ClientOnly + public ExcursionFunnelModel model; + + public ExcursionFunnelEntity(EntityType entityType, Level level) { + super(entityType, level); + } + + public static ExcursionFunnelEntity spawnAndEmit(Level level, Vec3 pos, Direction facing, boolean reversed, float length) { + ExcursionFunnelEntity entity = new ExcursionFunnelEntity(PortalCubedEntities.EXCURSION_FUNNEL, level); + entity.setPos(pos); + entity.setFacing(facing); + entity.setReversed(reversed); + + entity.reEmit(length); + level.addFreshEntity(entity); + return entity; + } + + @Override + protected EmittedEntity createNext() { + ExcursionFunnelEntity entity = new ExcursionFunnelEntity(PortalCubedEntities.EXCURSION_FUNNEL, level()); + entity.setReversed(isReversed()); + return entity; + } + + public boolean isReversed() { + return reversed; + } + + public void setReversed(boolean reversed) { + entityData.set(REVERSED, reversed); + } + + @Override + protected void defineSynchedData() { + super.defineSynchedData(); + entityData.define(REVERSED, false); + } + + @Override + public void onSyncedDataUpdated(EntityDataAccessor key) { + super.onSyncedDataUpdated(key); + if (key.equals(REVERSED)) { + this.reversed = entityData.get(REVERSED); + } + } + + @Override + public void writeAdditionalSpawnData(FriendlyByteBuf buf) { + super.writeAdditionalSpawnData(buf); + buf.writeBoolean(reversed); + } + + @Override + public void readAdditionalSpawnData(FriendlyByteBuf buf) { + super.readAdditionalSpawnData(buf); + this.reversed = buf.readBoolean(); + } + + @Override + protected void addAdditionalSaveData(CompoundTag tag) { + super.addAdditionalSaveData(tag); + tag.putBoolean("reversed", reversed); + } + + @Override + protected void readAdditionalSaveData(CompoundTag tag) { + super.readAdditionalSaveData(tag); + setReversed(tag.getBoolean("reversed")); + } + + @Override + protected AABB makeBaseBoundingBox() { + Direction facing = this.getFacing(); + Axis axis = facing.getAxis(); + Vec3 pos = position(); + return AABB.ofSize(pos, axis.choose(0, SIZE, SIZE), axis.choose(SIZE, 0, SIZE), axis.choose(SIZE, SIZE, 0)); + } + + @Override + public void tick() { + super.tick(); + Level level = level(); + List colliding = level.getEntitiesOfClass(LivingEntity.class, getBoundingBox(), Entity::isAlive); + if (!colliding.isEmpty()) { + Direction facing = getFacing(); + Direction motion = isReversed() ? facing.getOpposite() : facing; + Vec3 center = getCenter(); + for (LivingEntity entity : colliding) { + applyEffects(entity, center, motion); + } + } + } + + public static void applyEffects(Entity entity, Vec3 tubeCenter, Direction motionDirection) { + if (entity instanceof Player player && player.getAbilities().flying) + return; + Vec3 entityCenter = entity.getBoundingBox().getCenter(); + Vec3 motion = Vec3.atLowerCornerOf(motionDirection.getNormal()).scale(0.125); + + RayonIntegration.INSTANCE.setNoGravity(entity, true); + entity.resetFallDistance(); + + EntityExt entityEx = (EntityExt) entity; + if (!entityEx.isInFunnel()) { + entityEx.setInFunnel(true); + entity.setDeltaMovement(0, 0, 0); + if (entity instanceof Player player && player.isLocalPlayer()) + playEnterSound(); + } + entityEx.setFunnelTimer(2); + + Vec3 velocity = entity.getDeltaMovement(); + // check for inputs + if (entity instanceof HasMovementInputAccessor inputProvider && inputProvider.hasMovementInputPublic()) { + if (motion.x == 0) + motion = motion.add(velocity.x, 0, 0); + if (motion.y == 0) + motion = motion.add(0, velocity.y, 0); + if (motion.z == 0) + motion = motion.add(0, 0, velocity.z); + } + + // move entity towards center + double dx = entityCenter.x - tubeCenter.x + velocity.x; + double dy = entityCenter.y - tubeCenter.y + velocity.y; + double dz = entityCenter.z - tubeCenter.z + velocity.z; + + if (motion.x == 0) + motion = motion.add(-Math.copySign(Math.sqrt(Math.abs(dx)), dx) / 20, 0, 0); + if (motion.y == 0) + motion = motion.add(0, -Math.copySign(Math.sqrt(Math.abs(dy)), dy) / 20, 0); + if (motion.z == 0) + motion = motion.add(0, 0, -Math.copySign(Math.sqrt(Math.abs(dz)), dz) / 20); + + entity.setDeltaMovement(motion); + + if (entity.isShiftKeyDown() && motion.lengthSqr() < 0.15 * 0.15 && !entity.isFree(motion.x, motion.y, motion.z)) { + entityEx.setCFG(); + } + } + + @ClientOnly + private static void playEnterSound() { + Minecraft.getInstance().getSoundManager().play(new ExcursionFunnelEnterSoundInstance()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/fluids/PortalCubedFluids.java b/src/main/java/com/fusionflux/portalcubed/fluids/PortalCubedFluids.java index 602f0db5..548e3693 100644 --- a/src/main/java/com/fusionflux/portalcubed/fluids/PortalCubedFluids.java +++ b/src/main/java/com/fusionflux/portalcubed/fluids/PortalCubedFluids.java @@ -22,50 +22,50 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedFluids { - public static final FluidRegistryContainer TOXIC_GOO = createFluid( - "toxic_goo", - new ToxicGooFluid.Flowing(), new ToxicGooFluid.Still(), - still -> new ToxicGooFluid.Block(still, QuiltBlockSettings.copy(Blocks.WATER).mapColor(MapColor.TERRACOTTA_GREEN)) - ); + public static final FluidRegistryContainer TOXIC_GOO = createFluid( + "toxic_goo", + new ToxicGooFluid.Flowing(), new ToxicGooFluid.Still(), + still -> new ToxicGooFluid.Block(still, QuiltBlockSettings.copy(Blocks.WATER).mapColor(MapColor.TERRACOTTA_GREEN)) + ); - private static FluidRegistryContainer createFluid(String name, FlowingFluid flowing, FlowingFluid still, Function blockSupplier) { - return new FluidRegistryContainer(name, flowing, still, blockSupplier, new BucketItem(still, new QuiltItemSettings().craftRemainder(Items.BUCKET).stacksTo(1))); - } + private static FluidRegistryContainer createFluid(String name, FlowingFluid flowing, FlowingFluid still, Function blockSupplier) { + return new FluidRegistryContainer(name, flowing, still, blockSupplier, new BucketItem(still, new QuiltItemSettings().craftRemainder(Items.BUCKET).stacksTo(1))); + } - public static void registerFluids() { - TOXIC_GOO.register(); - } + public static void registerFluids() { + TOXIC_GOO.register(); + } - public static class FluidRegistryContainer { - public final String name; - public final FlowingFluid flowing; - public final FlowingFluid still; - public final Item bucket; + public static class FluidRegistryContainer { + public final String name; + public final FlowingFluid flowing; + public final FlowingFluid still; + public final Item bucket; - private final Supplier block; + private final Supplier block; - private FluidRegistryContainer(String name, FlowingFluid flowing, FlowingFluid still, Function blockSupplier, Item bucket) { - this.name = name; - this.flowing = flowing; - this.still = still; - this.bucket = bucket; - block = Suppliers.memoize(() -> blockSupplier.apply(still)); - } + private FluidRegistryContainer(String name, FlowingFluid flowing, FlowingFluid still, Function blockSupplier, Item bucket) { + this.name = name; + this.flowing = flowing; + this.still = still; + this.bucket = bucket; + block = Suppliers.memoize(() -> blockSupplier.apply(still)); + } - private void register() { - Registry.register(BuiltInRegistries.FLUID, id("flowing_" + name), flowing); - Registry.register(BuiltInRegistries.FLUID, id(name), still); - Registry.register(BuiltInRegistries.BLOCK, id(name), block.get()); - if (bucket != null) { - Registry.register(BuiltInRegistries.ITEM, id(name + "_bucket"), bucket); - DispenserBlock.registerBehavior( - bucket, ((DispenserBlockAccessor)Blocks.DISPENSER).invokeGetDispenseMethod(new ItemStack(Items.WATER_BUCKET)) - ); - } - } + private void register() { + Registry.register(BuiltInRegistries.FLUID, id("flowing_" + name), flowing); + Registry.register(BuiltInRegistries.FLUID, id(name), still); + Registry.register(BuiltInRegistries.BLOCK, id(name), block.get()); + if (bucket != null) { + Registry.register(BuiltInRegistries.ITEM, id(name + "_bucket"), bucket); + DispenserBlock.registerBehavior( + bucket, ((DispenserBlockAccessor)Blocks.DISPENSER).invokeGetDispenseMethod(new ItemStack(Items.WATER_BUCKET)) + ); + } + } - public LiquidBlock getBlock() { - return block.get(); - } - } + public LiquidBlock getBlock() { + return block.get(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/fluids/ToxicGooFluid.java b/src/main/java/com/fusionflux/portalcubed/fluids/ToxicGooFluid.java index a3ad3641..8c9db7c1 100644 --- a/src/main/java/com/fusionflux/portalcubed/fluids/ToxicGooFluid.java +++ b/src/main/java/com/fusionflux/portalcubed/fluids/ToxicGooFluid.java @@ -21,116 +21,116 @@ import static com.fusionflux.portalcubed.mechanics.PortalCubedDamageSources.pcSources; public abstract class ToxicGooFluid extends FlowingFluid { - @NotNull - @Override - public Fluid getSource() { - return PortalCubedFluids.TOXIC_GOO.still; - } - - @NotNull - @Override - public Fluid getFlowing() { - return PortalCubedFluids.TOXIC_GOO.flowing; - } - - @NotNull - @Override - public Item getBucket() { - return PortalCubedFluids.TOXIC_GOO.bucket; - } - - @NotNull - @Override - protected BlockState createLegacyBlock(FluidState state) { - return PortalCubedFluids.TOXIC_GOO.getBlock().defaultBlockState().setValue(BlockStateProperties.LEVEL, getLegacyLevel(state)); - } - - @Override - public boolean isSame(Fluid fluid) { - return fluid == getSource() || fluid == getFlowing(); - } - - @Override - protected boolean canConvertToSource(Level level) { - return true; - } - - @Override - protected void beforeDestroyingBlock(LevelAccessor world, BlockPos pos, BlockState state) { - Block.dropResources(state, world, pos, state.hasBlockEntity() ? world.getBlockEntity(pos) : null); - } - - @Override - protected boolean canBeReplacedWith(FluidState state, BlockGetter world, BlockPos pos, Fluid fluid, - Direction direction) { - return false; - } - - @Override - protected int getSlopeFindDistance(LevelReader world) { - return 4; - } - - @Override - protected int getDropOff(LevelReader world) { - return 2; - } - - @Override - public int getTickDelay(LevelReader world) { - return 20; - } - - @Override - protected float getExplosionResistance() { - return 100; - } - - public static class Flowing extends ToxicGooFluid { - @Override - protected void createFluidStateDefinition(Builder builder) { - builder.add(FALLING, LEVEL); - } - - @Override - public int getAmount(FluidState state) { - return state.getValue(LEVEL); - } - - @Override - public boolean isSource(FluidState state) { - return false; - } - } - - public static class Still extends ToxicGooFluid { - @Override - public int getAmount(FluidState state) { - return 8; - } - - @Override - public boolean isSource(FluidState state) { - return true; - } - } - - public static class Block extends LiquidBlock { - public Block(FlowingFluid flowableFluid, Properties settings) { - super(flowableFluid, settings); - } - - @Override - @SuppressWarnings("deprecation") - public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { - if (!entity.isAlive()) return; - if (entity instanceof Fizzleable fizzleable) { - if (!level.isClientSide && fizzleable.fizzlesInGoo()) { - fizzleable.fizzle(); - } - } else { - entity.hurt(pcSources(level).acid(), level.getRandom().nextIntBetweenInclusive(7, 10)); - } - } - } + @NotNull + @Override + public Fluid getSource() { + return PortalCubedFluids.TOXIC_GOO.still; + } + + @NotNull + @Override + public Fluid getFlowing() { + return PortalCubedFluids.TOXIC_GOO.flowing; + } + + @NotNull + @Override + public Item getBucket() { + return PortalCubedFluids.TOXIC_GOO.bucket; + } + + @NotNull + @Override + protected BlockState createLegacyBlock(FluidState state) { + return PortalCubedFluids.TOXIC_GOO.getBlock().defaultBlockState().setValue(BlockStateProperties.LEVEL, getLegacyLevel(state)); + } + + @Override + public boolean isSame(Fluid fluid) { + return fluid == getSource() || fluid == getFlowing(); + } + + @Override + protected boolean canConvertToSource(Level level) { + return true; + } + + @Override + protected void beforeDestroyingBlock(LevelAccessor world, BlockPos pos, BlockState state) { + Block.dropResources(state, world, pos, state.hasBlockEntity() ? world.getBlockEntity(pos) : null); + } + + @Override + protected boolean canBeReplacedWith(FluidState state, BlockGetter world, BlockPos pos, Fluid fluid, + Direction direction) { + return false; + } + + @Override + protected int getSlopeFindDistance(LevelReader world) { + return 4; + } + + @Override + protected int getDropOff(LevelReader world) { + return 2; + } + + @Override + public int getTickDelay(LevelReader world) { + return 20; + } + + @Override + protected float getExplosionResistance() { + return 100; + } + + public static class Flowing extends ToxicGooFluid { + @Override + protected void createFluidStateDefinition(Builder builder) { + builder.add(FALLING, LEVEL); + } + + @Override + public int getAmount(FluidState state) { + return state.getValue(LEVEL); + } + + @Override + public boolean isSource(FluidState state) { + return false; + } + } + + public static class Still extends ToxicGooFluid { + @Override + public int getAmount(FluidState state) { + return 8; + } + + @Override + public boolean isSource(FluidState state) { + return true; + } + } + + public static class Block extends LiquidBlock { + public Block(FlowingFluid flowableFluid, Properties settings) { + super(flowableFluid, settings); + } + + @Override + @SuppressWarnings("deprecation") + public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { + if (!entity.isAlive()) return; + if (entity instanceof Fizzleable fizzleable) { + if (!level.isClientSide && fizzleable.fizzlesInGoo()) { + fizzleable.fizzle(); + } + } else { + entity.hurt(pcSources(level).acid(), level.getRandom().nextIntBetweenInclusive(7, 10)); + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/fog/FogPersistentState.java b/src/main/java/com/fusionflux/portalcubed/fog/FogPersistentState.java index e80eef11..0e0e37c7 100644 --- a/src/main/java/com/fusionflux/portalcubed/fog/FogPersistentState.java +++ b/src/main/java/com/fusionflux/portalcubed/fog/FogPersistentState.java @@ -6,41 +6,41 @@ import org.jetbrains.annotations.Nullable; public class FogPersistentState extends SavedData { - @Nullable - private FogSettings settings = null; - - public FogPersistentState() { - } - - public FogPersistentState(@Nullable FogSettings settings) { - this.settings = settings; - } - - @Override - public CompoundTag save(CompoundTag nbt) { - if (settings != null) { - nbt.put("Settings", settings.writeNbt(new CompoundTag())); - } - return nbt; - } - - public static FogPersistentState readNbt(CompoundTag nbt) { - return new FogPersistentState(FogSettings.readNbt(nbt.getCompound("Settings"))); - } - - @Nullable - public FogSettings getSettings() { - return settings; - } - - public void setSettings(@Nullable FogSettings settings) { - this.settings = settings; - setDirty(); - } - - public static FogPersistentState getOrCreate(ServerLevel world) { - return world.getDataStorage().computeIfAbsent( - FogPersistentState::readNbt, FogPersistentState::new, "pc_custom_fog" - ); - } + @Nullable + private FogSettings settings = null; + + public FogPersistentState() { + } + + public FogPersistentState(@Nullable FogSettings settings) { + this.settings = settings; + } + + @Override + public CompoundTag save(CompoundTag nbt) { + if (settings != null) { + nbt.put("Settings", settings.writeNbt(new CompoundTag())); + } + return nbt; + } + + public static FogPersistentState readNbt(CompoundTag nbt) { + return new FogPersistentState(FogSettings.readNbt(nbt.getCompound("Settings"))); + } + + @Nullable + public FogSettings getSettings() { + return settings; + } + + public void setSettings(@Nullable FogSettings settings) { + this.settings = settings; + setDirty(); + } + + public static FogPersistentState getOrCreate(ServerLevel world) { + return world.getDataStorage().computeIfAbsent( + FogPersistentState::readNbt, FogPersistentState::new, "pc_custom_fog" + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/fog/FogPreset.java b/src/main/java/com/fusionflux/portalcubed/fog/FogPreset.java index afafd8a6..9b39be35 100644 --- a/src/main/java/com/fusionflux/portalcubed/fog/FogPreset.java +++ b/src/main/java/com/fusionflux/portalcubed/fog/FogPreset.java @@ -5,45 +5,45 @@ import java.util.Locale; public enum FogPreset implements StringRepresentable { - PORTAL_ESCAPE(64, 3500, 58, 82, 101), - PORTAL_2_FAN(128, 3600, 16, 19, 22), - PORTAL_2_GLADOS_INTRO(0, 3500, 39, 54, 63), - PORTAL_2_TESTCHAMBER(128, 5000, 40, 53, 64), - PORTAL_2_DESTROYED(128, 2500, 50, 70, 80), - PORTAL_2_DESTROYED_B(128, 5000, 50, 70, 80), - PORTAL_2_BTS(1, 5000, 56, 95, 141), - PORTAL_2_MINES(0, 6000, 70, 85, 100), - PORTAL_2_BOTTOMLESS_PIT_FALLING(0, 3000, 3, 6, 8), - PORTAL_2_BOTTOMLESS_PIT(0, 6000, 70, 85, 100), - PORTAL_2_UNDERGROUND(0, 4500, 37, 35, 33), - PORTAL_2_LAKE_B(0, 4500, 70, 85, 100), - PORTAL_2_TUBERIDE(128, 5500, 120, 155, 170), - PORTAL_2_WHEATLEY_Z(10000, 11000, 0, 0, 0), - PORTAL_2_LAKE(0, 10000, 70, 85, 100), - PORTAL_2_DARKNESS(1, 2500, 14, 20, 22), - PORTAL_2_JAILBREAK(128, 4000, 100, 140, 160), - PORTAL_2_ACT4_01(128, 2500, 50, 70, 80), - PORTAL_2_ACT4_02(128, 3500, 50, 70, 80), - PORTAL_2_ACT4_03(64, 6000, 50, 70, 80); - - private final String id = name().toLowerCase(Locale.ROOT); - private final FogSettings settings; - - FogPreset(int start, int end, int r, int g, int b) { - this.settings = new FogSettings(start / 64f, end / 64f, new FogSettings.Color(r, g, b), FogSettings.Shape.SPHERE); - } - - @Override - public String getSerializedName() { - return id; - } - - @Override - public String toString() { - return id; - } - - public FogSettings getSettings() { - return settings; - } + PORTAL_ESCAPE(64, 3500, 58, 82, 101), + PORTAL_2_FAN(128, 3600, 16, 19, 22), + PORTAL_2_GLADOS_INTRO(0, 3500, 39, 54, 63), + PORTAL_2_TESTCHAMBER(128, 5000, 40, 53, 64), + PORTAL_2_DESTROYED(128, 2500, 50, 70, 80), + PORTAL_2_DESTROYED_B(128, 5000, 50, 70, 80), + PORTAL_2_BTS(1, 5000, 56, 95, 141), + PORTAL_2_MINES(0, 6000, 70, 85, 100), + PORTAL_2_BOTTOMLESS_PIT_FALLING(0, 3000, 3, 6, 8), + PORTAL_2_BOTTOMLESS_PIT(0, 6000, 70, 85, 100), + PORTAL_2_UNDERGROUND(0, 4500, 37, 35, 33), + PORTAL_2_LAKE_B(0, 4500, 70, 85, 100), + PORTAL_2_TUBERIDE(128, 5500, 120, 155, 170), + PORTAL_2_WHEATLEY_Z(10000, 11000, 0, 0, 0), + PORTAL_2_LAKE(0, 10000, 70, 85, 100), + PORTAL_2_DARKNESS(1, 2500, 14, 20, 22), + PORTAL_2_JAILBREAK(128, 4000, 100, 140, 160), + PORTAL_2_ACT4_01(128, 2500, 50, 70, 80), + PORTAL_2_ACT4_02(128, 3500, 50, 70, 80), + PORTAL_2_ACT4_03(64, 6000, 50, 70, 80); + + private final String id = name().toLowerCase(Locale.ROOT); + private final FogSettings settings; + + FogPreset(int start, int end, int r, int g, int b) { + this.settings = new FogSettings(start / 64f, end / 64f, new FogSettings.Color(r, g, b), FogSettings.Shape.SPHERE); + } + + @Override + public String getSerializedName() { + return id; + } + + @Override + public String toString() { + return id; + } + + public FogSettings getSettings() { + return settings; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/fog/FogSettings.java b/src/main/java/com/fusionflux/portalcubed/fog/FogSettings.java index dc73af90..e9b3c93f 100644 --- a/src/main/java/com/fusionflux/portalcubed/fog/FogSettings.java +++ b/src/main/java/com/fusionflux/portalcubed/fog/FogSettings.java @@ -11,76 +11,76 @@ import java.util.Optional; public record FogSettings(float start, float end, Color color, Shape shape) { - public record Color(int r, int g, int b) { - } + public record Color(int r, int g, int b) { + } - public enum Shape implements StringRepresentable { - SPHERE, CYLINDER; + public enum Shape implements StringRepresentable { + SPHERE, CYLINDER; - private final String id = name().toLowerCase(Locale.ROOT); + private final String id = name().toLowerCase(Locale.ROOT); - @Override - public String getSerializedName() { - return id; - } + @Override + public String getSerializedName() { + return id; + } - @Override - public String toString() { - return id; - } + @Override + public String toString() { + return id; + } - @ClientOnly - public com.mojang.blaze3d.shaders.FogShape toBlaze3d() { - return com.mojang.blaze3d.shaders.FogShape.values()[ordinal()]; - } - } + @ClientOnly + public com.mojang.blaze3d.shaders.FogShape toBlaze3d() { + return com.mojang.blaze3d.shaders.FogShape.values()[ordinal()]; + } + } - public CompoundTag writeNbt(CompoundTag nbt) { - nbt.putFloat("Start", start); - nbt.putFloat("End", end); - nbt.putByteArray("Color", new byte[] {(byte)color.r, (byte)color.g, (byte)color.b}); - nbt.putByte("Shape", (byte)shape.ordinal()); - return nbt; - } + public CompoundTag writeNbt(CompoundTag nbt) { + nbt.putFloat("Start", start); + nbt.putFloat("End", end); + nbt.putByteArray("Color", new byte[] {(byte)color.r, (byte)color.g, (byte)color.b}); + nbt.putByte("Shape", (byte)shape.ordinal()); + return nbt; + } - public static FogSettings readNbt(CompoundTag nbt) { - if (nbt.isEmpty()) { - return null; - } - final byte[] color = nbt.getByteArray("Color"); - return new FogSettings( - nbt.getFloat("Start"), - nbt.getFloat("End"), - new Color(color[0] & 0xff, color[1] & 0xff, color[2] & 0xff), - Shape.values()[nbt.getByte("Shape") & 0xff] - ); - } + public static FogSettings readNbt(CompoundTag nbt) { + if (nbt.isEmpty()) { + return null; + } + final byte[] color = nbt.getByteArray("Color"); + return new FogSettings( + nbt.getFloat("Start"), + nbt.getFloat("End"), + new Color(color[0] & 0xff, color[1] & 0xff, color[2] & 0xff), + Shape.values()[nbt.getByte("Shape") & 0xff] + ); + } - public void encode(FriendlyByteBuf buf) { - buf.writeFloat(start); - buf.writeFloat(end); - buf.writeByte(color.r); - buf.writeByte(color.g); - buf.writeByte(color.b); - buf.writeEnum(shape); - } + public void encode(FriendlyByteBuf buf) { + buf.writeFloat(start); + buf.writeFloat(end); + buf.writeByte(color.r); + buf.writeByte(color.g); + buf.writeByte(color.b); + buf.writeEnum(shape); + } - public static void encodeOptional(@Nullable FogSettings settings, FriendlyByteBuf buf) { - buf.writeOptional(Optional.ofNullable(settings), (buf1, settings1) -> settings1.encode(buf1)); - } + public static void encodeOptional(@Nullable FogSettings settings, FriendlyByteBuf buf) { + buf.writeOptional(Optional.ofNullable(settings), (buf1, settings1) -> settings1.encode(buf1)); + } - @NotNull - public static FogSettings decode(FriendlyByteBuf buf) { - return new FogSettings( - buf.readFloat(), - buf.readFloat(), - new Color(buf.readByte() & 0xff, buf.readByte() & 0xff, buf.readByte() & 0xff), - buf.readEnum(Shape.class) - ); - } + @NotNull + public static FogSettings decode(FriendlyByteBuf buf) { + return new FogSettings( + buf.readFloat(), + buf.readFloat(), + new Color(buf.readByte() & 0xff, buf.readByte() & 0xff, buf.readByte() & 0xff), + buf.readEnum(Shape.class) + ); + } - @Nullable - public static FogSettings decodeOptional(FriendlyByteBuf buf) { - return buf.readOptional(FogSettings::decode).orElse(null); - } + @Nullable + public static FogSettings decodeOptional(FriendlyByteBuf buf) { + return buf.readOptional(FogSettings::decode).orElse(null); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/gui/BlockPosScreenHandler.java b/src/main/java/com/fusionflux/portalcubed/gui/BlockPosScreenHandler.java index 09a7f2e0..0fa0d989 100644 --- a/src/main/java/com/fusionflux/portalcubed/gui/BlockPosScreenHandler.java +++ b/src/main/java/com/fusionflux/portalcubed/gui/BlockPosScreenHandler.java @@ -13,37 +13,37 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class BlockPosScreenHandler extends AbstractContainerMenu { - private final BlockPos at; - - public BlockPosScreenHandler(MenuType type, int syncId, BlockPos at) { - super(type, syncId); - this.at = at; - } - - public static ExtendedScreenHandlerType createType() { - @SuppressWarnings("unchecked") - final ExtendedScreenHandlerType[] type = new ExtendedScreenHandlerType[1]; - return type[0] = new ExtendedScreenHandlerType<>( - (syncId, inventory, buf) -> new BlockPosScreenHandler(type[0], syncId, buf.readBlockPos()) - ); - } - - public static MenuType registerNew(String id) { - return Registry.register(BuiltInRegistries.MENU, id(id), createType()); - } - - @NotNull - @Override - public ItemStack quickMoveStack(Player player, int fromIndex) { - return ItemStack.EMPTY; - } - - @Override - public boolean stillValid(Player player) { - return player.isCreative(); - } - - public BlockPos getAt() { - return at; - } + private final BlockPos at; + + public BlockPosScreenHandler(MenuType type, int syncId, BlockPos at) { + super(type, syncId); + this.at = at; + } + + public static ExtendedScreenHandlerType createType() { + @SuppressWarnings("unchecked") + final ExtendedScreenHandlerType[] type = new ExtendedScreenHandlerType[1]; + return type[0] = new ExtendedScreenHandlerType<>( + (syncId, inventory, buf) -> new BlockPosScreenHandler(type[0], syncId, buf.readBlockPos()) + ); + } + + public static MenuType registerNew(String id) { + return Registry.register(BuiltInRegistries.MENU, id(id), createType()); + } + + @NotNull + @Override + public ItemStack quickMoveStack(Player player, int fromIndex) { + return ItemStack.EMPTY; + } + + @Override + public boolean stillValid(Player player) { + return player.isCreative(); + } + + public BlockPos getAt() { + return at; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/gui/FaithPlateScreenHandler.java b/src/main/java/com/fusionflux/portalcubed/gui/FaithPlateScreenHandler.java index 9085d140..2ed5a447 100644 --- a/src/main/java/com/fusionflux/portalcubed/gui/FaithPlateScreenHandler.java +++ b/src/main/java/com/fusionflux/portalcubed/gui/FaithPlateScreenHandler.java @@ -9,46 +9,46 @@ import net.minecraft.world.item.ItemStack; public class FaithPlateScreenHandler extends AbstractContainerMenu { - private BlockPos pos; - private double x = 0; - private double y = 0; - private double z = 0; - - public FaithPlateScreenHandler(int syncId, @SuppressWarnings("unused") Inventory playerInventory, FriendlyByteBuf buf) { - this(syncId); - this.pos = buf.readBlockPos(); - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - } - - public BlockPos getPos() { - return pos; - } - - public double getX() { - return x; - } - - public double getY() { - return y; - } - - public double getZ() { - return z; - } - - public FaithPlateScreenHandler(int syncId) { - super(PortalCubed.FAITH_PLATE_SCREEN_HANDLER, syncId); - } - - @Override - public ItemStack quickMoveStack(Player player, int fromIndex) { - return null; - } - - @Override - public boolean stillValid(Player player) { - return true; - } + private BlockPos pos; + private double x = 0; + private double y = 0; + private double z = 0; + + public FaithPlateScreenHandler(int syncId, @SuppressWarnings("unused") Inventory playerInventory, FriendlyByteBuf buf) { + this(syncId); + this.pos = buf.readBlockPos(); + this.x = buf.readDouble(); + this.y = buf.readDouble(); + this.z = buf.readDouble(); + } + + public BlockPos getPos() { + return pos; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public FaithPlateScreenHandler(int syncId) { + super(PortalCubed.FAITH_PLATE_SCREEN_HANDLER, syncId); + } + + @Override + public ItemStack quickMoveStack(Player player, int fromIndex) { + return null; + } + + @Override + public boolean stillValid(Player player) { + return true; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/CrowbarItem.java b/src/main/java/com/fusionflux/portalcubed/items/CrowbarItem.java index 145acca3..2d505968 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/CrowbarItem.java +++ b/src/main/java/com/fusionflux/portalcubed/items/CrowbarItem.java @@ -16,41 +16,41 @@ import org.jetbrains.annotations.NotNull; public class CrowbarItem extends Item { - private static final Multimap ATTRIBUTE_MODIFIERS = - ImmutableMultimap.builder() - .put( - Attributes.ATTACK_DAMAGE, - new AttributeModifier( - BASE_ATTACK_DAMAGE_UUID, - "Weapon modifier", - ((SwordItem)Items.IRON_SWORD).getDamage(), - AttributeModifier.Operation.ADDITION - ) - ) - .put( - Attributes.ATTACK_SPEED, - new AttributeModifier( - BASE_ATTACK_SPEED_UUID, - "Weapon modifier", - -2.4f, - AttributeModifier.Operation.ADDITION - ) - ) - .build(); + private static final Multimap ATTRIBUTE_MODIFIERS = + ImmutableMultimap.builder() + .put( + Attributes.ATTACK_DAMAGE, + new AttributeModifier( + BASE_ATTACK_DAMAGE_UUID, + "Weapon modifier", + ((SwordItem)Items.IRON_SWORD).getDamage(), + AttributeModifier.Operation.ADDITION + ) + ) + .put( + Attributes.ATTACK_SPEED, + new AttributeModifier( + BASE_ATTACK_SPEED_UUID, + "Weapon modifier", + -2.4f, + AttributeModifier.Operation.ADDITION + ) + ) + .build(); - public CrowbarItem(Properties settings) { - super(settings); - } + public CrowbarItem(Properties settings) { + super(settings); + } - @Override - public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { - // We spawn a decal instead of mining - return false; - } + @Override + public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { + // We spawn a decal instead of mining + return false; + } - @NotNull - @Override - public Multimap getDefaultAttributeModifiers(EquipmentSlot slot) { - return slot == EquipmentSlot.MAINHAND ? ATTRIBUTE_MODIFIERS : super.getDefaultAttributeModifiers(slot); - } + @NotNull + @Override + public Multimap getDefaultAttributeModifiers(EquipmentSlot slot) { + return slot == EquipmentSlot.MAINHAND ? ATTRIBUTE_MODIFIERS : super.getDefaultAttributeModifiers(slot); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/EnergyPelletItem.java b/src/main/java/com/fusionflux/portalcubed/items/EnergyPelletItem.java index af2ed5c8..e629770e 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/EnergyPelletItem.java +++ b/src/main/java/com/fusionflux/portalcubed/items/EnergyPelletItem.java @@ -18,62 +18,62 @@ import org.jetbrains.annotations.NotNull; public class EnergyPelletItem extends Item { - private final boolean isSuper; + private final boolean isSuper; - public EnergyPelletItem(Properties settings, boolean isSuper) { - super(settings); - this.isSuper = isSuper; - } + public EnergyPelletItem(Properties settings, boolean isSuper) { + super(settings); + this.isSuper = isSuper; + } - @NotNull - @Override - public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { - final ItemStack item = user.getItemInHand(hand); - if (world.isClientSide) return InteractionResultHolder.pass(item); - if (!user.getAbilities().instabuild) { - item.shrink(1); - } - final EnergyPellet pellet = PortalCubedEntities.ENERGY_PELLET.create(world); - if (pellet == null) return InteractionResultHolder.pass(item); - pellet.setPos(user.getEyePosition(0).add(user.getLookAngle())); - Vec3 userVelocity = user.getDeltaMovement(); - if (user.onGround()) { - userVelocity = userVelocity.with(Direction.Axis.Y, 0); - } - pellet.setDeltaMovement(userVelocity.add(user.getLookAngle().scale(0.25))); - if (isSuper) { - pellet.resetLife(-1); - } - pellet.setThrower(user); - world.addFreshEntity(pellet); - return InteractionResultHolder.consume(item); - } + @NotNull + @Override + public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { + final ItemStack item = user.getItemInHand(hand); + if (world.isClientSide) return InteractionResultHolder.pass(item); + if (!user.getAbilities().instabuild) { + item.shrink(1); + } + final EnergyPellet pellet = PortalCubedEntities.ENERGY_PELLET.create(world); + if (pellet == null) return InteractionResultHolder.pass(item); + pellet.setPos(user.getEyePosition(0).add(user.getLookAngle())); + Vec3 userVelocity = user.getDeltaMovement(); + if (user.onGround()) { + userVelocity = userVelocity.with(Direction.Axis.Y, 0); + } + pellet.setDeltaMovement(userVelocity.add(user.getLookAngle().scale(0.25))); + if (isSuper) { + pellet.resetLife(-1); + } + pellet.setThrower(user); + world.addFreshEntity(pellet); + return InteractionResultHolder.consume(item); + } - public DispenseItemBehavior createDispenserBehavior() { - return new DefaultDispenseItemBehavior() { - @NotNull - @Override - protected ItemStack execute(BlockSource pointer, ItemStack stack) { - final EnergyPellet pellet = PortalCubedEntities.ENERGY_PELLET.create(pointer.getLevel()); - if (pellet == null) return stack; - final Position pos = DispenserBlock.getDispensePosition(pointer); - pellet.setPos(pos.x(), pos.y(), pos.z()); - pellet.setDeltaMovement(Vec3.atLowerCornerOf(pointer.getBlockState().getValue(DispenserBlock.FACING).getNormal())); - if (isSuper) { - pellet.resetLife(-1); - } - pointer.getLevel().addFreshEntity(pellet); - stack.shrink(1); - return stack; - } + public DispenseItemBehavior createDispenserBehavior() { + return new DefaultDispenseItemBehavior() { + @NotNull + @Override + protected ItemStack execute(BlockSource pointer, ItemStack stack) { + final EnergyPellet pellet = PortalCubedEntities.ENERGY_PELLET.create(pointer.getLevel()); + if (pellet == null) return stack; + final Position pos = DispenserBlock.getDispensePosition(pointer); + pellet.setPos(pos.x(), pos.y(), pos.z()); + pellet.setDeltaMovement(Vec3.atLowerCornerOf(pointer.getBlockState().getValue(DispenserBlock.FACING).getNormal())); + if (isSuper) { + pellet.resetLife(-1); + } + pointer.getLevel().addFreshEntity(pellet); + stack.shrink(1); + return stack; + } - @Override - protected void playSound(BlockSource pointer) { - } + @Override + protected void playSound(BlockSource pointer) { + } - @Override - protected void playAnimation(BlockSource pointer, Direction side) { - } - }; - } + @Override + protected void playAnimation(BlockSource pointer, Direction side) { + } + }; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/ExcursionFunnelEmitterBlockItem.java b/src/main/java/com/fusionflux/portalcubed/items/ExcursionFunnelEmitterBlockItem.java index 1be7770a..09ea1729 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/ExcursionFunnelEmitterBlockItem.java +++ b/src/main/java/com/fusionflux/portalcubed/items/ExcursionFunnelEmitterBlockItem.java @@ -19,80 +19,80 @@ import java.util.List; public class ExcursionFunnelEmitterBlockItem extends BlockItem implements MultiblockItem { - public static final Collection> REQUIRED_PROPERTIES = List.of( - ExcursionFunnelEmitterBlock.QUADRANT, BlockStateProperties.FACING - ); + public static final Collection> REQUIRED_PROPERTIES = List.of( + ExcursionFunnelEmitterBlock.QUADRANT, BlockStateProperties.FACING + ); - public ExcursionFunnelEmitterBlockItem(Block block, Properties properties) { - super(block, properties); - if (!block.getStateDefinition().getProperties().containsAll(REQUIRED_PROPERTIES)) - throw new IllegalArgumentException("Cannot create an ExcursionFunnelEmitterBlockItem for a block without the required properties"); - } + public ExcursionFunnelEmitterBlockItem(Block block, Properties properties) { + super(block, properties); + if (!block.getStateDefinition().getProperties().containsAll(REQUIRED_PROPERTIES)) + throw new IllegalArgumentException("Cannot create an ExcursionFunnelEmitterBlockItem for a block without the required properties"); + } - @Override - protected boolean placeBlock(BlockPlaceContext context, BlockState state) { - Direction playerFacing = context.getHorizontalDirection(); - Level level = context.getLevel(); - TwoByTwo placement = findValidPlacement(level, state, context.getClickedPos(), playerFacing); - if (placement == null) - return false; - // placing is handled with facing as player facing, but facing is actually the direction the funnel faces - Direction facing = state.getValue(BlockStateProperties.FACING).getOpposite(); - BlockState baseToPlace = state.setValue(BlockStateProperties.FACING, facing); - // for each quadrant - for (int i = 1; i <= 4; i++) { - BlockPos pos = placement.byQuadrant(i); - BlockState toPlace = baseToPlace.setValue(ExcursionFunnelEmitterBlock.QUADRANT, i); - level.setBlock(pos, toPlace, 11); - } - // trigger an update, check for power - level.blockUpdated(placement.byQuadrant(1), Blocks.AIR); - return true; - } + @Override + protected boolean placeBlock(BlockPlaceContext context, BlockState state) { + Direction playerFacing = context.getHorizontalDirection(); + Level level = context.getLevel(); + TwoByTwo placement = findValidPlacement(level, state, context.getClickedPos(), playerFacing); + if (placement == null) + return false; + // placing is handled with facing as player facing, but facing is actually the direction the funnel faces + Direction facing = state.getValue(BlockStateProperties.FACING).getOpposite(); + BlockState baseToPlace = state.setValue(BlockStateProperties.FACING, facing); + // for each quadrant + for (int i = 1; i <= 4; i++) { + BlockPos pos = placement.byQuadrant(i); + BlockState toPlace = baseToPlace.setValue(ExcursionFunnelEmitterBlock.QUADRANT, i); + level.setBlock(pos, toPlace, 11); + } + // trigger an update, check for power + level.blockUpdated(placement.byQuadrant(1), Blocks.AIR); + return true; + } - @Nullable - @Override - public TwoByTwo findValidPlacement(Level level, BlockState state, BlockPos initial, Direction playerFacing) { - Direction facing = state.getValue(BlockStateProperties.FACING); - TwoByTwo bases = findBasePlacements(initial, facing, playerFacing); - Direction left = getLeftOf(facing, Direction.SOUTH); - Direction up = getDownOf(facing, Direction.SOUTH).getOpposite(); - basesLoop: for (BlockPos base : bases.quadrants(2, 1, 3, 4)) { - TwoByTwo toPlace = TwoByTwo.fromBottomRightCorner(base, left, up); - for (BlockPos pos : toPlace) { - if (!canPlaceAt(level, pos)) - continue basesLoop; - } - return toPlace; - } - return null; - } + @Nullable + @Override + public TwoByTwo findValidPlacement(Level level, BlockState state, BlockPos initial, Direction playerFacing) { + Direction facing = state.getValue(BlockStateProperties.FACING); + TwoByTwo bases = findBasePlacements(initial, facing, playerFacing); + Direction left = getLeftOf(facing, Direction.SOUTH); + Direction up = getDownOf(facing, Direction.SOUTH).getOpposite(); + basesLoop: for (BlockPos base : bases.quadrants(2, 1, 3, 4)) { + TwoByTwo toPlace = TwoByTwo.fromBottomRightCorner(base, left, up); + for (BlockPos pos : toPlace) { + if (!canPlaceAt(level, pos)) + continue basesLoop; + } + return toPlace; + } + return null; + } - protected TwoByTwo findBasePlacements(BlockPos initial, Direction facing, Direction playerFacing) { - Direction right = getLeftOf(facing, playerFacing).getOpposite(); - Direction down = getDownOf(facing, playerFacing); - return TwoByTwo.fromTopLeftCorner(initial, right, down); - } + protected TwoByTwo findBasePlacements(BlockPos initial, Direction facing, Direction playerFacing) { + Direction right = getLeftOf(facing, playerFacing).getOpposite(); + Direction down = getDownOf(facing, playerFacing); + return TwoByTwo.fromTopLeftCorner(initial, right, down); + } - protected boolean canPlaceAt(Level level, BlockPos pos) { - return level.getBlockState(pos).canBeReplaced(); - } + protected boolean canPlaceAt(Level level, BlockPos pos) { + return level.getBlockState(pos).canBeReplaced(); + } - public static Direction getLeftOf(Direction facing, Direction perspectiveFacing) { - if (facing.getAxis().isHorizontal()) - return facing.getCounterClockWise(); - return perspectiveFacing.getCounterClockWise(); - } + public static Direction getLeftOf(Direction facing, Direction perspectiveFacing) { + if (facing.getAxis().isHorizontal()) + return facing.getCounterClockWise(); + return perspectiveFacing.getCounterClockWise(); + } - public static Direction getDownOf(Direction facing, Direction perspectiveFacing) { - if (facing.getAxis().isHorizontal()) - return Direction.DOWN; - return facing == Direction.DOWN ? perspectiveFacing.getOpposite() : perspectiveFacing; - } + public static Direction getDownOf(Direction facing, Direction perspectiveFacing) { + if (facing.getAxis().isHorizontal()) + return Direction.DOWN; + return facing == Direction.DOWN ? perspectiveFacing.getOpposite() : perspectiveFacing; + } - @Override - @SuppressWarnings("unchecked") - public T getMultiblockBlock() { - return (T)getBlock(); - } + @Override + @SuppressWarnings("unchecked") + public T getMultiblockBlock() { + return (T)getBlock(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/GelBlobItem.java b/src/main/java/com/fusionflux/portalcubed/items/GelBlobItem.java index dafc84f5..5802f378 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/GelBlobItem.java +++ b/src/main/java/com/fusionflux/portalcubed/items/GelBlobItem.java @@ -11,26 +11,26 @@ import net.minecraft.world.level.block.Block; public class GelBlobItem extends BlockItem { - private final EntityType blobEntity; + private final EntityType blobEntity; - public GelBlobItem(Block block, EntityType blobEntity, Properties settings) { - super(block, settings); - this.blobEntity = blobEntity; - } + public GelBlobItem(Block block, EntityType blobEntity, Properties settings) { + super(block, settings); + this.blobEntity = blobEntity; + } - @Override - public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { - final ItemStack item = user.getItemInHand(hand); - if (world.isClientSide) return InteractionResultHolder.pass(item); - final GelBlobEntity entity = blobEntity.create(world); - if (entity == null) return InteractionResultHolder.pass(item); - entity.setPos(user.getX(), user.getEyeY(), user.getZ()); - entity.shootFromRotation(user, user.getXRot(), user.getYRot(), 0f, 3f, 1f); - entity.setOwner(user); - world.addFreshEntity(entity); - if (!user.getAbilities().instabuild) { - item.shrink(1); - } - return InteractionResultHolder.consume(item); - } + @Override + public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { + final ItemStack item = user.getItemInHand(hand); + if (world.isClientSide) return InteractionResultHolder.pass(item); + final GelBlobEntity entity = blobEntity.create(world); + if (entity == null) return InteractionResultHolder.pass(item); + entity.setPos(user.getX(), user.getEyeY(), user.getZ()); + entity.shootFromRotation(user, user.getXRot(), user.getYRot(), 0f, 3f, 1f); + entity.setOwner(user); + world.addFreshEntity(entity); + if (!user.getAbilities().instabuild) { + item.shrink(1); + } + return InteractionResultHolder.consume(item); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/MultiblockItem.java b/src/main/java/com/fusionflux/portalcubed/items/MultiblockItem.java index 3cfae02e..ce637cfe 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/MultiblockItem.java +++ b/src/main/java/com/fusionflux/portalcubed/items/MultiblockItem.java @@ -10,8 +10,8 @@ import org.jetbrains.annotations.Nullable; public interface MultiblockItem { - T getMultiblockBlock(); + T getMultiblockBlock(); - @Nullable - TwoByTwo findValidPlacement(Level level, BlockState state, BlockPos initial, Direction playerFacing); + @Nullable + TwoByTwo findValidPlacement(Level level, BlockState state, BlockPos initial, Direction playerFacing); } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PaintGun.java b/src/main/java/com/fusionflux/portalcubed/items/PaintGun.java index e3ec768a..2a3d54d8 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PaintGun.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PaintGun.java @@ -22,80 +22,80 @@ public class PaintGun extends Item implements ClickHandlingItem, DyeableLeatherItem { - public PaintGun(Properties settings) { - super(settings); - } + public PaintGun(Properties settings) { + super(settings); + } - @Override - public int getColor(ItemStack stack) { - CompoundTag compoundTag = stack.getOrCreateTag(); - boolean complementary = compoundTag.getBoolean("complementary"); - compoundTag = stack.getTagElement("display"); - return compoundTag != null && compoundTag.contains("color", 99) ? complementary ? compoundTag.getInt("color") * -1 : compoundTag.getInt("color") : (complementary ? 14842149 : -14842149); - } + @Override + public int getColor(ItemStack stack) { + CompoundTag compoundTag = stack.getOrCreateTag(); + boolean complementary = compoundTag.getBoolean("complementary"); + compoundTag = stack.getTagElement("display"); + return compoundTag != null && compoundTag.contains("color", 99) ? complementary ? compoundTag.getInt("color") * -1 : compoundTag.getInt("color") : (complementary ? 14842149 : -14842149); + } - private FireableGelType lastFiredGelType = null; + private FireableGelType lastFiredGelType = null; - @Override - public InteractionResult onLeftClick(Player user, InteractionHand hand) { - fireGel(user.level(), user, FireableGelType.REPULSION); - return InteractionResult.CONSUME; - } + @Override + public InteractionResult onLeftClick(Player user, InteractionHand hand) { + fireGel(user.level(), user, FireableGelType.REPULSION); + return InteractionResult.CONSUME; + } - @Override - public InteractionResult onRightClick(Player user, InteractionHand hand) { - fireGel(user.level(), user, FireableGelType.PROPULSION); - return InteractionResult.CONSUME; - } + @Override + public InteractionResult onRightClick(Player user, InteractionHand hand) { + fireGel(user.level(), user, FireableGelType.PROPULSION); + return InteractionResult.CONSUME; + } - @NotNull - @Override - public UseAnim getUseAnimation(ItemStack stack) { - return UseAnim.NONE; - } + @NotNull + @Override + public UseAnim getUseAnimation(ItemStack stack) { + return UseAnim.NONE; + } - @Override - public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { - return false; - } + @Override + public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { + return false; + } - private void fireGel(Level world, Player user, FireableGelType gelType) { - if (lastFiredGelType != null && lastFiredGelType != gelType) { - lastFiredGelType = null; - return; - } - lastFiredGelType = gelType; + private void fireGel(Level world, Player user, FireableGelType gelType) { + if (lastFiredGelType != null && lastFiredGelType != gelType) { + lastFiredGelType = null; + return; + } + lastFiredGelType = gelType; - if (world.isClientSide && !user.isSpectator() && !CalledValues.getCanFireGel(user)) { - var byteBuf = PacketByteBufs.create(); - byteBuf.writeDouble(user.getDeltaMovement().x); - byteBuf.writeDouble(user.getDeltaMovement().y); - byteBuf.writeDouble(user.getDeltaMovement().z); - byteBuf.writeBoolean(true); - NetworkingSafetyWrapper.sendFromClient("request_velocity_for_gel", byteBuf); - } - if (!world.isClientSide && !user.isSpectator() && CalledValues.getCanFireGel(user)) { - final GelBlobEntity entity = gelType.blobEntityType.create(world); - if (entity == null) return; - entity.setPos(user.getX(), user.getEyeY() - .5, user.getZ()); - entity.shootFromRotation(user, user.getXRot(), user.getYRot(), 0f, 2f, 1f); - entity.setOwner(user); - entity.setSize(1); - world.addFreshEntity(entity); - CalledValues.setCanFireGel(user, false); - entity.push(CalledValues.getServerVelForGel(user).x, CalledValues.getServerVelForGel(user).y, CalledValues.getServerVelForGel(user).z); - } - } + if (world.isClientSide && !user.isSpectator() && !CalledValues.getCanFireGel(user)) { + var byteBuf = PacketByteBufs.create(); + byteBuf.writeDouble(user.getDeltaMovement().x); + byteBuf.writeDouble(user.getDeltaMovement().y); + byteBuf.writeDouble(user.getDeltaMovement().z); + byteBuf.writeBoolean(true); + NetworkingSafetyWrapper.sendFromClient("request_velocity_for_gel", byteBuf); + } + if (!world.isClientSide && !user.isSpectator() && CalledValues.getCanFireGel(user)) { + final GelBlobEntity entity = gelType.blobEntityType.create(world); + if (entity == null) return; + entity.setPos(user.getX(), user.getEyeY() - .5, user.getZ()); + entity.shootFromRotation(user, user.getXRot(), user.getYRot(), 0f, 2f, 1f); + entity.setOwner(user); + entity.setSize(1); + world.addFreshEntity(entity); + CalledValues.setCanFireGel(user, false); + entity.push(CalledValues.getServerVelForGel(user).x, CalledValues.getServerVelForGel(user).y, CalledValues.getServerVelForGel(user).z); + } + } - private enum FireableGelType { - REPULSION(PortalCubedEntities.REPULSION_GEL_BLOB), - PROPULSION(PortalCubedEntities.PROPULSION_GEL_BLOB); + private enum FireableGelType { + REPULSION(PortalCubedEntities.REPULSION_GEL_BLOB), + PROPULSION(PortalCubedEntities.PROPULSION_GEL_BLOB); - public final EntityType blobEntityType; + public final EntityType blobEntityType; - FireableGelType(EntityType blobEntityType) { - this.blobEntityType = blobEntityType; - } - } + FireableGelType(EntityType blobEntityType) { + this.blobEntityType = blobEntityType; + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PortalArmor.java b/src/main/java/com/fusionflux/portalcubed/items/PortalArmor.java index 2af17615..5805b280 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PortalArmor.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PortalArmor.java @@ -13,57 +13,57 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalArmor implements ArmorMaterial { - private static final ResourceLocation TEXTURE = id("textures/models/armor/portal_armor"); - private static final int[] BASE_DURABILITY = new int[]{13, 15, 16, 11}; - private static final int[] PROTECTION_VALUES = new int[]{3, 6, 8, 3}; + private static final ResourceLocation TEXTURE = id("textures/models/armor/portal_armor"); + private static final int[] BASE_DURABILITY = new int[]{13, 15, 16, 11}; + private static final int[] PROTECTION_VALUES = new int[]{3, 6, 8, 3}; - @Override - public int getDurabilityForType(ArmorItem.Type type) { - return BASE_DURABILITY[type.getSlot().getIndex()] * 37; - } + @Override + public int getDurabilityForType(ArmorItem.Type type) { + return BASE_DURABILITY[type.getSlot().getIndex()] * 37; + } - @Override - public int getDefenseForType(ArmorItem.Type type) { - return PROTECTION_VALUES[type.getSlot().getIndex()]; - } + @Override + public int getDefenseForType(ArmorItem.Type type) { + return PROTECTION_VALUES[type.getSlot().getIndex()]; + } - @Override - public int getEnchantmentValue() { - return 15; - } + @Override + public int getEnchantmentValue() { + return 15; + } - @NotNull - @Override - public SoundEvent getEquipSound() { - return SoundEvents.ARMOR_EQUIP_NETHERITE; - } + @NotNull + @Override + public SoundEvent getEquipSound() { + return SoundEvents.ARMOR_EQUIP_NETHERITE; + } - @NotNull - @Override - public Ingredient getRepairIngredient() { - return Ingredient.of(Items.NETHERITE_INGOT); - } + @NotNull + @Override + public Ingredient getRepairIngredient() { + return Ingredient.of(Items.NETHERITE_INGOT); + } - @NotNull - @Override - public String getName() { - return "portal_armor"; - } + @NotNull + @Override + public String getName() { + return "portal_armor"; + } - @Override - public float getToughness() { - return 3; - } + @Override + public float getToughness() { + return 3; + } - @Override - public float getKnockbackResistance() { - return 0F; - } + @Override + public float getKnockbackResistance() { + return 0F; + } - @NotNull - @Override - @ClientOnly - public ResourceLocation getTexture() { - return TEXTURE; - } + @NotNull + @Override + @ClientOnly + public ResourceLocation getTexture() { + return TEXTURE; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PortalCubedItems.java b/src/main/java/com/fusionflux/portalcubed/items/PortalCubedItems.java index d4437bcc..3ce1ec12 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PortalCubedItems.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PortalCubedItems.java @@ -16,115 +16,115 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedItems { - public static final ArmorMaterial PORTAL_ARMOR = new PortalArmor(); - public static final Item LONG_FALL_BOOTS = new ArmorItem(PORTAL_ARMOR, ArmorItem.Type.BOOTS, new Item.Properties().fireResistant()); - public static final PortalGun PORTAL_GUN = new PortalGun(new QuiltItemSettings().stacksTo(1).fireResistant()); - - public static final PortalGunPrimary PORTAL_GUN_PRIMARY = new PortalGunPrimary(new QuiltItemSettings().stacksTo(1).fireResistant()); - - public static final PortalGunSecondary PORTAL_GUN_SECONDARY = new PortalGunSecondary(new QuiltItemSettings().stacksTo(1).fireResistant()); - - public static final PaintGun PAINT_GUN = new PaintGun(new QuiltItemSettings().stacksTo(1).fireResistant()); - - public static final Item PORTAL_GUN_FRAME = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); - public static final Item PORTAL_GUN_CASING = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); - public static final Item MINI_BLACKHOLE = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); - public static final Item BLOCK_ITEM_ICON = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); - public static final SpawnEggItem STORAGE_CUBE = new SpawnEggItem(PortalCubedEntities.STORAGE_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem COMPANION_CUBE = new SpawnEggItem(PortalCubedEntities.COMPANION_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem RADIO = new SpawnEggItem(PortalCubedEntities.RADIO, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem REDIRECTION_CUBE = new SpawnEggItem(PortalCubedEntities.REDIRECTION_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem SCHRODINGER_CUBE = new SpawnEggItem(PortalCubedEntities.SCHRODINGER_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem OLD_AP_CUBE = new SpawnEggItem(PortalCubedEntities.OLD_AP_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem PORTAL_1_COMPANION_CUBE = new SpawnEggItem(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem PORTAL_1_STORAGE_CUBE = new SpawnEggItem(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem LIL_PINEAPPLE = new SpawnEggItem(PortalCubedEntities.LIL_PINEAPPLE, 1, 1, new QuiltItemSettings()); - - public static final SpawnEggItem BEANS = new SpawnEggItem(PortalCubedEntities.BEANS, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem MUG = new SpawnEggItem(PortalCubedEntities.MUG, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem JUG = new SpawnEggItem(PortalCubedEntities.JUG, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem COMPUTER = new SpawnEggItem(PortalCubedEntities.COMPUTER, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem CHAIR = new SpawnEggItem(PortalCubedEntities.CHAIR, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem HOOPY = new SpawnEggItem(PortalCubedEntities.HOOPY, 1, 1, new QuiltItemSettings()); - - public static final SpawnEggItem CORE_FRAME = new SpawnEggItem(PortalCubedEntities.CORE_FRAME, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem ANGER_CORE = new SpawnEggItem(PortalCubedEntities.ANGER_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem MORALITY_CORE = new SpawnEggItem(PortalCubedEntities.MORALITY_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem CAKE_CORE = new SpawnEggItem(PortalCubedEntities.CAKE_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem CURIOSITY_CORE = new SpawnEggItem(PortalCubedEntities.CURIOSITY_CORE, 1, 1, new QuiltItemSettings()); - - public static final SpawnEggItem SPACE_CORE = new SpawnEggItem(PortalCubedEntities.SPACE_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem FACT_CORE = new SpawnEggItem(PortalCubedEntities.FACT_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem ADVENTURE_CORE = new SpawnEggItem(PortalCubedEntities.ADVENTURE_CORE, 1, 1, new QuiltItemSettings()); - public static final SpawnEggItem TURRET = new SpawnEggItem(PortalCubedEntities.TURRET, 1, 1, new QuiltItemSettings()); - - - public static final Item HAMMER = new Item(new QuiltItemSettings().stacksTo(1)); - - public static final EnergyPelletItem ENERGY_PELLET = new EnergyPelletItem(new QuiltItemSettings(), false); - public static final EnergyPelletItem SUPER_PELLET = new EnergyPelletItem(new QuiltItemSettings(), true); - - public static final CrowbarItem CROWBAR = new CrowbarItem(new QuiltItemSettings().maxCount(1)); - - public static final Item STILL_ALIVE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/still_alive")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 177); - public static final Item CARA_MIA_ADDIO = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/cara_mia_addio")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 154); - public static final Item WANT_YOU_GONE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/want_you_gone")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 142); - public static final Item RECONSTRUCTING_MORE_SCIENCE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/reconstructing_more_science")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 157); - - public static final TagKey WRENCHES = TagKey.create(Registries.ITEM, new ResourceLocation("c:wrenches")); - public static final TagKey HOLDS_OBJECT = QuiltTagKey.of(Registries.ITEM, id("holds_object"), TagType.CLIENT_ONLY); - public static final TagKey LAYS_ON_FLOOR = QuiltTagKey.of(Registries.ITEM, id("lays_on_floor"), TagType.CLIENT_ONLY); - - public static void registerItems() { - Registry.register(BuiltInRegistries.ITEM, id("long_fall_boots"), LONG_FALL_BOOTS); - Registry.register(BuiltInRegistries.ITEM, id("portal_gun"), PORTAL_GUN); - Registry.register(BuiltInRegistries.ITEM, id("portal_gun_primary"), PORTAL_GUN_PRIMARY); - Registry.register(BuiltInRegistries.ITEM, id("portal_gun_secondary"), PORTAL_GUN_SECONDARY); - - Registry.register(BuiltInRegistries.ITEM, id("paint_gun"), PAINT_GUN); - Registry.register(BuiltInRegistries.ITEM, id("portal_gun_frame"), PORTAL_GUN_FRAME); - Registry.register(BuiltInRegistries.ITEM, id("portal_gun_casing"), PORTAL_GUN_CASING); - Registry.register(BuiltInRegistries.ITEM, id("mini_blackhole"), MINI_BLACKHOLE); - Registry.register(BuiltInRegistries.ITEM, id("storage_cube"), STORAGE_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("companion_cube"), COMPANION_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("redirection_cube"), REDIRECTION_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("schrodinger_cube"), SCHRODINGER_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("old_ap_cube"), OLD_AP_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("portal_1_companion_cube"), PORTAL_1_COMPANION_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("portal_1_storage_cube"), PORTAL_1_STORAGE_CUBE); - Registry.register(BuiltInRegistries.ITEM, id("lil_pineapple"), LIL_PINEAPPLE); - - Registry.register(BuiltInRegistries.ITEM, id("radio"), RADIO); - Registry.register(BuiltInRegistries.ITEM, id("beans"), BEANS); - Registry.register(BuiltInRegistries.ITEM, id("mug"), MUG); - Registry.register(BuiltInRegistries.ITEM, id("jug"), JUG); - Registry.register(BuiltInRegistries.ITEM, id("computer"), COMPUTER); - Registry.register(BuiltInRegistries.ITEM, id("chair"), CHAIR); - Registry.register(BuiltInRegistries.ITEM, id("hoopy"), HOOPY); - Registry.register(BuiltInRegistries.ITEM, id("core_frame"), CORE_FRAME); - Registry.register(BuiltInRegistries.ITEM, id("anger_core"), ANGER_CORE); - Registry.register(BuiltInRegistries.ITEM, id("intelligence_core"), CAKE_CORE); - Registry.register(BuiltInRegistries.ITEM, id("curiosity_core"), CURIOSITY_CORE); - Registry.register(BuiltInRegistries.ITEM, id("morality_core"), MORALITY_CORE); - - Registry.register(BuiltInRegistries.ITEM, id("space_core"), SPACE_CORE); - Registry.register(BuiltInRegistries.ITEM, id("fact_core"), FACT_CORE); - Registry.register(BuiltInRegistries.ITEM, id("adventure_core"), ADVENTURE_CORE); - Registry.register(BuiltInRegistries.ITEM, id("turret"), TURRET); - - Registry.register(BuiltInRegistries.ITEM, id("block_item_icon"), BLOCK_ITEM_ICON); - - Registry.register(BuiltInRegistries.ITEM, id("hammer"), HAMMER); - Registry.register(BuiltInRegistries.ITEM, id("energy_pellet"), ENERGY_PELLET); - Registry.register(BuiltInRegistries.ITEM, id("super_pellet"), SUPER_PELLET); - Registry.register(BuiltInRegistries.ITEM, id("crowbar"), CROWBAR); - - Registry.register(BuiltInRegistries.ITEM, id("music_disc_still_alive"), STILL_ALIVE); - Registry.register(BuiltInRegistries.ITEM, id("music_disc_cara_mia_addio"), CARA_MIA_ADDIO); - Registry.register(BuiltInRegistries.ITEM, id("music_disc_want_you_gone"), WANT_YOU_GONE); - Registry.register(BuiltInRegistries.ITEM, id("music_disc_reconstructing_more_science"), RECONSTRUCTING_MORE_SCIENCE); - - DispenserBlock.registerBehavior(ENERGY_PELLET, ENERGY_PELLET.createDispenserBehavior()); - DispenserBlock.registerBehavior(SUPER_PELLET, SUPER_PELLET.createDispenserBehavior()); - } + public static final ArmorMaterial PORTAL_ARMOR = new PortalArmor(); + public static final Item LONG_FALL_BOOTS = new ArmorItem(PORTAL_ARMOR, ArmorItem.Type.BOOTS, new Item.Properties().fireResistant()); + public static final PortalGun PORTAL_GUN = new PortalGun(new QuiltItemSettings().stacksTo(1).fireResistant()); + + public static final PortalGunPrimary PORTAL_GUN_PRIMARY = new PortalGunPrimary(new QuiltItemSettings().stacksTo(1).fireResistant()); + + public static final PortalGunSecondary PORTAL_GUN_SECONDARY = new PortalGunSecondary(new QuiltItemSettings().stacksTo(1).fireResistant()); + + public static final PaintGun PAINT_GUN = new PaintGun(new QuiltItemSettings().stacksTo(1).fireResistant()); + + public static final Item PORTAL_GUN_FRAME = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); + public static final Item PORTAL_GUN_CASING = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); + public static final Item MINI_BLACKHOLE = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); + public static final Item BLOCK_ITEM_ICON = new Item(new QuiltItemSettings().stacksTo(1).fireResistant()); + public static final SpawnEggItem STORAGE_CUBE = new SpawnEggItem(PortalCubedEntities.STORAGE_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem COMPANION_CUBE = new SpawnEggItem(PortalCubedEntities.COMPANION_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem RADIO = new SpawnEggItem(PortalCubedEntities.RADIO, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem REDIRECTION_CUBE = new SpawnEggItem(PortalCubedEntities.REDIRECTION_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem SCHRODINGER_CUBE = new SpawnEggItem(PortalCubedEntities.SCHRODINGER_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem OLD_AP_CUBE = new SpawnEggItem(PortalCubedEntities.OLD_AP_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem PORTAL_1_COMPANION_CUBE = new SpawnEggItem(PortalCubedEntities.PORTAL_1_COMPANION_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem PORTAL_1_STORAGE_CUBE = new SpawnEggItem(PortalCubedEntities.PORTAL_1_STORAGE_CUBE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem LIL_PINEAPPLE = new SpawnEggItem(PortalCubedEntities.LIL_PINEAPPLE, 1, 1, new QuiltItemSettings()); + + public static final SpawnEggItem BEANS = new SpawnEggItem(PortalCubedEntities.BEANS, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem MUG = new SpawnEggItem(PortalCubedEntities.MUG, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem JUG = new SpawnEggItem(PortalCubedEntities.JUG, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem COMPUTER = new SpawnEggItem(PortalCubedEntities.COMPUTER, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem CHAIR = new SpawnEggItem(PortalCubedEntities.CHAIR, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem HOOPY = new SpawnEggItem(PortalCubedEntities.HOOPY, 1, 1, new QuiltItemSettings()); + + public static final SpawnEggItem CORE_FRAME = new SpawnEggItem(PortalCubedEntities.CORE_FRAME, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem ANGER_CORE = new SpawnEggItem(PortalCubedEntities.ANGER_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem MORALITY_CORE = new SpawnEggItem(PortalCubedEntities.MORALITY_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem CAKE_CORE = new SpawnEggItem(PortalCubedEntities.CAKE_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem CURIOSITY_CORE = new SpawnEggItem(PortalCubedEntities.CURIOSITY_CORE, 1, 1, new QuiltItemSettings()); + + public static final SpawnEggItem SPACE_CORE = new SpawnEggItem(PortalCubedEntities.SPACE_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem FACT_CORE = new SpawnEggItem(PortalCubedEntities.FACT_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem ADVENTURE_CORE = new SpawnEggItem(PortalCubedEntities.ADVENTURE_CORE, 1, 1, new QuiltItemSettings()); + public static final SpawnEggItem TURRET = new SpawnEggItem(PortalCubedEntities.TURRET, 1, 1, new QuiltItemSettings()); + + + public static final Item HAMMER = new Item(new QuiltItemSettings().stacksTo(1)); + + public static final EnergyPelletItem ENERGY_PELLET = new EnergyPelletItem(new QuiltItemSettings(), false); + public static final EnergyPelletItem SUPER_PELLET = new EnergyPelletItem(new QuiltItemSettings(), true); + + public static final CrowbarItem CROWBAR = new CrowbarItem(new QuiltItemSettings().maxCount(1)); + + public static final Item STILL_ALIVE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/still_alive")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 177); + public static final Item CARA_MIA_ADDIO = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/cara_mia_addio")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 154); + public static final Item WANT_YOU_GONE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/want_you_gone")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 142); + public static final Item RECONSTRUCTING_MORE_SCIENCE = new RecordItem(15, SoundEvent.createVariableRangeEvent(id("disc/reconstructing_more_science")), new Item.Properties().stacksTo(1).rarity(Rarity.RARE), 157); + + public static final TagKey WRENCHES = TagKey.create(Registries.ITEM, new ResourceLocation("c:wrenches")); + public static final TagKey HOLDS_OBJECT = QuiltTagKey.of(Registries.ITEM, id("holds_object"), TagType.CLIENT_ONLY); + public static final TagKey LAYS_ON_FLOOR = QuiltTagKey.of(Registries.ITEM, id("lays_on_floor"), TagType.CLIENT_ONLY); + + public static void registerItems() { + Registry.register(BuiltInRegistries.ITEM, id("long_fall_boots"), LONG_FALL_BOOTS); + Registry.register(BuiltInRegistries.ITEM, id("portal_gun"), PORTAL_GUN); + Registry.register(BuiltInRegistries.ITEM, id("portal_gun_primary"), PORTAL_GUN_PRIMARY); + Registry.register(BuiltInRegistries.ITEM, id("portal_gun_secondary"), PORTAL_GUN_SECONDARY); + + Registry.register(BuiltInRegistries.ITEM, id("paint_gun"), PAINT_GUN); + Registry.register(BuiltInRegistries.ITEM, id("portal_gun_frame"), PORTAL_GUN_FRAME); + Registry.register(BuiltInRegistries.ITEM, id("portal_gun_casing"), PORTAL_GUN_CASING); + Registry.register(BuiltInRegistries.ITEM, id("mini_blackhole"), MINI_BLACKHOLE); + Registry.register(BuiltInRegistries.ITEM, id("storage_cube"), STORAGE_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("companion_cube"), COMPANION_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("redirection_cube"), REDIRECTION_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("schrodinger_cube"), SCHRODINGER_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("old_ap_cube"), OLD_AP_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("portal_1_companion_cube"), PORTAL_1_COMPANION_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("portal_1_storage_cube"), PORTAL_1_STORAGE_CUBE); + Registry.register(BuiltInRegistries.ITEM, id("lil_pineapple"), LIL_PINEAPPLE); + + Registry.register(BuiltInRegistries.ITEM, id("radio"), RADIO); + Registry.register(BuiltInRegistries.ITEM, id("beans"), BEANS); + Registry.register(BuiltInRegistries.ITEM, id("mug"), MUG); + Registry.register(BuiltInRegistries.ITEM, id("jug"), JUG); + Registry.register(BuiltInRegistries.ITEM, id("computer"), COMPUTER); + Registry.register(BuiltInRegistries.ITEM, id("chair"), CHAIR); + Registry.register(BuiltInRegistries.ITEM, id("hoopy"), HOOPY); + Registry.register(BuiltInRegistries.ITEM, id("core_frame"), CORE_FRAME); + Registry.register(BuiltInRegistries.ITEM, id("anger_core"), ANGER_CORE); + Registry.register(BuiltInRegistries.ITEM, id("intelligence_core"), CAKE_CORE); + Registry.register(BuiltInRegistries.ITEM, id("curiosity_core"), CURIOSITY_CORE); + Registry.register(BuiltInRegistries.ITEM, id("morality_core"), MORALITY_CORE); + + Registry.register(BuiltInRegistries.ITEM, id("space_core"), SPACE_CORE); + Registry.register(BuiltInRegistries.ITEM, id("fact_core"), FACT_CORE); + Registry.register(BuiltInRegistries.ITEM, id("adventure_core"), ADVENTURE_CORE); + Registry.register(BuiltInRegistries.ITEM, id("turret"), TURRET); + + Registry.register(BuiltInRegistries.ITEM, id("block_item_icon"), BLOCK_ITEM_ICON); + + Registry.register(BuiltInRegistries.ITEM, id("hammer"), HAMMER); + Registry.register(BuiltInRegistries.ITEM, id("energy_pellet"), ENERGY_PELLET); + Registry.register(BuiltInRegistries.ITEM, id("super_pellet"), SUPER_PELLET); + Registry.register(BuiltInRegistries.ITEM, id("crowbar"), CROWBAR); + + Registry.register(BuiltInRegistries.ITEM, id("music_disc_still_alive"), STILL_ALIVE); + Registry.register(BuiltInRegistries.ITEM, id("music_disc_cara_mia_addio"), CARA_MIA_ADDIO); + Registry.register(BuiltInRegistries.ITEM, id("music_disc_want_you_gone"), WANT_YOU_GONE); + Registry.register(BuiltInRegistries.ITEM, id("music_disc_reconstructing_more_science"), RECONSTRUCTING_MORE_SCIENCE); + + DispenserBlock.registerBehavior(ENERGY_PELLET, ENERGY_PELLET.createDispenserBehavior()); + DispenserBlock.registerBehavior(SUPER_PELLET, SUPER_PELLET.createDispenserBehavior()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PortalGun.java b/src/main/java/com/fusionflux/portalcubed/items/PortalGun.java index 56628385..c97a25d6 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PortalGun.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PortalGun.java @@ -54,382 +54,382 @@ import java.util.function.BiFunction; public class PortalGun extends Item implements ClickHandlingItem, DyeableLeatherItem { - private static final Map, List>> FAIL_TRIES; - private static final Map FAIL_AXIS_DIRS = new EnumMap<>(Map.of( - Direction.AxisDirection.NEGATIVE, Math::floor, - Direction.AxisDirection.POSITIVE, Math::ceil - )); - - static { - final List>> failTryFns = List.of( - (u, r) -> List.of(r.getOpposite()), - (u, r) -> List.of(u), - (u, r) -> List.of(r), - (u, r) -> List.of(u.getOpposite()), - (u, r) -> List.of(r.getOpposite(), u), - (u, r) -> List.of(r, u), - (u, r) -> List.of(r, u.getOpposite()), - (u, r) -> List.of(r.getOpposite(), u.getOpposite()) - ); - final ImmutableMap.Builder, List>> failTries = ImmutableMap.builder(); - for (final Direction u : Direction.values()) { - for (final Direction r : Direction.values()) { - final ImmutableList.Builder> entry = ImmutableList.builder(); - for (final var fn : failTryFns) { - entry.add(fn.apply(u, r)); - } - failTries.put(Pair.of(u.getNormal(), r.getNormal()), entry.build()); - } - } - FAIL_TRIES = failTries.build(); - } - - public PortalGun(Properties settings) { - super(settings); - } - - @Override - public int getColor(ItemStack stack) { - CompoundTag compoundTag = stack.getTagElement("display"); - return compoundTag != null && compoundTag.contains("color", 99) ? compoundTag.getInt("color") : 0x1d86db; - } - - public boolean isComplementary(ItemStack stack) { - return stack.getOrCreateTag().getBoolean("complementary"); - } - - public int getSidedColor(ItemStack stack) { - final int color = getColor(stack); - return isComplementary(stack) ? 0xffffff - color + 1 : color; - } - - public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { - final int color = getColor(stack); - return rightHalf ? 0xffffff - color + 1 : color; - } - - @ClientOnly - public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { - final CompoundTag portalsTag = stack.getOrCreateTag().getCompound(level.dimension().location().toString()); - final String key = rightSide ? "RightPortal" : "LeftPortal"; - if (!portalsTag.hasUUID(key)) return false; - final UUID uuid = portalsTag.getUUID(key); - if (((LevelExt)level).getEntityByUuid(uuid) != null) { - return true; - } - final String otherKey = rightSide ? "LeftPortal" : "RightPortal"; - if (!portalsTag.hasUUID(otherKey)) return false; - final UUID otherUuid = portalsTag.getUUID(otherKey); - return ((LevelExt)level).getEntityByUuid(otherUuid) instanceof Portal portal && portal.getActive(); - } - - @Override - public InteractionResult onLeftClick(Player user, InteractionHand hand) { - shoot(user.level(), user, hand, true); - return InteractionResult.CONSUME; - } - - @Override - public InteractionResult onRightClick(Player user, InteractionHand hand) { - shoot(user.level(), user, hand, false); - return InteractionResult.CONSUME; - } - - @NotNull - @Override - public UseAnim getUseAnimation(ItemStack stack) { - return UseAnim.NONE; - } - - @Override - public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { - return false; - } - - @Override - public boolean allowNbtUpdateAnimation(Player player, InteractionHand hand, ItemStack oldStack, ItemStack newStack) { - return false; - } - - protected boolean allowLinkingToOther() { - return false; - } - - protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { - if (user.isSpectator() || PortalCubedComponents.HOLDER_COMPONENT.get(user).entityBeingHeld() != null) return; - ItemStack stack = user.getItemInHand(hand); - stack.getOrCreateTag().putBoolean("complementary", !leftClick); - if (level instanceof ServerLevel serverLevel) { - level.playSound(null, user.position().x(), user.position().y(), user.position().z(), leftClick ? PortalCubedSounds.FIRE_EVENT_PRIMARY : PortalCubedSounds.FIRE_EVENT_SECONDARY, SoundSource.NEUTRAL, .3F, 1F); - - Vec3i up; - Vec3i normal; - Vec3i right; - Vec3 blockPos; - - HitResult hitResult = customRaycast(user, 128.0D, 0.0F); - if (hitResult.getType() != HitResult.Type.BLOCK) { - level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); - return; - } - - CompoundTag tag = stack.getOrCreateTag(); - - Portal portalHolder; - Portal originalPortal; - CompoundTag portalsTag = tag.getCompound(level.dimension().location().toString()); - - if (portalsTag.contains((leftClick ? "Left" : "Right") + "Portal")) { - originalPortal = (Portal) ((ServerLevel) level).getEntity(portalsTag.getUUID((leftClick ? "Left" : "Right") + "Portal")); - } else { - originalPortal = null; - } - portalHolder = PortalCubedEntities.PORTAL.create(level); - - Portal otherPortal; - if (portalsTag.contains((leftClick ? "Right" : "Left") + "Portal")) { - otherPortal = (Portal) ((ServerLevel) level).getEntity(portalsTag.getUUID((leftClick ? "Right" : "Left") + "Portal")); - } else { - otherPortal = null; - } - - - Direction hitFace = ((BlockHitResult) hitResult).getDirection(); - Direction intoWall = hitFace.getOpposite(); - // fixme: why is this intoWall, and not hitFace? - normal = intoWall.getNormal(); - if (normal.getY() == 0) { - up = new Vec3i(0, 1, 0); - } else { - final Vec3 lookAngle = user.getLookAngle(); - up = Direction.getNearest(lookAngle.x, 0, lookAngle.z).getNormal(); - } - right = up.cross(normal); - - final int alignment = level.getGameRules().getInt(PortalCubedGameRules.PORTAL_ALIGNMENT); - if (alignment == 0) { - blockPos = hitResult.getLocation(); - } else { - blockPos = new Vec3( - Math.round(hitResult.getLocation().x * alignment) / (double) alignment, - Math.round(hitResult.getLocation().y * alignment) / (double) alignment, - Math.round(hitResult.getLocation().z * alignment) / (double) alignment - ); - } - - Vec3 portalPos1 = calcPos(blockPos, normal); - // align portal with nearest funnel - AABB funnelSearchArea = AABB.ofSize(portalPos1, 1, 1, 1) - .expandTowards(hitFace.getStepX(), hitFace.getStepY(), hitFace.getStepZ()); - List funnels = serverLevel.getEntities( - PortalCubedEntities.EXCURSION_FUNNEL, - funnel -> funnel.getBoundingBox().intersects(funnelSearchArea) && funnel.getFacing() == intoWall - ); - if (funnels.size() > 1) { // when multiple present, sort by nearest - Vec3 finalPortalPos = portalPos1; - funnels.sort(Comparator.comparingDouble(funnel -> funnel.distanceToSqr(finalPortalPos))); - } - for (ExcursionFunnelEntity funnel : funnels) { - Axis facingAxis = intoWall.getAxis(); - // align with funnel - portalPos1 = funnel.position().with(facingAxis, portalPos1.get(facingAxis)); - break; // only care about first - } - - assert portalHolder != null; - portalHolder.setDisableValidation(level.getGameRules().getBoolean(PortalCubedGameRules.DISABLE_PORTAL_VALIDATION)); - portalHolder.setOwnerUUID(Optional.of(user.getUUID())); - portalHolder.setOriginPos(portalPos1); - portalHolder.setDestination(Optional.of(portalPos1)); - - portalHolder.setRotation( - IPQuaternion.matrixToQuaternion( - Vec3.atLowerCornerOf(right), - Vec3.atLowerCornerOf(up), - Vec3.atLowerCornerOf(normal) - ).toQuaternionf() - ); - portalHolder.setColor(this.getSidedColor(stack)); - - //noinspection DataFlowIssue - final Direction.Axis hAxis = Direction.fromDelta(right.getX(), right.getY(), right.getZ()).getAxis(); - findCorrectOrientation: - if (!portalHolder.validate()) { - for (final var try_ : FAIL_TRIES.get(Pair.of(up, right))) { - Vec3 tryPos = portalPos1; - for (final Direction part : try_) { - double newAxis = FAIL_AXIS_DIRS.get(part.getAxisDirection()).get(tryPos.get(part.getAxis())); - if (part.getAxis() == hAxis) { - newAxis += part.getAxisDirection() == Direction.AxisDirection.POSITIVE ? -0.5 : 0.5; - } - tryPos = tryPos.with(part.getAxis(), newAxis); - } - portalHolder.setOriginPos(tryPos); - if (portalHolder.validate()) { - break findCorrectOrientation; - } - } - level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); - return; - } - - final List overlappingPortals = level.getEntities( - PortalCubedEntities.PORTAL, - portalHolder.getBoundingBox(), - p -> p != originalPortal && vectorsEqual(p.getNormal(), portalHolder.getNormal()) - ); - - if (!overlappingPortals.isEmpty()) { - boolean bumpSuccess = false; - if (overlappingPortals.size() == 1) { - final Portal overlappingPortal = overlappingPortals.get(0); - if (overlappingPortal.getAxisW().equals(portalHolder.getAxisW())) { - final Direction.Axis axis = Objects.requireNonNull(Direction.fromDelta(right.getX(), right.getY(), right.getZ())).getAxis(); - if (overlappingPortal.getOriginPos().get(axis) < portalHolder.getOriginPos().get(axis)) { - portalHolder.setOriginPos(portalHolder.getOriginPos().with(axis, overlappingPortal.getOriginPos().get(axis) + 1)); - } else { - portalHolder.setOriginPos(portalHolder.getOriginPos().with(axis, overlappingPortal.getOriginPos().get(axis) - 1)); - } - bumpSuccess = portalHolder.validate() && level.getEntities( - PortalCubedEntities.PORTAL, - portalHolder.getBoundingBox(), - p -> p != originalPortal && vectorsEqual(p.getNormal(), portalHolder.getNormal()) - ).isEmpty(); - } - } - if (!bumpSuccess) { - level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); - return; - } - } - - if (originalPortal == null) { - portalHolder.setLinkedPortalUUID(Optional.empty()); - } else { - CalledValues.removePortals(user, originalPortal.getUUID()); - originalPortal.kill(); - } - level.addFreshEntity(portalHolder); - CalledValues.addPortals(user, portalHolder.getUUID()); - final boolean isOtherAuto = otherPortal == null; - if (isOtherAuto) { - otherPortal = getPotentialOpposite( - level, portalPos1, portalHolder, portalHolder.getColor(), allowLinkingToOther() - ).orElse(null); - } - if (otherPortal != null) { - linkPortals(portalHolder, otherPortal, 0.1f); - - portalHolder.setOwnerUUID(Optional.of(user.getUUID())); - if (!isOtherAuto) { - otherPortal.setOwnerUUID(Optional.of(user.getUUID())); - } - - CalledValues.addPortals(user, portalHolder.getUUID()); - if (!isOtherAuto) { - CalledValues.addPortals(user, otherPortal.getUUID()); - } - } - - portalsTag.putUUID((leftClick ? "Left" : "Right") + "Portal", portalHolder.getUUID()); - - tag.put(level.dimension().location().toString(), portalsTag); - portalHolder.notifyListeners(false); - portalHolder.notifyListenersOfCreation(); - // also notify the other portal to re-propagate - if (otherPortal != null) { - otherPortal.notifyListeners(false); - Portal finalOtherPortal = otherPortal; - otherPortal.forEachListeningEntity(entity -> entity.onLinkedPortalCreate(finalOtherPortal, portalHolder)); - } - } else { - final LocalPlayer localPlayer = (LocalPlayer)user; - if (localPlayer.input.getMoveVector().lengthSquared() < 0.1 && user.getXRot() >= 88.0) { - user.setDeltaMovement(0, user.getDeltaMovement().y, 0); - } - localPlayer.connection.send(new ServerboundMovePlayerPacket.Pos( - user.getX(), - user.getY(), - user.getZ(), - user.onGround() - )); - // PosRot doesn't apply yHeadRot until the next tick, but we need it applied now - ClientPlayNetworking.send(PortalCubedServerPackets.SYNC_SHOOTER_ROT, Util.make(PacketByteBufs.create(), buf -> { - buf.writeFloat(user.getXRot()); - buf.writeFloat(user.getYHeadRot()); - })); - } - } - - /** - * {@link Vec3#equals} uses {@link Double#compare} to compare axes. {@link Double#compare}, however, treats 0.0 and - * -0.0 as not equal. - */ - private static boolean vectorsEqual(Vec3 a, Vec3 b) { - return a.x() == b.x() && a.y() == b.y() && a.z() == b.z(); - } - - public static Optional getPotentialOpposite(Level world, Vec3 portalPos, @Nullable Portal ignore, int color, boolean includePlayerPortals) { - return world.getEntities( - PortalCubedEntities.PORTAL, - AABB.ofSize(portalPos, 256, 256, 256), - p -> - p != ignore && - p.getColor() == 0xffffff - color + 1 && - (includePlayerPortals || p.getOwnerUUID().isEmpty()) && - !p.getActive() - ).stream().min(Comparator.comparingDouble(p -> p.getOriginPos().distanceToSqr(portalPos))); - } - - public static void linkPortals(Portal portal1, Portal portal2, float volume) { - portal1.setDestination(Optional.of(portal2.getOriginPos())); - portal1.setOtherRotation(Optional.of(portal2.getRotation().get())); - portal1.setLinkedPortalUUID(Optional.of(portal2.getUUID())); - portal2.setDestination(Optional.of(portal1.getOriginPos())); - portal2.setOtherRotation(Optional.of(portal1.getRotation().get())); - portal2.setLinkedPortalUUID(Optional.of(portal1.getUUID())); - - portal1.level().playSound(null, portal1.position().x(), portal1.position().y(), portal1.position().z(), PortalCubedSounds.ENTITY_PORTAL_OPEN, SoundSource.NEUTRAL, volume, 1F); - portal2.level().playSound(null, portal2.position().x(), portal2.position().y(), portal2.position().z(), PortalCubedSounds.ENTITY_PORTAL_OPEN, SoundSource.NEUTRAL, volume, 1F); - } - - /** - * @param hit the position designated by the player's input for a given portal. - * @param facing the facing axial vector of the portal based on placement context. - * @return a vector position specifying the portal's final position in the world. - */ - private Vec3 calcPos(Vec3 hit, Vec3i facing) { - double faceOffset = -Portal.SURFACE_OFFSET; - return new Vec3( - ((hit.x()) + faceOffset * facing.getX()), // x component - ((hit.y()) + faceOffset * facing.getY()), // y component - ((hit.z()) + faceOffset * facing.getZ()) // z component - ); - } - - public HitResult customRaycast(Entity user, double maxDistance, float tickDelta) { - final Vec3 start = user.getEyePosition(tickDelta); - final Vec3 rotation = user.getViewVector(tickDelta); - final Vec3 end = start.add(rotation.x * maxDistance, rotation.y * maxDistance, rotation.z * maxDistance); - final Level level = user.level(); - final CollisionContext shapeContext = CollisionContext.of(user); - return BlockGetter.traverseBlocks( - start, end, null, - (context, pos) -> { - final BlockState block = level.getBlockState(pos); - if (block.is(PortalCubedBlocks.PORTAL_NONSOLID)) { - return null; - } - final VoxelShape blockShape = block.is(PortalCubedBlocks.PORTAL_SOLID) - ? block.getShape(level, pos, shapeContext) - : block.getCollisionShape(level, pos, shapeContext); - return level.clipWithInteractionOverride(start, end, pos, blockShape, block); - }, - context -> { - final Vec3 offset = start.subtract(end); - return BlockHitResult.miss(end, Direction.getNearest(offset.x, offset.y, offset.z), BlockPos.containing(end)); - } - ); - } + private static final Map, List>> FAIL_TRIES; + private static final Map FAIL_AXIS_DIRS = new EnumMap<>(Map.of( + Direction.AxisDirection.NEGATIVE, Math::floor, + Direction.AxisDirection.POSITIVE, Math::ceil + )); + + static { + final List>> failTryFns = List.of( + (u, r) -> List.of(r.getOpposite()), + (u, r) -> List.of(u), + (u, r) -> List.of(r), + (u, r) -> List.of(u.getOpposite()), + (u, r) -> List.of(r.getOpposite(), u), + (u, r) -> List.of(r, u), + (u, r) -> List.of(r, u.getOpposite()), + (u, r) -> List.of(r.getOpposite(), u.getOpposite()) + ); + final ImmutableMap.Builder, List>> failTries = ImmutableMap.builder(); + for (final Direction u : Direction.values()) { + for (final Direction r : Direction.values()) { + final ImmutableList.Builder> entry = ImmutableList.builder(); + for (final var fn : failTryFns) { + entry.add(fn.apply(u, r)); + } + failTries.put(Pair.of(u.getNormal(), r.getNormal()), entry.build()); + } + } + FAIL_TRIES = failTries.build(); + } + + public PortalGun(Properties settings) { + super(settings); + } + + @Override + public int getColor(ItemStack stack) { + CompoundTag compoundTag = stack.getTagElement("display"); + return compoundTag != null && compoundTag.contains("color", 99) ? compoundTag.getInt("color") : 0x1d86db; + } + + public boolean isComplementary(ItemStack stack) { + return stack.getOrCreateTag().getBoolean("complementary"); + } + + public int getSidedColor(ItemStack stack) { + final int color = getColor(stack); + return isComplementary(stack) ? 0xffffff - color + 1 : color; + } + + public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { + final int color = getColor(stack); + return rightHalf ? 0xffffff - color + 1 : color; + } + + @ClientOnly + public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { + final CompoundTag portalsTag = stack.getOrCreateTag().getCompound(level.dimension().location().toString()); + final String key = rightSide ? "RightPortal" : "LeftPortal"; + if (!portalsTag.hasUUID(key)) return false; + final UUID uuid = portalsTag.getUUID(key); + if (((LevelExt)level).getEntityByUuid(uuid) != null) { + return true; + } + final String otherKey = rightSide ? "LeftPortal" : "RightPortal"; + if (!portalsTag.hasUUID(otherKey)) return false; + final UUID otherUuid = portalsTag.getUUID(otherKey); + return ((LevelExt)level).getEntityByUuid(otherUuid) instanceof Portal portal && portal.getActive(); + } + + @Override + public InteractionResult onLeftClick(Player user, InteractionHand hand) { + shoot(user.level(), user, hand, true); + return InteractionResult.CONSUME; + } + + @Override + public InteractionResult onRightClick(Player user, InteractionHand hand) { + shoot(user.level(), user, hand, false); + return InteractionResult.CONSUME; + } + + @NotNull + @Override + public UseAnim getUseAnimation(ItemStack stack) { + return UseAnim.NONE; + } + + @Override + public boolean canAttackBlock(BlockState state, Level world, BlockPos pos, Player miner) { + return false; + } + + @Override + public boolean allowNbtUpdateAnimation(Player player, InteractionHand hand, ItemStack oldStack, ItemStack newStack) { + return false; + } + + protected boolean allowLinkingToOther() { + return false; + } + + protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { + if (user.isSpectator() || PortalCubedComponents.HOLDER_COMPONENT.get(user).entityBeingHeld() != null) return; + ItemStack stack = user.getItemInHand(hand); + stack.getOrCreateTag().putBoolean("complementary", !leftClick); + if (level instanceof ServerLevel serverLevel) { + level.playSound(null, user.position().x(), user.position().y(), user.position().z(), leftClick ? PortalCubedSounds.FIRE_EVENT_PRIMARY : PortalCubedSounds.FIRE_EVENT_SECONDARY, SoundSource.NEUTRAL, .3F, 1F); + + Vec3i up; + Vec3i normal; + Vec3i right; + Vec3 blockPos; + + HitResult hitResult = customRaycast(user, 128.0D, 0.0F); + if (hitResult.getType() != HitResult.Type.BLOCK) { + level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); + return; + } + + CompoundTag tag = stack.getOrCreateTag(); + + Portal portalHolder; + Portal originalPortal; + CompoundTag portalsTag = tag.getCompound(level.dimension().location().toString()); + + if (portalsTag.contains((leftClick ? "Left" : "Right") + "Portal")) { + originalPortal = (Portal) ((ServerLevel) level).getEntity(portalsTag.getUUID((leftClick ? "Left" : "Right") + "Portal")); + } else { + originalPortal = null; + } + portalHolder = PortalCubedEntities.PORTAL.create(level); + + Portal otherPortal; + if (portalsTag.contains((leftClick ? "Right" : "Left") + "Portal")) { + otherPortal = (Portal) ((ServerLevel) level).getEntity(portalsTag.getUUID((leftClick ? "Right" : "Left") + "Portal")); + } else { + otherPortal = null; + } + + + Direction hitFace = ((BlockHitResult) hitResult).getDirection(); + Direction intoWall = hitFace.getOpposite(); + // fixme: why is this intoWall, and not hitFace? + normal = intoWall.getNormal(); + if (normal.getY() == 0) { + up = new Vec3i(0, 1, 0); + } else { + final Vec3 lookAngle = user.getLookAngle(); + up = Direction.getNearest(lookAngle.x, 0, lookAngle.z).getNormal(); + } + right = up.cross(normal); + + final int alignment = level.getGameRules().getInt(PortalCubedGameRules.PORTAL_ALIGNMENT); + if (alignment == 0) { + blockPos = hitResult.getLocation(); + } else { + blockPos = new Vec3( + Math.round(hitResult.getLocation().x * alignment) / (double) alignment, + Math.round(hitResult.getLocation().y * alignment) / (double) alignment, + Math.round(hitResult.getLocation().z * alignment) / (double) alignment + ); + } + + Vec3 portalPos1 = calcPos(blockPos, normal); + // align portal with nearest funnel + AABB funnelSearchArea = AABB.ofSize(portalPos1, 1, 1, 1) + .expandTowards(hitFace.getStepX(), hitFace.getStepY(), hitFace.getStepZ()); + List funnels = serverLevel.getEntities( + PortalCubedEntities.EXCURSION_FUNNEL, + funnel -> funnel.getBoundingBox().intersects(funnelSearchArea) && funnel.getFacing() == intoWall + ); + if (funnels.size() > 1) { // when multiple present, sort by nearest + Vec3 finalPortalPos = portalPos1; + funnels.sort(Comparator.comparingDouble(funnel -> funnel.distanceToSqr(finalPortalPos))); + } + for (ExcursionFunnelEntity funnel : funnels) { + Axis facingAxis = intoWall.getAxis(); + // align with funnel + portalPos1 = funnel.position().with(facingAxis, portalPos1.get(facingAxis)); + break; // only care about first + } + + assert portalHolder != null; + portalHolder.setDisableValidation(level.getGameRules().getBoolean(PortalCubedGameRules.DISABLE_PORTAL_VALIDATION)); + portalHolder.setOwnerUUID(Optional.of(user.getUUID())); + portalHolder.setOriginPos(portalPos1); + portalHolder.setDestination(Optional.of(portalPos1)); + + portalHolder.setRotation( + IPQuaternion.matrixToQuaternion( + Vec3.atLowerCornerOf(right), + Vec3.atLowerCornerOf(up), + Vec3.atLowerCornerOf(normal) + ).toQuaternionf() + ); + portalHolder.setColor(this.getSidedColor(stack)); + + //noinspection DataFlowIssue + final Direction.Axis hAxis = Direction.fromDelta(right.getX(), right.getY(), right.getZ()).getAxis(); + findCorrectOrientation: + if (!portalHolder.validate()) { + for (final var try_ : FAIL_TRIES.get(Pair.of(up, right))) { + Vec3 tryPos = portalPos1; + for (final Direction part : try_) { + double newAxis = FAIL_AXIS_DIRS.get(part.getAxisDirection()).get(tryPos.get(part.getAxis())); + if (part.getAxis() == hAxis) { + newAxis += part.getAxisDirection() == Direction.AxisDirection.POSITIVE ? -0.5 : 0.5; + } + tryPos = tryPos.with(part.getAxis(), newAxis); + } + portalHolder.setOriginPos(tryPos); + if (portalHolder.validate()) { + break findCorrectOrientation; + } + } + level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); + return; + } + + final List overlappingPortals = level.getEntities( + PortalCubedEntities.PORTAL, + portalHolder.getBoundingBox(), + p -> p != originalPortal && vectorsEqual(p.getNormal(), portalHolder.getNormal()) + ); + + if (!overlappingPortals.isEmpty()) { + boolean bumpSuccess = false; + if (overlappingPortals.size() == 1) { + final Portal overlappingPortal = overlappingPortals.get(0); + if (overlappingPortal.getAxisW().equals(portalHolder.getAxisW())) { + final Direction.Axis axis = Objects.requireNonNull(Direction.fromDelta(right.getX(), right.getY(), right.getZ())).getAxis(); + if (overlappingPortal.getOriginPos().get(axis) < portalHolder.getOriginPos().get(axis)) { + portalHolder.setOriginPos(portalHolder.getOriginPos().with(axis, overlappingPortal.getOriginPos().get(axis) + 1)); + } else { + portalHolder.setOriginPos(portalHolder.getOriginPos().with(axis, overlappingPortal.getOriginPos().get(axis) - 1)); + } + bumpSuccess = portalHolder.validate() && level.getEntities( + PortalCubedEntities.PORTAL, + portalHolder.getBoundingBox(), + p -> p != originalPortal && vectorsEqual(p.getNormal(), portalHolder.getNormal()) + ).isEmpty(); + } + } + if (!bumpSuccess) { + level.playSound(null, user.position().x(), user.position().y(), user.position().z(), PortalCubedSounds.INVALID_PORTAL_EVENT, SoundSource.NEUTRAL, 1F, 1F); + return; + } + } + + if (originalPortal == null) { + portalHolder.setLinkedPortalUUID(Optional.empty()); + } else { + CalledValues.removePortals(user, originalPortal.getUUID()); + originalPortal.kill(); + } + level.addFreshEntity(portalHolder); + CalledValues.addPortals(user, portalHolder.getUUID()); + final boolean isOtherAuto = otherPortal == null; + if (isOtherAuto) { + otherPortal = getPotentialOpposite( + level, portalPos1, portalHolder, portalHolder.getColor(), allowLinkingToOther() + ).orElse(null); + } + if (otherPortal != null) { + linkPortals(portalHolder, otherPortal, 0.1f); + + portalHolder.setOwnerUUID(Optional.of(user.getUUID())); + if (!isOtherAuto) { + otherPortal.setOwnerUUID(Optional.of(user.getUUID())); + } + + CalledValues.addPortals(user, portalHolder.getUUID()); + if (!isOtherAuto) { + CalledValues.addPortals(user, otherPortal.getUUID()); + } + } + + portalsTag.putUUID((leftClick ? "Left" : "Right") + "Portal", portalHolder.getUUID()); + + tag.put(level.dimension().location().toString(), portalsTag); + portalHolder.notifyListeners(false); + portalHolder.notifyListenersOfCreation(); + // also notify the other portal to re-propagate + if (otherPortal != null) { + otherPortal.notifyListeners(false); + Portal finalOtherPortal = otherPortal; + otherPortal.forEachListeningEntity(entity -> entity.onLinkedPortalCreate(finalOtherPortal, portalHolder)); + } + } else { + final LocalPlayer localPlayer = (LocalPlayer)user; + if (localPlayer.input.getMoveVector().lengthSquared() < 0.1 && user.getXRot() >= 88.0) { + user.setDeltaMovement(0, user.getDeltaMovement().y, 0); + } + localPlayer.connection.send(new ServerboundMovePlayerPacket.Pos( + user.getX(), + user.getY(), + user.getZ(), + user.onGround() + )); + // PosRot doesn't apply yHeadRot until the next tick, but we need it applied now + ClientPlayNetworking.send(PortalCubedServerPackets.SYNC_SHOOTER_ROT, Util.make(PacketByteBufs.create(), buf -> { + buf.writeFloat(user.getXRot()); + buf.writeFloat(user.getYHeadRot()); + })); + } + } + + /** + * {@link Vec3#equals} uses {@link Double#compare} to compare axes. {@link Double#compare}, however, treats 0.0 and + * -0.0 as not equal. + */ + private static boolean vectorsEqual(Vec3 a, Vec3 b) { + return a.x() == b.x() && a.y() == b.y() && a.z() == b.z(); + } + + public static Optional getPotentialOpposite(Level world, Vec3 portalPos, @Nullable Portal ignore, int color, boolean includePlayerPortals) { + return world.getEntities( + PortalCubedEntities.PORTAL, + AABB.ofSize(portalPos, 256, 256, 256), + p -> + p != ignore && + p.getColor() == 0xffffff - color + 1 && + (includePlayerPortals || p.getOwnerUUID().isEmpty()) && + !p.getActive() + ).stream().min(Comparator.comparingDouble(p -> p.getOriginPos().distanceToSqr(portalPos))); + } + + public static void linkPortals(Portal portal1, Portal portal2, float volume) { + portal1.setDestination(Optional.of(portal2.getOriginPos())); + portal1.setOtherRotation(Optional.of(portal2.getRotation().get())); + portal1.setLinkedPortalUUID(Optional.of(portal2.getUUID())); + portal2.setDestination(Optional.of(portal1.getOriginPos())); + portal2.setOtherRotation(Optional.of(portal1.getRotation().get())); + portal2.setLinkedPortalUUID(Optional.of(portal1.getUUID())); + + portal1.level().playSound(null, portal1.position().x(), portal1.position().y(), portal1.position().z(), PortalCubedSounds.ENTITY_PORTAL_OPEN, SoundSource.NEUTRAL, volume, 1F); + portal2.level().playSound(null, portal2.position().x(), portal2.position().y(), portal2.position().z(), PortalCubedSounds.ENTITY_PORTAL_OPEN, SoundSource.NEUTRAL, volume, 1F); + } + + /** + * @param hit the position designated by the player's input for a given portal. + * @param facing the facing axial vector of the portal based on placement context. + * @return a vector position specifying the portal's final position in the world. + */ + private Vec3 calcPos(Vec3 hit, Vec3i facing) { + double faceOffset = -Portal.SURFACE_OFFSET; + return new Vec3( + ((hit.x()) + faceOffset * facing.getX()), // x component + ((hit.y()) + faceOffset * facing.getY()), // y component + ((hit.z()) + faceOffset * facing.getZ()) // z component + ); + } + + public HitResult customRaycast(Entity user, double maxDistance, float tickDelta) { + final Vec3 start = user.getEyePosition(tickDelta); + final Vec3 rotation = user.getViewVector(tickDelta); + final Vec3 end = start.add(rotation.x * maxDistance, rotation.y * maxDistance, rotation.z * maxDistance); + final Level level = user.level(); + final CollisionContext shapeContext = CollisionContext.of(user); + return BlockGetter.traverseBlocks( + start, end, null, + (context, pos) -> { + final BlockState block = level.getBlockState(pos); + if (block.is(PortalCubedBlocks.PORTAL_NONSOLID)) { + return null; + } + final VoxelShape blockShape = block.is(PortalCubedBlocks.PORTAL_SOLID) + ? block.getShape(level, pos, shapeContext) + : block.getCollisionShape(level, pos, shapeContext); + return level.clipWithInteractionOverride(start, end, pos, blockShape, block); + }, + context -> { + final Vec3 offset = start.subtract(end); + return BlockHitResult.miss(end, Direction.getNearest(offset.x, offset.y, offset.z), BlockPos.containing(end)); + } + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PortalGunPrimary.java b/src/main/java/com/fusionflux/portalcubed/items/PortalGunPrimary.java index c48b9f99..55db0ab5 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PortalGunPrimary.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PortalGunPrimary.java @@ -10,33 +10,33 @@ public class PortalGunPrimary extends PortalGun { - public PortalGunPrimary(Properties settings) { - super(settings); - } - - @Override - protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { - super.shoot(level, user, hand, true); - } - - @Override - public boolean isComplementary(ItemStack stack) { - return false; - } - - @Override - public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { - return super.getColorForHudHalf(stack, false); - } - - @Override - @ClientOnly - public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { - return super.isSideActive(level, stack, false); - } - - @Override - protected boolean allowLinkingToOther() { - return true; - } + public PortalGunPrimary(Properties settings) { + super(settings); + } + + @Override + protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { + super.shoot(level, user, hand, true); + } + + @Override + public boolean isComplementary(ItemStack stack) { + return false; + } + + @Override + public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { + return super.getColorForHudHalf(stack, false); + } + + @Override + @ClientOnly + public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { + return super.isSideActive(level, stack, false); + } + + @Override + protected boolean allowLinkingToOther() { + return true; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/items/PortalGunSecondary.java b/src/main/java/com/fusionflux/portalcubed/items/PortalGunSecondary.java index c4e2c7eb..9a2717f8 100644 --- a/src/main/java/com/fusionflux/portalcubed/items/PortalGunSecondary.java +++ b/src/main/java/com/fusionflux/portalcubed/items/PortalGunSecondary.java @@ -8,33 +8,33 @@ import org.quiltmc.loader.api.minecraft.ClientOnly; public class PortalGunSecondary extends PortalGun { - public PortalGunSecondary(Properties settings) { - super(settings); - } + public PortalGunSecondary(Properties settings) { + super(settings); + } - @Override - protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { - super.shoot(level, user, hand, false); - } + @Override + protected void shoot(Level level, Player user, InteractionHand hand, boolean leftClick) { + super.shoot(level, user, hand, false); + } - @Override - public boolean isComplementary(ItemStack stack) { - return true; - } + @Override + public boolean isComplementary(ItemStack stack) { + return true; + } - @Override - public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { - return super.getColorForHudHalf(stack, true); - } + @Override + public int getColorForHudHalf(ItemStack stack, boolean rightHalf) { + return super.getColorForHudHalf(stack, true); + } - @Override - @ClientOnly - public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { - return super.isSideActive(level, stack, true); - } + @Override + @ClientOnly + public boolean isSideActive(ClientLevel level, ItemStack stack, boolean rightSide) { + return super.isSideActive(level, stack, true); + } - @Override - protected boolean allowLinkingToOther() { - return true; - } + @Override + protected boolean allowLinkingToOther() { + return true; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/listeners/NbtSyncable.java b/src/main/java/com/fusionflux/portalcubed/listeners/NbtSyncable.java index d2d7ca56..aecf25c0 100644 --- a/src/main/java/com/fusionflux/portalcubed/listeners/NbtSyncable.java +++ b/src/main/java/com/fusionflux/portalcubed/listeners/NbtSyncable.java @@ -5,5 +5,5 @@ import net.minecraft.server.level.ServerPlayer; public interface NbtSyncable { - void syncNbt(CompoundTag nbt, ServerPlayer player) throws CommandRuntimeException; + void syncNbt(CompoundTag nbt, ServerPlayer player) throws CommandRuntimeException; } diff --git a/src/main/java/com/fusionflux/portalcubed/listeners/ServerAnimatable.java b/src/main/java/com/fusionflux/portalcubed/listeners/ServerAnimatable.java index ba4ebc44..62afe315 100644 --- a/src/main/java/com/fusionflux/portalcubed/listeners/ServerAnimatable.java +++ b/src/main/java/com/fusionflux/portalcubed/listeners/ServerAnimatable.java @@ -4,8 +4,8 @@ import org.jetbrains.annotations.Nullable; public interface ServerAnimatable { - int getAge(); + int getAge(); - @Nullable - AnimationState getAnimation(String name); + @Nullable + AnimationState getAnimation(String name); } diff --git a/src/main/java/com/fusionflux/portalcubed/listeners/WentThroughPortalListener.java b/src/main/java/com/fusionflux/portalcubed/listeners/WentThroughPortalListener.java index 6eb8a37e..938ac66e 100644 --- a/src/main/java/com/fusionflux/portalcubed/listeners/WentThroughPortalListener.java +++ b/src/main/java/com/fusionflux/portalcubed/listeners/WentThroughPortalListener.java @@ -3,5 +3,5 @@ import com.fusionflux.portalcubed.entity.Portal; public interface WentThroughPortalListener { - void wentThroughPortal(Portal portal); + void wentThroughPortal(Portal portal); } diff --git a/src/main/java/com/fusionflux/portalcubed/mechanics/CrossPortalInteraction.java b/src/main/java/com/fusionflux/portalcubed/mechanics/CrossPortalInteraction.java index 43d33621..85e09584 100644 --- a/src/main/java/com/fusionflux/portalcubed/mechanics/CrossPortalInteraction.java +++ b/src/main/java/com/fusionflux/portalcubed/mechanics/CrossPortalInteraction.java @@ -15,30 +15,30 @@ public final class CrossPortalInteraction { - private CrossPortalInteraction() { } - - public static BlockHitResult blockInteractionRaycast(@NotNull Level world, @NotNull ClipContext context) { - final var result = PortalDirectionUtils.raycast(world, context); - final var finalHit = (BlockHitResult)result.finalHit(); - ((AdvancedRaycastResultHolder) finalHit).setResult(Optional.of(result)); - return finalHit; - } - - public static double interactionDistance(@NotNull Entity originEntity, @NotNull Vec3 originPos, @NotNull Vec3 endPos, @NotNull Vec3 regularInteractionPos) { - final var rays = PortalDirectionUtils.raycast(originEntity.level(), new ClipContext(originPos, endPos, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, originEntity)).rays(); - if (rays.size() > 1) { - var distance = 0.0; - for (AdvancedEntityRaycast.Result.Ray ray : rays) { - distance += ray.start().distanceTo(ray.end()); - } - distance *= distance; - return distance; - } - return Double.NEGATIVE_INFINITY; - } - - public static double interactionDistance(@NotNull Player player, double maxDistance, @NotNull Vec3 regularInteractionPos) { - return interactionDistance(player, player.getEyePosition(), player.getEyePosition().add(player.getLookAngle().scale(maxDistance)), regularInteractionPos); - } + private CrossPortalInteraction() { } + + public static BlockHitResult blockInteractionRaycast(@NotNull Level world, @NotNull ClipContext context) { + final var result = PortalDirectionUtils.raycast(world, context); + final var finalHit = (BlockHitResult)result.finalHit(); + ((AdvancedRaycastResultHolder) finalHit).setResult(Optional.of(result)); + return finalHit; + } + + public static double interactionDistance(@NotNull Entity originEntity, @NotNull Vec3 originPos, @NotNull Vec3 endPos, @NotNull Vec3 regularInteractionPos) { + final var rays = PortalDirectionUtils.raycast(originEntity.level(), new ClipContext(originPos, endPos, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, originEntity)).rays(); + if (rays.size() > 1) { + var distance = 0.0; + for (AdvancedEntityRaycast.Result.Ray ray : rays) { + distance += ray.start().distanceTo(ray.end()); + } + distance *= distance; + return distance; + } + return Double.NEGATIVE_INFINITY; + } + + public static double interactionDistance(@NotNull Player player, double maxDistance, @NotNull Vec3 regularInteractionPos) { + return interactionDistance(player, player.getEyePosition(), player.getEyePosition().add(player.getLookAngle().scale(maxDistance)), regularInteractionPos); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageSources.java b/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageSources.java index 1f850067..174c83f3 100644 --- a/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageSources.java +++ b/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageSources.java @@ -14,61 +14,61 @@ public class PortalCubedDamageSources { - private final Registry damageTypes; - - private final DamageSource acid; - private final DamageSource fizzle; - private final DamageSource vaporization; - private final DamageSource laser; - private final DamageSource cube; - - public PortalCubedDamageSources(RegistryAccess registryAccess) { - this.damageTypes = registryAccess.registryOrThrow(Registries.DAMAGE_TYPE); - acid = source(PortalCubedDamageTypes.ACID); - fizzle = source(PortalCubedDamageTypes.FIZZLE); - vaporization = source(PortalCubedDamageTypes.VAPORIZATION); - laser = source(PortalCubedDamageTypes.LASER); - cube = source(PortalCubedDamageTypes.CUBE); - } - - public static PortalCubedDamageSources pcSources(Level level) { - return ((LevelExt)level).pcDamageSources(); - } - - private DamageSource source(ResourceKey key) { - return new DamageSource(damageTypes.getHolderOrThrow(key)); - } - - private DamageSource source(ResourceKey damageTypeKey, @Nullable Entity entity) { - return new DamageSource(this.damageTypes.getHolderOrThrow(damageTypeKey), entity); - } - - private DamageSource source(ResourceKey damageTypeKey, @Nullable Entity causingEntity, @Nullable Entity directEntity) { - return new DamageSource(this.damageTypes.getHolderOrThrow(damageTypeKey), causingEntity, directEntity); - } - - public DamageSource acid() { - return acid; - } - - public DamageSource fizzle() { - return fizzle; - } - - public DamageSource vaporization() { - return vaporization; - } - - public DamageSource vaporization(EnergyPellet pellet, @Nullable Entity thrower) { - return source(PortalCubedDamageTypes.VAPORIZATION, pellet, thrower); - } - - public DamageSource laser() { - return laser; - } - - public DamageSource cube() { - return cube; - } + private final Registry damageTypes; + + private final DamageSource acid; + private final DamageSource fizzle; + private final DamageSource vaporization; + private final DamageSource laser; + private final DamageSource cube; + + public PortalCubedDamageSources(RegistryAccess registryAccess) { + this.damageTypes = registryAccess.registryOrThrow(Registries.DAMAGE_TYPE); + acid = source(PortalCubedDamageTypes.ACID); + fizzle = source(PortalCubedDamageTypes.FIZZLE); + vaporization = source(PortalCubedDamageTypes.VAPORIZATION); + laser = source(PortalCubedDamageTypes.LASER); + cube = source(PortalCubedDamageTypes.CUBE); + } + + public static PortalCubedDamageSources pcSources(Level level) { + return ((LevelExt)level).pcDamageSources(); + } + + private DamageSource source(ResourceKey key) { + return new DamageSource(damageTypes.getHolderOrThrow(key)); + } + + private DamageSource source(ResourceKey damageTypeKey, @Nullable Entity entity) { + return new DamageSource(this.damageTypes.getHolderOrThrow(damageTypeKey), entity); + } + + private DamageSource source(ResourceKey damageTypeKey, @Nullable Entity causingEntity, @Nullable Entity directEntity) { + return new DamageSource(this.damageTypes.getHolderOrThrow(damageTypeKey), causingEntity, directEntity); + } + + public DamageSource acid() { + return acid; + } + + public DamageSource fizzle() { + return fizzle; + } + + public DamageSource vaporization() { + return vaporization; + } + + public DamageSource vaporization(EnergyPellet pellet, @Nullable Entity thrower) { + return source(PortalCubedDamageTypes.VAPORIZATION, pellet, thrower); + } + + public DamageSource laser() { + return laser; + } + + public DamageSource cube() { + return cube; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageTypes.java b/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageTypes.java index ab129f28..143e827e 100644 --- a/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageTypes.java +++ b/src/main/java/com/fusionflux/portalcubed/mechanics/PortalCubedDamageTypes.java @@ -7,9 +7,9 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public interface PortalCubedDamageTypes { - ResourceKey ACID = ResourceKey.create(Registries.DAMAGE_TYPE, id("acid")); - ResourceKey FIZZLE = ResourceKey.create(Registries.DAMAGE_TYPE, id("fizzle")); - ResourceKey VAPORIZATION = ResourceKey.create(Registries.DAMAGE_TYPE, id("vaporization")); - ResourceKey LASER = ResourceKey.create(Registries.DAMAGE_TYPE, id("laser")); - ResourceKey CUBE = ResourceKey.create(Registries.DAMAGE_TYPE, id("cube")); + ResourceKey ACID = ResourceKey.create(Registries.DAMAGE_TYPE, id("acid")); + ResourceKey FIZZLE = ResourceKey.create(Registries.DAMAGE_TYPE, id("fizzle")); + ResourceKey VAPORIZATION = ResourceKey.create(Registries.DAMAGE_TYPE, id("vaporization")); + ResourceKey LASER = ResourceKey.create(Registries.DAMAGE_TYPE, id("laser")); + ResourceKey CUBE = ResourceKey.create(Registries.DAMAGE_TYPE, id("cube")); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/BlockCollisionsMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/BlockCollisionsMixin.java index e7517ef4..4d7926a6 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/BlockCollisionsMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/BlockCollisionsMixin.java @@ -14,41 +14,41 @@ @Mixin(BlockCollisions.class) public class BlockCollisionsMixin implements BlockCollisionsExt { - @Unique - private static final VoxelShape empty = Shapes.empty(); - - @Unique - private VoxelShape pc$portalCutout; - @Unique - private VoxelShape pc$crossCollision; - - @Override - @SuppressWarnings("unchecked") - public BlockCollisions setExtraShapes(VoxelShape cutout, VoxelShape crossCollision) { - pc$portalCutout = cutout; - pc$crossCollision = crossCollision; - return (BlockCollisions)(Object)this; - } - - @ModifyExpressionValue( - method = "computeNext", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;getCollisionShape(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Lnet/minecraft/world/phys/shapes/VoxelShape;" - ) - ) - private VoxelShape handlePortalCollisions(VoxelShape shape, - @Local(ordinal = 0) int x, - @Local(ordinal = 1) int y, - @Local(ordinal = 2) int z) { - - if (pc$portalCutout != null && pc$portalCutout != empty) { - shape = Shapes.joinUnoptimized(shape, pc$portalCutout.move(-x, -y, -z), BooleanOp.ONLY_FIRST); - } - if (pc$crossCollision != null && pc$portalCutout != empty) { - shape = Shapes.joinUnoptimized(shape, pc$crossCollision.move(-x, -y, -z), BooleanOp.OR); - } - - return shape; - } + @Unique + private static final VoxelShape empty = Shapes.empty(); + + @Unique + private VoxelShape pc$portalCutout; + @Unique + private VoxelShape pc$crossCollision; + + @Override + @SuppressWarnings("unchecked") + public BlockCollisions setExtraShapes(VoxelShape cutout, VoxelShape crossCollision) { + pc$portalCutout = cutout; + pc$crossCollision = crossCollision; + return (BlockCollisions)(Object)this; + } + + @ModifyExpressionValue( + method = "computeNext", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/block/state/BlockState;getCollisionShape(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Lnet/minecraft/world/phys/shapes/VoxelShape;" + ) + ) + private VoxelShape handlePortalCollisions(VoxelShape shape, + @Local(ordinal = 0) int x, + @Local(ordinal = 1) int y, + @Local(ordinal = 2) int z) { + + if (pc$portalCutout != null && pc$portalCutout != empty) { + shape = Shapes.joinUnoptimized(shape, pc$portalCutout.move(-x, -y, -z), BooleanOp.ONLY_FIRST); + } + if (pc$crossCollision != null && pc$portalCutout != empty) { + shape = Shapes.joinUnoptimized(shape, pc$crossCollision.move(-x, -y, -z), BooleanOp.OR); + } + + return shape; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/BlockHitResultMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/BlockHitResultMixin.java index 8a45cc41..b5ff9958 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/BlockHitResultMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/BlockHitResultMixin.java @@ -10,16 +10,16 @@ @Mixin(BlockHitResult.class) public abstract class BlockHitResultMixin implements AdvancedRaycastResultHolder { - @Unique - private Optional result = Optional.empty(); + @Unique + private Optional result = Optional.empty(); - @Override - public Optional getResult() { - return result; - } + @Override + public Optional getResult() { + return result; + } - @Override - public void setResult(Optional result) { - this.result = result; - } + @Override + public void setResult(Optional result) { + this.result = result; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/BlockMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/BlockMixin.java index ddf42b2a..70196c91 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/BlockMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/BlockMixin.java @@ -17,11 +17,11 @@ @Mixin(Block.class) public abstract class BlockMixin { - @Inject(method = "appendHoverText", at = @At("HEAD")) - private void portalCubedTooltip(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag, CallbackInfo ci) { - final List tooltips = PortalCubed.TOOLTIPS.get(BuiltInRegistries.BLOCK.getKey((Block)(Object)this)); - if (tooltips != null) { - tooltip.addAll(tooltips); - } - } + @Inject(method = "appendHoverText", at = @At("HEAD")) + private void portalCubedTooltip(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag, CallbackInfo ci) { + final List tooltips = PortalCubed.TOOLTIPS.get(BuiltInRegistries.BLOCK.getKey((Block)(Object)this)); + if (tooltips != null) { + tooltip.addAll(tooltips); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/BucketItemMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/BucketItemMixin.java index 919132f0..54b17a05 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/BucketItemMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/BucketItemMixin.java @@ -15,14 +15,14 @@ @Mixin(BucketItem.class) public class BucketItemMixin { - @WrapOperation( - method = "use", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/BucketPickup;getPickupSound()Ljava/util/Optional;" - ) - ) - private Optional pickupSoundWithFluid(BucketPickup instance, Operation> original, @Local BlockState blockState) { - return instance instanceof BucketPickupEx ex ? ex.getPickupSound(blockState) : original.call(instance); - } + @WrapOperation( + method = "use", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/block/BucketPickup;getPickupSound()Ljava/util/Optional;" + ) + ) + private Optional pickupSoundWithFluid(BucketPickup instance, Operation> original, @Local BlockState blockState) { + return instance instanceof BucketPickupEx ex ? ex.getPickupSound(blockState) : original.call(instance); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/ClipContextAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/ClipContextAccessor.java index 23f7946f..e89c8720 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/ClipContextAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/ClipContextAccessor.java @@ -7,12 +7,12 @@ @Mixin(ClipContext.class) public interface ClipContextAccessor { - @Accessor - ClipContext.Block getBlock(); + @Accessor + ClipContext.Block getBlock(); - @Accessor - ClipContext.Fluid getFluid(); + @Accessor + ClipContext.Fluid getFluid(); - @Accessor - CollisionContext getCollisionContext(); + @Accessor + CollisionContext getCollisionContext(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/CollisionContextMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/CollisionContextMixin.java index e7ad9ebc..c3a76645 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/CollisionContextMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/CollisionContextMixin.java @@ -9,10 +9,10 @@ @Mixin(CollisionContext.class) public interface CollisionContextMixin { - @Inject(method = "of", at = @At("HEAD"), cancellable = true) - private static void ofNullable(Entity entity, CallbackInfoReturnable cir) { - if (entity == null) { - cir.setReturnValue(CollisionContext.empty()); - } - } + @Inject(method = "of", at = @At("HEAD"), cancellable = true) + private static void ofNullable(Entity entity, CallbackInfoReturnable cir) { + if (entity == null) { + cir.setReturnValue(CollisionContext.empty()); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/CollisionGetterMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/CollisionGetterMixin.java index f6c517cf..06956711 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/CollisionGetterMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/CollisionGetterMixin.java @@ -14,30 +14,30 @@ @Mixin(CollisionGetter.class) public interface CollisionGetterMixin { - @ModifyReturnValue( - method = "getBlockCollisions", - at = @At("RETURN") - ) - @SuppressWarnings("unchecked") - default Iterable supportCutout(Iterable original, @Local Entity entity) { - if (entity == null) { - return original; - } - final VoxelShape cutout = CalledValues.getPortalCutout(entity); - final VoxelShape crossCollision = CalledValues.getCrossPortalCollision(entity); - return () -> ((BlockCollisionsExt)original.iterator()).setExtraShapes(cutout, crossCollision); - } + @ModifyReturnValue( + method = "getBlockCollisions", + at = @At("RETURN") + ) + @SuppressWarnings("unchecked") + default Iterable supportCutout(Iterable original, @Local Entity entity) { + if (entity == null) { + return original; + } + final VoxelShape cutout = CalledValues.getPortalCutout(entity); + final VoxelShape crossCollision = CalledValues.getCrossPortalCollision(entity); + return () -> ((BlockCollisionsExt)original.iterator()).setExtraShapes(cutout, crossCollision); + } - @ModifyVariable( - method = "collidesWithSuffocatingBlock", - at = @At("STORE"), - ordinal = 0 - ) - @SuppressWarnings({"InvalidInjectorMethodSignature", "unchecked"}) - default BlockCollisions supportCutout(BlockCollisions value, @Local Entity entity) { - return ((BlockCollisionsExt)value).setExtraShapes( - CalledValues.getPortalCutout(entity), - CalledValues.getCrossPortalCollision(entity) - ); - } + @ModifyVariable( + method = "collidesWithSuffocatingBlock", + at = @At("STORE"), + ordinal = 0 + ) + @SuppressWarnings({"InvalidInjectorMethodSignature", "unchecked"}) + default BlockCollisions supportCutout(BlockCollisions value, @Local Entity entity) { + return ((BlockCollisionsExt)value).setExtraShapes( + CalledValues.getPortalCutout(entity), + CalledValues.getCrossPortalCollision(entity) + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/CreativeModeTabsAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/CreativeModeTabsAccessor.java index f8911d8e..8d85be23 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/CreativeModeTabsAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/CreativeModeTabsAccessor.java @@ -7,9 +7,9 @@ @Mixin(CreativeModeTabs.class) public interface CreativeModeTabsAccessor { - @Accessor - @SuppressWarnings("checkstyle:MethodName") - static void setCACHED_PARAMETERS(CreativeModeTab.ItemDisplayParameters cache) { - throw new AssertionError(); - } + @Accessor + @SuppressWarnings("checkstyle:MethodName") + static void setCACHED_PARAMETERS(CreativeModeTab.ItemDisplayParameters cache) { + throw new AssertionError(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/DispenserBlockAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/DispenserBlockAccessor.java index 9272abae..1ef23074 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/DispenserBlockAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/DispenserBlockAccessor.java @@ -8,6 +8,6 @@ @Mixin(DispenserBlock.class) public interface DispenserBlockAccessor { - @Invoker - DispenseItemBehavior invokeGetDispenseMethod(ItemStack stack); + @Invoker + DispenseItemBehavior invokeGetDispenseMethod(ItemStack stack); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/EntityMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/EntityMixin.java index e97e90db..2200e47f 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/EntityMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/EntityMixin.java @@ -73,626 +73,626 @@ @Mixin(Entity.class) public abstract class EntityMixin implements EntityExt, EntityPortalsAccess, ClientTeleportCheck { - @Unique - private double maxFallSpeed = 0; + @Unique + private double maxFallSpeed = 0; - @Unique - private boolean inFunnel = false; + @Unique + private boolean inFunnel = false; - @Unique - private double maxFallHeight = -99999999; + @Unique + private double maxFallHeight = -99999999; - @Unique - private Direction prevGravDirec = Direction.DOWN; + @Unique + private Direction prevGravDirec = Direction.DOWN; - @Unique - private Vec3 lastVel = Vec3.ZERO; + @Unique + private Vec3 lastVel = Vec3.ZERO; - @Unique - private int gelTransferTimer = 0; + @Unique + private int gelTransferTimer = 0; - @Unique - private int gelTransferChangeTimer = 0; + @Unique + private int gelTransferChangeTimer = 0; - @Unique - private boolean isBounced = false; + @Unique + private boolean isBounced = false; - @Unique - private int funnelTimer = 0; + @Unique + private int funnelTimer = 0; - @Override - public double getMaxFallSpeed() { - return maxFallSpeed; - } + @Override + public double getMaxFallSpeed() { + return maxFallSpeed; + } - @Override - public void setMaxFallSpeed(double maxFallSpeed) { - this.maxFallSpeed = maxFallSpeed; - } + @Override + public void setMaxFallSpeed(double maxFallSpeed) { + this.maxFallSpeed = maxFallSpeed; + } - @Shadow - public abstract BlockPos blockPosition(); + @Shadow + public abstract BlockPos blockPosition(); - @Shadow - public abstract Vec3 getDeltaMovement(); + @Shadow + public abstract Vec3 getDeltaMovement(); - @Shadow - public abstract AABB getBoundingBox(); + @Shadow + public abstract AABB getBoundingBox(); - @Shadow - public abstract boolean equals(Object o); + @Shadow + public abstract boolean equals(Object o); - @Shadow - public abstract boolean onGround(); + @Shadow + public abstract boolean onGround(); - @Shadow - private Vec3 position; + @Shadow + private Vec3 position; - @Shadow - public abstract boolean canChangeDimensions(); + @Shadow + public abstract boolean canChangeDimensions(); - @Shadow - public abstract void setDeltaMovement(Vec3 velocity); + @Shadow + public abstract void setDeltaMovement(Vec3 velocity); - @Shadow - public abstract float getYRot(); + @Shadow + public abstract float getYRot(); - @Shadow public abstract double getY(); + @Shadow public abstract double getY(); - @Shadow public abstract int getId(); + @Shadow public abstract int getId(); - @Shadow public abstract double getX(); + @Shadow public abstract double getX(); - @Shadow public abstract double getZ(); + @Shadow public abstract double getZ(); - @Shadow public abstract float getXRot(); + @Shadow public abstract float getXRot(); - @Shadow public abstract Vec3 getPosition(float partialTicks); + @Shadow public abstract Vec3 getPosition(float partialTicks); - @Shadow public abstract Vec3 position(); + @Shadow public abstract Vec3 position(); - @Shadow public abstract Vec3 getEyePosition(); + @Shadow public abstract Vec3 getEyePosition(); - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - @Shadow public abstract boolean isEffectiveAi(); + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + @Shadow public abstract boolean isEffectiveAi(); - @Shadow public boolean hasImpulse; + @Shadow public boolean hasImpulse; - @Shadow public abstract Level level(); + @Shadow public abstract Level level(); - @Shadow private Level level; - @Unique - private final Map collidingBlocks = new HashMap<>(); - @Unique - private final Map leftBlocks = new HashMap<>(); + @Shadow private Level level; + @Unique + private final Map collidingBlocks = new HashMap<>(); + @Unique + private final Map leftBlocks = new HashMap<>(); - @Unique - private Pair portalEyeInfo; - @Unique - private Vec3 portalEyeInfoKey; - @Unique - private Pair portalEyeInfo2; - @Unique - private Vec3 portalEyeInfo2Key; + @Unique + private Pair portalEyeInfo; + @Unique + private Vec3 portalEyeInfoKey; + @Unique + private Pair portalEyeInfo2; + @Unique + private Vec3 portalEyeInfo2Key; - @Unique - private VelocityHelperBlockEntity velocityHelper; - @Unique - private long velocityHelperStartTime; - @Unique - private Vec3 velocityHelperOffset; + @Unique + private VelocityHelperBlockEntity velocityHelper; + @Unique + private long velocityHelperStartTime; + @Unique + private Vec3 velocityHelperOffset; - @Inject(method = "tick", at = @At("HEAD")) - public void tick(CallbackInfo ci) { - final ProfilerFiller profiler = level.getProfiler(); - profiler.push("portalcubed_entity"); + @Inject(method = "tick", at = @At("HEAD")) + public void tick(CallbackInfo ci) { + final ProfilerFiller profiler = level.getProfiler(); + profiler.push("portalcubed_entity"); - Entity thiz = (Entity) (Object) this; + Entity thiz = (Entity) (Object) this; - if (!(thiz instanceof Player) && !(thiz instanceof Portal) && !thiz.getType().is(PortalCubedEntities.PORTAL_BLACKLIST)) { - GeneralUtil.setupPortalShapes(thiz); - } + if (!(thiz instanceof Player) && !(thiz instanceof Portal) && !thiz.getType().is(PortalCubedEntities.PORTAL_BLACKLIST)) { + GeneralUtil.setupPortalShapes(thiz); + } - if (this.isInFunnel() && this.getFunnelTimer() != 0) { - this.setFunnelTimer(this.getFunnelTimer() - 1); - } - if (this.isInFunnel() && this.getFunnelTimer() == 0) { - RayonIntegration.INSTANCE.setNoGravity((Entity)(Object)this, false); - setInFunnel(false); - } - - - if (this.gelTransferTimer != 0) { - this.gelTransferTimer -= 1; - } - if (this.gelTransferChangeTimer != 0) { - this.gelTransferChangeTimer -= 1; - } - - if (maxFallSpeed == 10 && level().getBlockState(this.blockPosition()).getBlock() == PortalCubedBlocks.PROPULSION_GEL) { - maxFallSpeed = 10; - } else { - if (maxFallSpeed > 0) { - maxFallSpeed = maxFallSpeed - 1; - } - } - - - Vec3 rotatedPos; - rotatedPos = RotationUtil.vecWorldToPlayer(this.position, GravityChangerAPI.getGravityDirection((Entity) (Object) this)); - if (prevGravDirec != GravityChangerAPI.getGravityDirection(((Entity) (Object) this))) { - this.maxFallHeight = rotatedPos.y; - } - - if (!this.onGround()) { - if (rotatedPos.y > this.maxFallHeight) { - this.maxFallHeight = rotatedPos.y; - } - } else { - this.maxFallHeight = rotatedPos.y; - } - - this.lastVel = this.getDeltaMovement(); - - if (level().getBlockState(this.blockPosition()).getBlock() != PortalCubedBlocks.REPULSION_GEL && this.isBounced()) { - this.setBounced(false); - } - - prevGravDirec = GravityChangerAPI.getGravityDirection(((Entity) (Object) this)); - - profiler.pop(); - } - - @Inject(method = "tick", at = @At("TAIL")) - public void tickTail(CallbackInfo ci) { - Entity thisEntity = ((Entity) (Object) this); - - if (!thisEntity.level().isClientSide() && !(thisEntity instanceof Player) && !(thisEntity instanceof Portal) && !thisEntity.getType().is(PortalCubedEntities.PORTAL_BLACKLIST)) { - Vec3 entityVelocity = this.getDeltaMovement(); - - - AABB portalCheckBox = getBoundingBox(); - - portalCheckBox = portalCheckBox.expandTowards(entityVelocity.add(0, .08, 0)); - - - List list = ((Entity) (Object) this).level().getEntitiesOfClass(Portal.class, portalCheckBox); - Portal portal; - for (Portal portalCheck : list) { - portal = portalCheck; - if (this.canChangeDimensions() && portal.getActive() && !CalledValues.getHasTeleportationHappened(thisEntity) && !CalledValues.getIsTeleporting(thisEntity)) { - assert portal.getOtherNormal().isPresent(); - Direction portalFacing = portal.getFacingDirection(); - - //noinspection ConstantValue - if ((Object)this instanceof LivingEntity) { - entityVelocity = entityVelocity.add(0, .08, 0); - } - - Vec3 entityEyePos = thisEntity.getEyePosition(); - - if (portalFacing.step().x() < 0) { - if (entityEyePos.x() + entityVelocity.x >= portal.position().x() && entityVelocity.x() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - if (portalFacing.step().y() < 0) { - if (entityEyePos.y() + entityVelocity.y >= portal.position().y() && entityVelocity.y() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - if (portalFacing.step().z() < 0) { - if (entityEyePos.z() + entityVelocity.z >= portal.position().z() && entityVelocity.z() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - if (portalFacing.step().x() > 0) { - if (entityEyePos.x() + entityVelocity.x <= portal.position().x() && entityVelocity.x() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - if (portalFacing.step().y() > 0) { - if (entityEyePos.y() + entityVelocity.y <= portal.position().y() && entityVelocity.y() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - if (portalFacing.step().z() > 0) { - if (entityEyePos.z() + entityVelocity.z <= portal.position().z() && entityVelocity.z() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { - performTeleport(thisEntity, portal, entityVelocity); - break; - } - } - - } - } - } - } - - @Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("HEAD"), cancellable = true) - public void pushAwayFrom(Entity entity, CallbackInfo ci) { - if (entity instanceof CorePhysicsEntity || entity instanceof GelBlobEntity) { - ci.cancel(); - } - } - - @Unique - private void performTeleport( - Entity thisEntity, - Portal portal, - Vec3 entityVelocity - ) { - final TeleportResult result = PortalCubed.commonTeleport( - portal, - entityVelocity, - new Vec3( - (thisEntity.getEyePosition().x()) - portal.position().x(), - (thisEntity.getEyePosition().y()) - portal.position().y(), - (thisEntity.getEyePosition().z()) - portal.position().z() - ), - Vec3.ZERO, - thisEntity, - Optional.empty(), - thisEntity.getXRot(), - thisEntity.getYRot() - ); - - final Vec3 dest = result.dest(); - thisEntity.moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); - thisEntity.setDeltaMovement(result.velocity()); - GravityChangerAPI.clearGravity(thisEntity); - if (level() instanceof ServerLevel serverWorld) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeVarInt(getId()); - buf.writeDouble(getX()); - buf.writeDouble(getY()); - buf.writeDouble(getZ()); - buf.writeFloat(getYRot()); - buf.writeFloat(getXRot()); - final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.REFRESH_POS, buf); - for (final ServerPlayer player : serverWorld.players()) { - serverWorld.sendParticles(player, true, dest.x, dest.y, dest.z, packet); - } - } - if (this instanceof WentThroughPortalListener listener) { - listener.wentThroughPortal(portal); - } - } - - @Override - public boolean isInFunnel() { - return this.inFunnel; - } - - @Override - public void setInFunnel(boolean inFunnel) { - this.inFunnel = inFunnel; - } - - @Override - public boolean isBounced() { - return this.isBounced; - } - - @Override - public void setBounced(boolean bounced) { - this.isBounced = bounced; - } - - @Override - public int getFunnelTimer() { - - return this.funnelTimer; - } - - @Override - public double getMaxFallHeight() { - return this.maxFallHeight; - } - - - @Override - public void setMaxFallHeight(double fall) { - this.maxFallHeight = fall; - } - - @Override - public Vec3 getLastVel() { - return this.lastVel; - } - - - @Override - public void setFunnelTimer(int funnelTimer) { - this.funnelTimer = funnelTimer; - } - - @Override - public void setGelTimer(int funnelTimer) { - this.gelTransferTimer = funnelTimer; - } - - @Override - public int getGelTimer() { - return this.gelTransferTimer; - } - - @ModifyArgs( - method = "isInWall", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/AABB;ofSize(Lnet/minecraft/world/phys/Vec3;DDD)Lnet/minecraft/world/phys/AABB;" - ) - ) - private void rotateInWallCheckBB(Args args) { - getEyePosition(); - if (portalEyeInfo == null) return; - final Vec3 newBB = portalEyeInfo.second().getTransformQuat().rotate( - new Vec3(args.get(1), args.get(2), args.get(3)), false - ); - args.set(1, newBB.x); - args.set(2, newBB.y); - args.set(3, newBB.z); - } - - @ModifyArg( - method = "method_30022", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/shapes/Shapes;joinIsNotEmpty(Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/BooleanOp;)Z" - ), - index = 0 - ) - private VoxelShape cutoutForIsInWall(VoxelShape shape) { - VoxelShape portalCutout = CalledValues.getPortalCutout((Entity) (Object) this); - if (portalCutout != Shapes.empty()) { - shape = Shapes.joinUnoptimized(shape, portalCutout, BooleanOp.ONLY_FIRST); - } - VoxelShape crossPortalCollision = CalledValues.getCrossPortalCollision((Entity) (Object) this); - if (crossPortalCollision != Shapes.empty()) { - shape = Shapes.joinUnoptimized(shape, crossPortalCollision, BooleanOp.OR); - } - return shape; - } - - @ModifyArg( - method = "isColliding", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/shapes/Shapes;joinIsNotEmpty(Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/BooleanOp;)Z" - ), - index = 0 - ) - private VoxelShape cutoutForIsColliding(VoxelShape shape) { - VoxelShape portalCutout = CalledValues.getPortalCutout((Entity) (Object) this); - if (portalCutout != Shapes.empty()) { - shape = Shapes.joinUnoptimized(shape, portalCutout, BooleanOp.ONLY_FIRST); - } - VoxelShape crossPortalCollision = CalledValues.getCrossPortalCollision((Entity) (Object) this); - if (crossPortalCollision != Shapes.empty()) { - shape = Shapes.joinUnoptimized(shape, crossPortalCollision, BooleanOp.OR); - } - return shape; - } - - @Inject(method = "checkInsideBlocks", at = @At("HEAD")) - private void beginBlockCheck(CallbackInfo ci) { - leftBlocks.putAll(collidingBlocks); - } - - @WrapOperation( - method = "checkInsideBlocks", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;entityInside(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/Entity;)V" - ) - ) - private void midBlockCheck(BlockState instance, Level level, BlockPos pos, Entity entity, Operation original) { - original.call(instance, level, pos, entity); - if ( - instance.getBlock() instanceof BlockCollisionTrigger trigger && - intersects( - entity.getBoundingBox().move(pos.multiply(-1)), - trigger.getTriggerShape(instance, level, pos, CollisionContext.of(entity)) - ) - ) { - final BlockPos immutable = pos.immutable(); - if (collidingBlocks.put(instance, immutable) == null) { - trigger.onEntityEnter(instance, level, immutable, entity); - } - leftBlocks.remove(instance); - } - } - - @Inject(method = "checkInsideBlocks", at = @At("TAIL")) - private void endBlockCheck(CallbackInfo ci) { - for (final var entry : leftBlocks.entrySet()) { - if (entry.getKey().getBlock() instanceof BlockCollisionTrigger trigger) { - trigger.onEntityLeave(entry.getKey(), level(), entry.getValue(), (Entity) (Object) this); - } - collidingBlocks.remove(entry.getKey()); - } - leftBlocks.clear(); - } - - @Redirect( - method = "pick", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;clip(Lnet/minecraft/world/level/ClipContext;)Lnet/minecraft/world/phys/BlockHitResult;" - ) - ) - private BlockHitResult portalCubed$portalCompatibleRaycast(Level world, ClipContext context) { - return CrossPortalInteraction.blockInteractionRaycast(world, context); - } - - @Unique - private boolean intersects(AABB box, VoxelShape shape) { - return shape.toAabbs().stream().anyMatch(box::intersects); - } - - @Override - public boolean cfg() { - return false; - } - - @Override - public void setCFG() { - } - - @ModifyReturnValue(method = "getEyePosition()Lnet/minecraft/world/phys/Vec3;", at = @At("RETURN")) - private Vec3 transformViaPortalNoInterp(Vec3 original) { - return transformVecThroughPortal(position(), original); - } - - @ModifyReturnValue(method = "getEyePosition(F)Lnet/minecraft/world/phys/Vec3;", at = @At("RETURN")) - private Vec3 transformViaPortalInterp(Vec3 original, float tickDelta) { - return transformVecThroughPortal(getPosition(tickDelta), original); - } - - @Unique - private Vec3 transformVecThroughPortal(Vec3 base, Vec3 vec) { - final Pair eyeInfo; - if (base == portalEyeInfoKey) { - eyeInfo = portalEyeInfo; - } else if (base == portalEyeInfo2Key) { - eyeInfo = portalEyeInfo2; - } else { - portalEyeInfo2 = portalEyeInfo; - portalEyeInfo2Key = portalEyeInfoKey; - eyeInfo = portalEyeInfo = PortalDirectionUtils.simpleTransformPassingVector( - (Entity)(Object)this, - base.add(0, 0.02, 0), - vec, p -> p.getNormal().y < 0 - ); - portalEyeInfoKey = base; - } - return eyeInfo != null ? eyeInfo.first() : vec; - } - - @ModifyReturnValue(method = "calculateViewVector", at = @At("RETURN")) - private Vec3 transformViewVector(Vec3 original, float xRot, float yRot) { - getEyePosition(); - if (portalEyeInfo == null) { - return original; - } - return portalEyeInfo.second().getTransformQuat().rotate(original, false); - } - - @WrapOperation(method = "move", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;setPos(DDD)V")) - private void collideWithFizzlersOnMove(Entity self, double x, double y, double z, Operation original) { - // this is done so collision works even when moving very fast. - Vec3 pos = position(); - original.call(self, x, y, z); - Vec3 newPos = position(); - // based on ProjectileUtil - ClipContext ctx = new ClipContext(pos, newPos, Block.OUTLINE, Fluid.NONE, (Entity) (Object) this); - BlockHitResult hit = level().clip(ctx); - if (hit.getType() == Type.BLOCK) { - BlockState state = level().getBlockState(hit.getBlockPos()); - if (state.getBlock() instanceof AbstractFizzlerBlock fizzler) - fizzler.applyEffectsTo((Entity) (Object) this); - } - } - - @Override - public void collidedWithVelocityHelper(VelocityHelperBlockEntity block) { - if (!isEffectiveAi() || block.getDestination() == null) return; - if (velocityHelper != null && block.getBlockPos().equals(velocityHelper.getBlockPos())) return; - final Expression condition = block.getCondition(); - condition.setVariable("x", getDeltaMovement().x); - condition.setVariable("y", getDeltaMovement().y); - condition.setVariable("z", getDeltaMovement().z); - try { - if (condition.evaluate() == 0) return; - } catch (RuntimeException e) { - logVHWarning("condition", e); - return; - } - velocityHelper = block; - velocityHelperStartTime = level().getGameTime(); - velocityHelperOffset = Vec3.atCenterOf(block.getBlockPos()).subtract(position()); - } - - @Override - public void collidedWithCatapult(CatapultBlockEntity block) { - if (!isEffectiveAi()) return; - final double relH = block.getRelH(position().x, position().z); - final double relY = block.getRelY(position().y); - final double angle = block.getAngle(); - final double speed = GeneralUtil.calculateVelocity(relH, relY, angle, -0.08 * PehkuiApi.INSTANCE.getFallingScale((Entity)(Object)this)); - if (!Double.isFinite(speed)) return; - //noinspection ConstantValue - if ((Object)this instanceof Player player) { - player.setDiscardFriction(player.getItemBySlot(EquipmentSlot.FEET).is(PortalCubedItems.LONG_FALL_BOOTS)); - } - RayonIntegration.INSTANCE.setVelocity((Entity)(Object)this, block.getLaunchDir(position().x, position().z).scale(Math.min(speed, 10))); - hasImpulse = true; - } - - @Unique - private void logVHWarning(String type, RuntimeException e) { - //noinspection ConstantValue - if ((Object)this instanceof Player && level().isClientSide) { - logVHWarningToChat(type, e); - } - PortalCubed.LOGGER.info("{} at {}", getVHWarning(type).getString(), velocityHelper.getBlockPos(), e); - } - - @Unique - @ClientOnly - private void logVHWarningToChat(String type, RuntimeException e) { - Minecraft.getInstance().gui.getChat().addMessage(getVHWarning(type)); - Minecraft.getInstance().gui.getChat().addMessage( - Component.literal(ExpressionFieldWidget.cleanError(e)).withStyle(ChatFormatting.RED) - ); - } - - @Unique - private Component getVHWarning(String type) { - return Component.translatable( - "portalcubed.velocity_helper.failed_expression", - Component.translatable("portalcubed.velocity_helper." + type + "_expression") - ).withStyle(ChatFormatting.RED); - } - - @Inject(method = "tick", at = @At("TAIL")) - private void tickVelocityHelper(CallbackInfo ci) { - if (velocityHelper == null || velocityHelper.getDestination() == null) { - velocityHelper = null; - return; - } - double progress = (level().getGameTime() - velocityHelperStartTime) / (double)velocityHelper.getFlightDuration(); - if (progress >= 1.0) { - velocityHelper = null; - return; - } - if (progress < 0) { - progress = 0; - } - final Expression curve = velocityHelper.getInterpolationCurve(); - curve.setVariable("x", progress); - final double useProgress; - try { - useProgress = Mth.clamp(curve.evaluate(), 0, 1); - } catch (RuntimeException e) { - logVHWarning("curve", e); - return; - } - assert velocityHelper.getDestination() != null; - setDeltaMovement(new Vec3( - Mth.lerp(useProgress, velocityHelper.getBlockPos().getX() + 0.5, velocityHelper.getDestination().getX() + 0.5), - Mth.lerp(useProgress, velocityHelper.getBlockPos().getY() + 0.5, velocityHelper.getDestination().getY() + 0.5), - Mth.lerp(useProgress, velocityHelper.getBlockPos().getZ() + 0.5, velocityHelper.getDestination().getZ() + 0.5) - ).subtract(position()).subtract(velocityHelperOffset)); - } - - @Inject(method = "resetFallDistance", at = @At("HEAD")) - private void resetLauncher(CallbackInfo ci) { - PortalCubedComponents.ENTITY_COMPONENT.get(this).setLauncher(null); - } + if (this.isInFunnel() && this.getFunnelTimer() != 0) { + this.setFunnelTimer(this.getFunnelTimer() - 1); + } + if (this.isInFunnel() && this.getFunnelTimer() == 0) { + RayonIntegration.INSTANCE.setNoGravity((Entity)(Object)this, false); + setInFunnel(false); + } + + + if (this.gelTransferTimer != 0) { + this.gelTransferTimer -= 1; + } + if (this.gelTransferChangeTimer != 0) { + this.gelTransferChangeTimer -= 1; + } + + if (maxFallSpeed == 10 && level().getBlockState(this.blockPosition()).getBlock() == PortalCubedBlocks.PROPULSION_GEL) { + maxFallSpeed = 10; + } else { + if (maxFallSpeed > 0) { + maxFallSpeed = maxFallSpeed - 1; + } + } + + + Vec3 rotatedPos; + rotatedPos = RotationUtil.vecWorldToPlayer(this.position, GravityChangerAPI.getGravityDirection((Entity) (Object) this)); + if (prevGravDirec != GravityChangerAPI.getGravityDirection(((Entity) (Object) this))) { + this.maxFallHeight = rotatedPos.y; + } + + if (!this.onGround()) { + if (rotatedPos.y > this.maxFallHeight) { + this.maxFallHeight = rotatedPos.y; + } + } else { + this.maxFallHeight = rotatedPos.y; + } + + this.lastVel = this.getDeltaMovement(); + + if (level().getBlockState(this.blockPosition()).getBlock() != PortalCubedBlocks.REPULSION_GEL && this.isBounced()) { + this.setBounced(false); + } + + prevGravDirec = GravityChangerAPI.getGravityDirection(((Entity) (Object) this)); + + profiler.pop(); + } + + @Inject(method = "tick", at = @At("TAIL")) + public void tickTail(CallbackInfo ci) { + Entity thisEntity = ((Entity) (Object) this); + + if (!thisEntity.level().isClientSide() && !(thisEntity instanceof Player) && !(thisEntity instanceof Portal) && !thisEntity.getType().is(PortalCubedEntities.PORTAL_BLACKLIST)) { + Vec3 entityVelocity = this.getDeltaMovement(); + + + AABB portalCheckBox = getBoundingBox(); + + portalCheckBox = portalCheckBox.expandTowards(entityVelocity.add(0, .08, 0)); + + + List list = ((Entity) (Object) this).level().getEntitiesOfClass(Portal.class, portalCheckBox); + Portal portal; + for (Portal portalCheck : list) { + portal = portalCheck; + if (this.canChangeDimensions() && portal.getActive() && !CalledValues.getHasTeleportationHappened(thisEntity) && !CalledValues.getIsTeleporting(thisEntity)) { + assert portal.getOtherNormal().isPresent(); + Direction portalFacing = portal.getFacingDirection(); + + //noinspection ConstantValue + if ((Object)this instanceof LivingEntity) { + entityVelocity = entityVelocity.add(0, .08, 0); + } + + Vec3 entityEyePos = thisEntity.getEyePosition(); + + if (portalFacing.step().x() < 0) { + if (entityEyePos.x() + entityVelocity.x >= portal.position().x() && entityVelocity.x() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + if (portalFacing.step().y() < 0) { + if (entityEyePos.y() + entityVelocity.y >= portal.position().y() && entityVelocity.y() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + if (portalFacing.step().z() < 0) { + if (entityEyePos.z() + entityVelocity.z >= portal.position().z() && entityVelocity.z() > 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + if (portalFacing.step().x() > 0) { + if (entityEyePos.x() + entityVelocity.x <= portal.position().x() && entityVelocity.x() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + if (portalFacing.step().y() > 0) { + if (entityEyePos.y() + entityVelocity.y <= portal.position().y() && entityVelocity.y() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + if (portalFacing.step().z() > 0) { + if (entityEyePos.z() + entityVelocity.z <= portal.position().z() && entityVelocity.z() < 0 && portal.calculateBoundsCheckBox().intersects(thisEntity.getBoundingBox())) { + performTeleport(thisEntity, portal, entityVelocity); + break; + } + } + + } + } + } + } + + @Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("HEAD"), cancellable = true) + public void pushAwayFrom(Entity entity, CallbackInfo ci) { + if (entity instanceof CorePhysicsEntity || entity instanceof GelBlobEntity) { + ci.cancel(); + } + } + + @Unique + private void performTeleport( + Entity thisEntity, + Portal portal, + Vec3 entityVelocity + ) { + final TeleportResult result = PortalCubed.commonTeleport( + portal, + entityVelocity, + new Vec3( + (thisEntity.getEyePosition().x()) - portal.position().x(), + (thisEntity.getEyePosition().y()) - portal.position().y(), + (thisEntity.getEyePosition().z()) - portal.position().z() + ), + Vec3.ZERO, + thisEntity, + Optional.empty(), + thisEntity.getXRot(), + thisEntity.getYRot() + ); + + final Vec3 dest = result.dest(); + thisEntity.moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); + thisEntity.setDeltaMovement(result.velocity()); + GravityChangerAPI.clearGravity(thisEntity); + if (level() instanceof ServerLevel serverWorld) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeVarInt(getId()); + buf.writeDouble(getX()); + buf.writeDouble(getY()); + buf.writeDouble(getZ()); + buf.writeFloat(getYRot()); + buf.writeFloat(getXRot()); + final Packet packet = ServerPlayNetworking.createS2CPacket(PortalCubedClientPackets.REFRESH_POS, buf); + for (final ServerPlayer player : serverWorld.players()) { + serverWorld.sendParticles(player, true, dest.x, dest.y, dest.z, packet); + } + } + if (this instanceof WentThroughPortalListener listener) { + listener.wentThroughPortal(portal); + } + } + + @Override + public boolean isInFunnel() { + return this.inFunnel; + } + + @Override + public void setInFunnel(boolean inFunnel) { + this.inFunnel = inFunnel; + } + + @Override + public boolean isBounced() { + return this.isBounced; + } + + @Override + public void setBounced(boolean bounced) { + this.isBounced = bounced; + } + + @Override + public int getFunnelTimer() { + + return this.funnelTimer; + } + + @Override + public double getMaxFallHeight() { + return this.maxFallHeight; + } + + + @Override + public void setMaxFallHeight(double fall) { + this.maxFallHeight = fall; + } + + @Override + public Vec3 getLastVel() { + return this.lastVel; + } + + + @Override + public void setFunnelTimer(int funnelTimer) { + this.funnelTimer = funnelTimer; + } + + @Override + public void setGelTimer(int funnelTimer) { + this.gelTransferTimer = funnelTimer; + } + + @Override + public int getGelTimer() { + return this.gelTransferTimer; + } + + @ModifyArgs( + method = "isInWall", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/AABB;ofSize(Lnet/minecraft/world/phys/Vec3;DDD)Lnet/minecraft/world/phys/AABB;" + ) + ) + private void rotateInWallCheckBB(Args args) { + getEyePosition(); + if (portalEyeInfo == null) return; + final Vec3 newBB = portalEyeInfo.second().getTransformQuat().rotate( + new Vec3(args.get(1), args.get(2), args.get(3)), false + ); + args.set(1, newBB.x); + args.set(2, newBB.y); + args.set(3, newBB.z); + } + + @ModifyArg( + method = "method_30022", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/shapes/Shapes;joinIsNotEmpty(Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/BooleanOp;)Z" + ), + index = 0 + ) + private VoxelShape cutoutForIsInWall(VoxelShape shape) { + VoxelShape portalCutout = CalledValues.getPortalCutout((Entity) (Object) this); + if (portalCutout != Shapes.empty()) { + shape = Shapes.joinUnoptimized(shape, portalCutout, BooleanOp.ONLY_FIRST); + } + VoxelShape crossPortalCollision = CalledValues.getCrossPortalCollision((Entity) (Object) this); + if (crossPortalCollision != Shapes.empty()) { + shape = Shapes.joinUnoptimized(shape, crossPortalCollision, BooleanOp.OR); + } + return shape; + } + + @ModifyArg( + method = "isColliding", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/shapes/Shapes;joinIsNotEmpty(Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/VoxelShape;Lnet/minecraft/world/phys/shapes/BooleanOp;)Z" + ), + index = 0 + ) + private VoxelShape cutoutForIsColliding(VoxelShape shape) { + VoxelShape portalCutout = CalledValues.getPortalCutout((Entity) (Object) this); + if (portalCutout != Shapes.empty()) { + shape = Shapes.joinUnoptimized(shape, portalCutout, BooleanOp.ONLY_FIRST); + } + VoxelShape crossPortalCollision = CalledValues.getCrossPortalCollision((Entity) (Object) this); + if (crossPortalCollision != Shapes.empty()) { + shape = Shapes.joinUnoptimized(shape, crossPortalCollision, BooleanOp.OR); + } + return shape; + } + + @Inject(method = "checkInsideBlocks", at = @At("HEAD")) + private void beginBlockCheck(CallbackInfo ci) { + leftBlocks.putAll(collidingBlocks); + } + + @WrapOperation( + method = "checkInsideBlocks", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/block/state/BlockState;entityInside(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/Entity;)V" + ) + ) + private void midBlockCheck(BlockState instance, Level level, BlockPos pos, Entity entity, Operation original) { + original.call(instance, level, pos, entity); + if ( + instance.getBlock() instanceof BlockCollisionTrigger trigger && + intersects( + entity.getBoundingBox().move(pos.multiply(-1)), + trigger.getTriggerShape(instance, level, pos, CollisionContext.of(entity)) + ) + ) { + final BlockPos immutable = pos.immutable(); + if (collidingBlocks.put(instance, immutable) == null) { + trigger.onEntityEnter(instance, level, immutable, entity); + } + leftBlocks.remove(instance); + } + } + + @Inject(method = "checkInsideBlocks", at = @At("TAIL")) + private void endBlockCheck(CallbackInfo ci) { + for (final var entry : leftBlocks.entrySet()) { + if (entry.getKey().getBlock() instanceof BlockCollisionTrigger trigger) { + trigger.onEntityLeave(entry.getKey(), level(), entry.getValue(), (Entity) (Object) this); + } + collidingBlocks.remove(entry.getKey()); + } + leftBlocks.clear(); + } + + @Redirect( + method = "pick", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/Level;clip(Lnet/minecraft/world/level/ClipContext;)Lnet/minecraft/world/phys/BlockHitResult;" + ) + ) + private BlockHitResult portalCubed$portalCompatibleRaycast(Level world, ClipContext context) { + return CrossPortalInteraction.blockInteractionRaycast(world, context); + } + + @Unique + private boolean intersects(AABB box, VoxelShape shape) { + return shape.toAabbs().stream().anyMatch(box::intersects); + } + + @Override + public boolean cfg() { + return false; + } + + @Override + public void setCFG() { + } + + @ModifyReturnValue(method = "getEyePosition()Lnet/minecraft/world/phys/Vec3;", at = @At("RETURN")) + private Vec3 transformViaPortalNoInterp(Vec3 original) { + return transformVecThroughPortal(position(), original); + } + + @ModifyReturnValue(method = "getEyePosition(F)Lnet/minecraft/world/phys/Vec3;", at = @At("RETURN")) + private Vec3 transformViaPortalInterp(Vec3 original, float tickDelta) { + return transformVecThroughPortal(getPosition(tickDelta), original); + } + + @Unique + private Vec3 transformVecThroughPortal(Vec3 base, Vec3 vec) { + final Pair eyeInfo; + if (base == portalEyeInfoKey) { + eyeInfo = portalEyeInfo; + } else if (base == portalEyeInfo2Key) { + eyeInfo = portalEyeInfo2; + } else { + portalEyeInfo2 = portalEyeInfo; + portalEyeInfo2Key = portalEyeInfoKey; + eyeInfo = portalEyeInfo = PortalDirectionUtils.simpleTransformPassingVector( + (Entity)(Object)this, + base.add(0, 0.02, 0), + vec, p -> p.getNormal().y < 0 + ); + portalEyeInfoKey = base; + } + return eyeInfo != null ? eyeInfo.first() : vec; + } + + @ModifyReturnValue(method = "calculateViewVector", at = @At("RETURN")) + private Vec3 transformViewVector(Vec3 original, float xRot, float yRot) { + getEyePosition(); + if (portalEyeInfo == null) { + return original; + } + return portalEyeInfo.second().getTransformQuat().rotate(original, false); + } + + @WrapOperation(method = "move", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;setPos(DDD)V")) + private void collideWithFizzlersOnMove(Entity self, double x, double y, double z, Operation original) { + // this is done so collision works even when moving very fast. + Vec3 pos = position(); + original.call(self, x, y, z); + Vec3 newPos = position(); + // based on ProjectileUtil + ClipContext ctx = new ClipContext(pos, newPos, Block.OUTLINE, Fluid.NONE, (Entity) (Object) this); + BlockHitResult hit = level().clip(ctx); + if (hit.getType() == Type.BLOCK) { + BlockState state = level().getBlockState(hit.getBlockPos()); + if (state.getBlock() instanceof AbstractFizzlerBlock fizzler) + fizzler.applyEffectsTo((Entity) (Object) this); + } + } + + @Override + public void collidedWithVelocityHelper(VelocityHelperBlockEntity block) { + if (!isEffectiveAi() || block.getDestination() == null) return; + if (velocityHelper != null && block.getBlockPos().equals(velocityHelper.getBlockPos())) return; + final Expression condition = block.getCondition(); + condition.setVariable("x", getDeltaMovement().x); + condition.setVariable("y", getDeltaMovement().y); + condition.setVariable("z", getDeltaMovement().z); + try { + if (condition.evaluate() == 0) return; + } catch (RuntimeException e) { + logVHWarning("condition", e); + return; + } + velocityHelper = block; + velocityHelperStartTime = level().getGameTime(); + velocityHelperOffset = Vec3.atCenterOf(block.getBlockPos()).subtract(position()); + } + + @Override + public void collidedWithCatapult(CatapultBlockEntity block) { + if (!isEffectiveAi()) return; + final double relH = block.getRelH(position().x, position().z); + final double relY = block.getRelY(position().y); + final double angle = block.getAngle(); + final double speed = GeneralUtil.calculateVelocity(relH, relY, angle, -0.08 * PehkuiApi.INSTANCE.getFallingScale((Entity)(Object)this)); + if (!Double.isFinite(speed)) return; + //noinspection ConstantValue + if ((Object)this instanceof Player player) { + player.setDiscardFriction(player.getItemBySlot(EquipmentSlot.FEET).is(PortalCubedItems.LONG_FALL_BOOTS)); + } + RayonIntegration.INSTANCE.setVelocity((Entity)(Object)this, block.getLaunchDir(position().x, position().z).scale(Math.min(speed, 10))); + hasImpulse = true; + } + + @Unique + private void logVHWarning(String type, RuntimeException e) { + //noinspection ConstantValue + if ((Object)this instanceof Player && level().isClientSide) { + logVHWarningToChat(type, e); + } + PortalCubed.LOGGER.info("{} at {}", getVHWarning(type).getString(), velocityHelper.getBlockPos(), e); + } + + @Unique + @ClientOnly + private void logVHWarningToChat(String type, RuntimeException e) { + Minecraft.getInstance().gui.getChat().addMessage(getVHWarning(type)); + Minecraft.getInstance().gui.getChat().addMessage( + Component.literal(ExpressionFieldWidget.cleanError(e)).withStyle(ChatFormatting.RED) + ); + } + + @Unique + private Component getVHWarning(String type) { + return Component.translatable( + "portalcubed.velocity_helper.failed_expression", + Component.translatable("portalcubed.velocity_helper." + type + "_expression") + ).withStyle(ChatFormatting.RED); + } + + @Inject(method = "tick", at = @At("TAIL")) + private void tickVelocityHelper(CallbackInfo ci) { + if (velocityHelper == null || velocityHelper.getDestination() == null) { + velocityHelper = null; + return; + } + double progress = (level().getGameTime() - velocityHelperStartTime) / (double)velocityHelper.getFlightDuration(); + if (progress >= 1.0) { + velocityHelper = null; + return; + } + if (progress < 0) { + progress = 0; + } + final Expression curve = velocityHelper.getInterpolationCurve(); + curve.setVariable("x", progress); + final double useProgress; + try { + useProgress = Mth.clamp(curve.evaluate(), 0, 1); + } catch (RuntimeException e) { + logVHWarning("curve", e); + return; + } + assert velocityHelper.getDestination() != null; + setDeltaMovement(new Vec3( + Mth.lerp(useProgress, velocityHelper.getBlockPos().getX() + 0.5, velocityHelper.getDestination().getX() + 0.5), + Mth.lerp(useProgress, velocityHelper.getBlockPos().getY() + 0.5, velocityHelper.getDestination().getY() + 0.5), + Mth.lerp(useProgress, velocityHelper.getBlockPos().getZ() + 0.5, velocityHelper.getDestination().getZ() + 0.5) + ).subtract(position()).subtract(velocityHelperOffset)); + } + + @Inject(method = "resetFallDistance", at = @At("HEAD")) + private void resetLauncher(CallbackInfo ci) { + PortalCubedComponents.ENTITY_COMPONENT.get(this).setLauncher(null); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/EntitySubPredicate_TypesMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/EntitySubPredicate_TypesMixin.java index ec47caa0..54ab618f 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/EntitySubPredicate_TypesMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/EntitySubPredicate_TypesMixin.java @@ -14,12 +14,12 @@ @Mixin(EntitySubPredicate.Types.class) @SuppressWarnings("checkstyle:TypeName") public class EntitySubPredicate_TypesMixin { - @Shadow @Final @Mutable - @SuppressWarnings("checkstyle:StaticVariableName") - public static BiMap TYPES; + @Shadow @Final @Mutable + @SuppressWarnings("checkstyle:StaticVariableName") + public static BiMap TYPES; - @Inject(method = "", at = @At("TAIL")) - private static void makeMapMutable(CallbackInfo ci) { - TYPES = HashBiMap.create(TYPES); - } + @Inject(method = "", at = @At("TAIL")) + private static void makeMapMutable(CallbackInfo ci) { + TYPES = HashBiMap.create(TYPES); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/InventoryMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/InventoryMixin.java index e5319718..ae91d71a 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/InventoryMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/InventoryMixin.java @@ -14,32 +14,32 @@ @Mixin(Inventory.class) public class InventoryMixin { - @Shadow @Final public Player player; + @Shadow @Final public Player player; - @Inject(method = "swapPaint", at = @At("HEAD"), cancellable = true) - private void zoomInPortalMode(double scrollAmount, CallbackInfo ci) { - if (player.level().isClientSide && performZoom((int)Math.signum(scrollAmount))) { - ci.cancel(); - } - } + @Inject(method = "swapPaint", at = @At("HEAD"), cancellable = true) + private void zoomInPortalMode(double scrollAmount, CallbackInfo ci) { + if (player.level().isClientSide && performZoom((int)Math.signum(scrollAmount))) { + ci.cancel(); + } + } - @Unique - @ClientOnly - private boolean performZoom(int delta) { - if (!PortalCubedClient.isPortalHudMode()) { - return false; - } - if (delta > 0) { - if (PortalCubedClient.zoomDir == 0) { - PortalCubedClient.zoomTimer = 0; - } else if (PortalCubedClient.zoomDir < 0) { - PortalCubedClient.zoomTimer = PortalCubedClient.ZOOM_TIME - PortalCubedClient.zoomTimer; - } - PortalCubedClient.zoomDir = 1; - } else if (delta < 0 && PortalCubedClient.zoomDir > 0) { - PortalCubedClient.zoomDir = -1; - PortalCubedClient.zoomTimer = Math.max(PortalCubedClient.ZOOM_TIME - PortalCubedClient.zoomTimer, 0); - } - return true; - } + @Unique + @ClientOnly + private boolean performZoom(int delta) { + if (!PortalCubedClient.isPortalHudMode()) { + return false; + } + if (delta > 0) { + if (PortalCubedClient.zoomDir == 0) { + PortalCubedClient.zoomTimer = 0; + } else if (PortalCubedClient.zoomDir < 0) { + PortalCubedClient.zoomTimer = PortalCubedClient.ZOOM_TIME - PortalCubedClient.zoomTimer; + } + PortalCubedClient.zoomDir = 1; + } else if (delta < 0 && PortalCubedClient.zoomDir > 0) { + PortalCubedClient.zoomDir = -1; + PortalCubedClient.zoomTimer = Math.max(PortalCubedClient.ZOOM_TIME - PortalCubedClient.zoomTimer, 0); + } + return true; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/ItemMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/ItemMixin.java index 712d31d5..bc58b517 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/ItemMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/ItemMixin.java @@ -18,14 +18,14 @@ @Mixin(Item.class) public abstract class ItemMixin { - @Inject(method = "appendHoverText", at = @At("HEAD")) - private void portalCubedTooltip(ItemStack stack, @Nullable Level level, List tooltipComponents, TooltipFlag isAdvanced, CallbackInfo ci) { - //noinspection ConstantValue - if (!((Object)this instanceof BlockItem)) { - final List tooltips = PortalCubed.TOOLTIPS.get(BuiltInRegistries.ITEM.getKey((Item)(Object)this)); - if (tooltips != null) { - tooltipComponents.addAll(tooltips); - } - } - } + @Inject(method = "appendHoverText", at = @At("HEAD")) + private void portalCubedTooltip(ItemStack stack, @Nullable Level level, List tooltipComponents, TooltipFlag isAdvanced, CallbackInfo ci) { + //noinspection ConstantValue + if (!((Object)this instanceof BlockItem)) { + final List tooltips = PortalCubed.TOOLTIPS.get(BuiltInRegistries.ITEM.getKey((Item)(Object)this)); + if (tooltips != null) { + tooltipComponents.addAll(tooltips); + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/LevelMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/LevelMixin.java index ae14fae6..7e5af3d1 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/LevelMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/LevelMixin.java @@ -39,75 +39,75 @@ @Mixin(Level.class) public abstract class LevelMixin implements LevelAccessor, LevelExt { - @Unique - private PortalCubedDamageSources pc$damageSources; - @Unique - private Long2ObjectMap> pc$blockChangeListeners = new Long2ObjectOpenHashMap<>(); + @Unique + private PortalCubedDamageSources pc$damageSources; + @Unique + private Long2ObjectMap> pc$blockChangeListeners = new Long2ObjectOpenHashMap<>(); - @Shadow - protected abstract LevelEntityGetter getEntities(); + @Shadow + protected abstract LevelEntityGetter getEntities(); - @Inject(method = "", at = @At("TAIL")) - private void createDamageSources( - WritableLevelData writableLevelData, - ResourceKey resourceKey, - RegistryAccess registryAccess, - Holder holder, - Supplier supplier, - boolean bl, - boolean bl2, - long l, - int i, - CallbackInfo ci - ) { - pc$damageSources = new PortalCubedDamageSources(registryAccess); - } + @Inject(method = "", at = @At("TAIL")) + private void createDamageSources( + WritableLevelData writableLevelData, + ResourceKey resourceKey, + RegistryAccess registryAccess, + Holder holder, + Supplier supplier, + boolean bl, + boolean bl2, + long l, + int i, + CallbackInfo ci + ) { + pc$damageSources = new PortalCubedDamageSources(registryAccess); + } - @Inject(method = "setBlocksDirty", at = @At("HEAD")) - private void updateEmittedEntities(BlockPos pos, BlockState old, BlockState updated, CallbackInfo ci) { - if ((Object) this instanceof ServerLevel) { - getListeners(pos).forEachRemaining(EmittedEntity::reEmit); - } - } + @Inject(method = "setBlocksDirty", at = @At("HEAD")) + private void updateEmittedEntities(BlockPos pos, BlockState old, BlockState updated, CallbackInfo ci) { + if ((Object) this instanceof ServerLevel) { + getListeners(pos).forEachRemaining(EmittedEntity::reEmit); + } + } - @Unique - private Iterator getListeners(BlockPos pos) { - long sectionPos = SectionPos.asLong(pos); - List listeners = pc$blockChangeListeners.get(sectionPos); - return listeners == null || listeners.isEmpty() ? Collections.emptyIterator() : new AbstractIterator<>() { - private final Iterator entities = List.copyOf(listeners).iterator(); // copy to avoid CMEs + @Unique + private Iterator getListeners(BlockPos pos) { + long sectionPos = SectionPos.asLong(pos); + List listeners = pc$blockChangeListeners.get(sectionPos); + return listeners == null || listeners.isEmpty() ? Collections.emptyIterator() : new AbstractIterator<>() { + private final Iterator entities = List.copyOf(listeners).iterator(); // copy to avoid CMEs - @Override - protected EmittedEntity computeNext() { - if (!entities.hasNext()) - return endOfData(); - EmittedEntity next = entities.next(); - return next.listensTo(pos) ? next : computeNext(); - } - }; - } + @Override + protected EmittedEntity computeNext() { + if (!entities.hasNext()) + return endOfData(); + EmittedEntity next = entities.next(); + return next.listensTo(pos) ? next : computeNext(); + } + }; + } - @Override - public void pc$addBlockChangeListener(long sectionPos, EmittedEntity entity) { - pc$blockChangeListeners.computeIfAbsent(sectionPos, $ -> new ArrayList<>()).add(entity); - } + @Override + public void pc$addBlockChangeListener(long sectionPos, EmittedEntity entity) { + pc$blockChangeListeners.computeIfAbsent(sectionPos, $ -> new ArrayList<>()).add(entity); + } - @Override - public void pc$removeBlockChangeListener(long sectionPos, EmittedEntity entity) { - List listeners = pc$blockChangeListeners.get(sectionPos); - if (listeners != null) { - listeners.remove(entity); - } - } + @Override + public void pc$removeBlockChangeListener(long sectionPos, EmittedEntity entity) { + List listeners = pc$blockChangeListeners.get(sectionPos); + if (listeners != null) { + listeners.remove(entity); + } + } - @Override - @Nullable - public Entity getEntityByUuid(UUID uuid) { - return this.getEntities().get(uuid); - } + @Override + @Nullable + public Entity getEntityByUuid(UUID uuid) { + return this.getEntities().get(uuid); + } - @Override - public PortalCubedDamageSources pcDamageSources() { - return pc$damageSources; - } + @Override + public PortalCubedDamageSources pcDamageSources() { + return pc$damageSources; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/LivingEntityMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/LivingEntityMixin.java index e59f2dff..493728b7 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/LivingEntityMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/LivingEntityMixin.java @@ -29,99 +29,99 @@ @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity implements LivingEntityAccessor { - @Shadow protected boolean jumping; + @Shadow protected boolean jumping; - @Shadow protected abstract float getFrictionInfluencedSpeed(float slipperiness); + @Shadow protected abstract float getFrictionInfluencedSpeed(float slipperiness); - @Shadow protected abstract Vec3 handleOnClimbable(Vec3 motion); + @Shadow protected abstract Vec3 handleOnClimbable(Vec3 motion); - @Shadow public abstract ItemStack getItemBySlot(EquipmentSlot slot); + @Shadow public abstract ItemStack getItemBySlot(EquipmentSlot slot); - @Shadow public abstract ItemStack getItemInHand(InteractionHand hand); + @Shadow public abstract ItemStack getItemInHand(InteractionHand hand); - public LivingEntityMixin(EntityType type, Level world) { - super(type, world); - } + public LivingEntityMixin(EntityType type, Level world) { + super(type, world); + } - @Override - public boolean isJumping() { - return jumping; - } + @Override + public boolean isJumping() { + return jumping; + } - @ModifyVariable(method = "travel", at = @At("STORE"), ordinal = 0) - private double cfg(double original) { - if (((EntityExt)this).cfg()) { - return 0; - } - return original; - } + @ModifyVariable(method = "travel", at = @At("STORE"), ordinal = 0) + private double cfg(double original) { + if (((EntityExt)this).cfg()) { + return 0; + } + return original; + } - @Inject(method = "handleRelativeFrictionAndCalculateMovement", at = @At("HEAD"), cancellable = true) - public void handleFrictionAndCalculateMovement(Vec3 movementInput, float slipperiness, CallbackInfoReturnable cir) { - if (((EntityExt) this).isInFunnel()) { - this.updateVelocityCustom(this.getFrictionInfluencedSpeed(slipperiness), movementInput); - this.setDeltaMovement(this.handleOnClimbable(this.getDeltaMovement())); - this.move(MoverType.SELF, this.getDeltaMovement()); - Vec3 vec3d = this.getDeltaMovement(); - cir.setReturnValue(vec3d); - } - } + @Inject(method = "handleRelativeFrictionAndCalculateMovement", at = @At("HEAD"), cancellable = true) + public void handleFrictionAndCalculateMovement(Vec3 movementInput, float slipperiness, CallbackInfoReturnable cir) { + if (((EntityExt) this).isInFunnel()) { + this.updateVelocityCustom(this.getFrictionInfluencedSpeed(slipperiness), movementInput); + this.setDeltaMovement(this.handleOnClimbable(this.getDeltaMovement())); + this.move(MoverType.SELF, this.getDeltaMovement()); + Vec3 vec3d = this.getDeltaMovement(); + cir.setReturnValue(vec3d); + } + } - @Unique - public void updateVelocityCustom(float speed, Vec3 movementInput) { - Vec3 vec3d = movementInputToVelocityCustom(movementInput, speed, this.getYRot(), this.getXRot()); - this.setDeltaMovement(this.getDeltaMovement().add(vec3d)); - } + @Unique + public void updateVelocityCustom(float speed, Vec3 movementInput) { + Vec3 vec3d = movementInputToVelocityCustom(movementInput, speed, this.getYRot(), this.getXRot()); + this.setDeltaMovement(this.getDeltaMovement().add(vec3d)); + } - @Unique - private static Vec3 movementInputToVelocityCustom(Vec3 movementInput, float speed, float yaw, float pitch) { - double d = movementInput.lengthSqr(); - if (d < 1.0E-7) { - return Vec3.ZERO; - } else { - Vec3 vec3d = (d > 1.0 ? movementInput.normalize() : movementInput).scale(speed); - float f = Mth.sin(yaw * 0.017453292F); - float g = Mth.cos(yaw * 0.017453292F); - float x = Mth.sin(pitch * 0.017453292F); - return new Vec3(vec3d.x * (double)g - vec3d.z * (double)f, -vec3d.z * (double)x, vec3d.z * (double)g + vec3d.x * (double)f); - } - } - @Inject(method = "swing(Lnet/minecraft/world/InteractionHand;)V", at = @At("HEAD")) - private void crowbarSwoosh(InteractionHand hand, CallbackInfo ci) { - //noinspection ConstantValue - if ((Object)this instanceof Player player && getItemInHand(hand).is(PortalCubedItems.CROWBAR)) { - level().playSound( - player, - player.getX(), player.getY(), player.getZ(), - PortalCubedSounds.CROWBAR_SWOOSH_EVENT, SoundSource.PLAYERS, - 0.7f, 1f - ); - } - } + @Unique + private static Vec3 movementInputToVelocityCustom(Vec3 movementInput, float speed, float yaw, float pitch) { + double d = movementInput.lengthSqr(); + if (d < 1.0E-7) { + return Vec3.ZERO; + } else { + Vec3 vec3d = (d > 1.0 ? movementInput.normalize() : movementInput).scale(speed); + float f = Mth.sin(yaw * 0.017453292F); + float g = Mth.cos(yaw * 0.017453292F); + float x = Mth.sin(pitch * 0.017453292F); + return new Vec3(vec3d.x * (double)g - vec3d.z * (double)f, -vec3d.z * (double)x, vec3d.z * (double)g + vec3d.x * (double)f); + } + } + @Inject(method = "swing(Lnet/minecraft/world/InteractionHand;)V", at = @At("HEAD")) + private void crowbarSwoosh(InteractionHand hand, CallbackInfo ci) { + //noinspection ConstantValue + if ((Object)this instanceof Player player && getItemInHand(hand).is(PortalCubedItems.CROWBAR)) { + level().playSound( + player, + player.getX(), player.getY(), player.getZ(), + PortalCubedSounds.CROWBAR_SWOOSH_EVENT, SoundSource.PLAYERS, + 0.7f, 1f + ); + } + } - @Inject(method = "causeFallDamage", at = @At("HEAD"), cancellable = true) - private void noFallDamage(float fallDistance, float multiplier, DamageSource source, CallbackInfoReturnable cir) { - if (getItemBySlot(EquipmentSlot.FEET).is(PortalCubedItems.LONG_FALL_BOOTS)) { - cir.setReturnValue(false); - return; - } - if (!isSuppressingBounce()) { - final AABB boundingBox = getBoundingBox(); - for (BlockPos pos : BlockPos.betweenClosed( - (int)Math.floor(boundingBox.minX), - (int)Math.floor(boundingBox.minY), - (int)Math.floor(boundingBox.minZ), - (int)Math.ceil(boundingBox.maxX), - (int)Math.ceil(boundingBox.maxY), - (int)Math.ceil(boundingBox.maxZ) - )) { - final BlockState state = level().getBlockState(pos); - if (state.is(PortalCubedBlocks.REPULSION_GEL) && BaseGel.collides(this, pos, state)) { - cir.setReturnValue(false); - return; - } - } - } - } + @Inject(method = "causeFallDamage", at = @At("HEAD"), cancellable = true) + private void noFallDamage(float fallDistance, float multiplier, DamageSource source, CallbackInfoReturnable cir) { + if (getItemBySlot(EquipmentSlot.FEET).is(PortalCubedItems.LONG_FALL_BOOTS)) { + cir.setReturnValue(false); + return; + } + if (!isSuppressingBounce()) { + final AABB boundingBox = getBoundingBox(); + for (BlockPos pos : BlockPos.betweenClosed( + (int)Math.floor(boundingBox.minX), + (int)Math.floor(boundingBox.minY), + (int)Math.floor(boundingBox.minZ), + (int)Math.ceil(boundingBox.maxX), + (int)Math.ceil(boundingBox.maxY), + (int)Math.ceil(boundingBox.maxZ) + )) { + final BlockState state = level().getBlockState(pos); + if (state.is(PortalCubedBlocks.REPULSION_GEL) && BaseGel.collides(this, pos, state)) { + cir.setReturnValue(false); + return; + } + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/PlayerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/PlayerMixin.java index d8f07ada..bc0abfce 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/PlayerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/PlayerMixin.java @@ -53,339 +53,339 @@ @Mixin(Player.class) public abstract class PlayerMixin extends LivingEntity implements EntityExt { - @Unique - private boolean cfg; - - protected PlayerMixin(EntityType entityType, Level world) { - super(entityType, world); - } - - @NotNull - @Shadow - @Override - public abstract ItemStack getItemBySlot(@NotNull EquipmentSlot slot); - - @Shadow - @Override - public abstract void playSound(@NotNull SoundEvent sound, float volume, float pitch); - - @Shadow - @Override - public abstract boolean isSwimming(); - - @Shadow @Final private Abilities abilities; - - @Override - @Shadow public abstract float getSpeed(); - - @ModifyVariable(method = "travel", at = @At("HEAD"), argsOnly = true) - private Vec3 portalCubed$what(Vec3 travelVectorOriginal) { - if (!this.isNoGravity() && !this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && this.getItemBySlot(EquipmentSlot.FEET).getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel()) { - double mathVal = 1; - double horizontalVelocity = Math.abs(this.getDeltaMovement().x) + Math.abs(this.getDeltaMovement().z); - if (horizontalVelocity / 0.01783440120041885 > 1) { - mathVal = horizontalVelocity / 0.01783440120041885; - } - travelVectorOriginal = new Vec3(travelVectorOriginal.x / mathVal, travelVectorOriginal.y, travelVectorOriginal.z / mathVal); - } - if (CalledValues.getIsTeleporting(this)) { - travelVectorOriginal = Vec3.ZERO; - } - - return travelVectorOriginal; - } - - @Inject(method = "getFlyingSpeed", at = @At("HEAD"), cancellable = true) - private void replaceFlyingSpeed(CallbackInfoReturnable cir) { - if (!this.isNoGravity() && !this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && this.getItemBySlot(EquipmentSlot.FEET).getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel()) { - cir.setReturnValue(0.04f); - } - } - - @Unique - private boolean enableNoDrag2; - - @Inject(method = "tick", at = @At("HEAD")) - public void tickHead(CallbackInfo ci) { - Player thisEntity = ((Player) (Object) this); - - if (level().isClientSide && CalledValues.getHasTeleportationHappened(thisEntity)) { - var byteBuf = PacketByteBufs.create(); - NetworkingSafetyWrapper.sendFromClient("client_teleport_update", byteBuf); - CalledValues.setHasTeleportationHappened(thisEntity, false); - ((EntityExt) thisEntity).setMaxFallHeight(-99999999); - CalledValues.setIsTeleporting(thisEntity, false); - this.setDeltaMovement(CalledValues.getVelocityUpdateAfterTeleport(thisEntity)); - } - - GeneralUtil.setupPortalShapes(this); - - ItemStack itemFeet = this.getItemBySlot(EquipmentSlot.FEET); - if ((!this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && itemFeet.getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel())) { - if (!enableNoDrag2) { - enableNoDrag2 = true; - } - this.setDiscardFriction(true); - } else if (enableNoDrag2) { - enableNoDrag2 = false; - this.setDiscardFriction(false); - } - - if (itemFeet.getItem().equals(PortalCubedItems.LONG_FALL_BOOTS)) { - if (this.getDeltaMovement().y < -3.92) { - this.setDeltaMovement(this.getDeltaMovement().add(0, .081d, 0)); - } - } - - if (!( - level().isClientSide - ? pc$allowCfgClient() - : level().getGameRules().getBoolean(PortalCubedGameRules.ALLOW_CROUCH_FLY_GLITCH) - ) || !isShiftKeyDown() - ) { - cfg = false; - } - } - - @Unique - @ClientOnly - private static boolean pc$allowCfgClient() { - return PortalCubedClient.allowCfg; - } - - @Inject(method = "tick", at = @At("TAIL")) - public void tickTail(CallbackInfo ci) { - if (this.level().isClientSide) { - Player thisEntity = ((Player) (Object) this); - - Vec3 entityVelocity = thisEntity.getDeltaMovement(); - - AABB portalCheckBox = getBoundingBox(); - - portalCheckBox = portalCheckBox.expandTowards(entityVelocity).expandTowards(entityVelocity.scale(-1)); - - List list = level().getEntitiesOfClass(Portal.class, portalCheckBox); - - Set> possiblePortals = new HashSet<>(); - - for (Portal portalCheck : list) { - if (this.canChangeDimensions() && portalCheck.getActive() && !CalledValues.getHasTeleportationHappened(thisEntity) && !CalledValues.getIsTeleporting(thisEntity)) { - assert portalCheck.getOtherNormal().isPresent(); - Direction portalFacing = portalCheck.getFacingDirection(); - entityVelocity = thisEntity.getDeltaMovement(); - - if (thisEntity.shouldDiscardFriction()) { - entityVelocity = entityVelocity.add(0, .08, 0); - } else { - entityVelocity = entityVelocity.add(0, .08 * .98, 0); - } -// Vec3 entityPos = portalCheck.getNormal().y > 0 ? thisEntity.position() : thisEntity.getEyePosition(); - Vec3 entityPos = thisEntity.position().add(0, doFeetTeleport(portalCheck) ? 0.02 - entityVelocity.y : thisEntity.getEyeHeight(), 0); - final boolean isColliding = portalCheck.getBoundingBox().distanceToSqr(entityPos) <= entityVelocity.lengthSqr(); - if (portalFacing.step().x() < 0) { - if (entityPos.x() + entityVelocity.x >= portalCheck.position().x() && entityVelocity.x() > 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - if (portalFacing.step().y() < 0) { - if (entityPos.y() + entityVelocity.y >= portalCheck.position().y() && entityVelocity.y() > 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - if (portalFacing.step().z() < 0) { - if (entityPos.z() + entityVelocity.z >= portalCheck.position().z() && entityVelocity.z() > 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - if (portalFacing.step().x() > 0) { - if (entityPos.x() + entityVelocity.x <= portalCheck.position().x() && entityVelocity.x() < 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - if (portalFacing.step().y() > 0) { - if (entityPos.y() + entityVelocity.y <= portalCheck.position().y() && entityVelocity.y() < 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - if (portalFacing.step().z() > 0) { - if (entityPos.z() + entityVelocity.z <= portalCheck.position().z() && entityVelocity.z() < 0 && isColliding) { - possiblePortals.add(Pair.of(portalCheck, entityPos)); - } - } - - } - } - Pair portal = null; - double distance = 100; - for (var portalTry : possiblePortals) { - double checkDistance = portalTry.first().position().distanceTo(thisEntity.getBoundingBox().getCenter()); - if (checkDistance < distance) { - distance = checkDistance; - portal = portalTry; - } - } - if (portal != null) { - performTeleport(thisEntity, portal.first(), entityVelocity, portal.second()); - } - - PortalCubedComponents.HOLDER_COMPONENT.get(this).tick(); - - } - } - - @Unique - private static boolean doFeetTeleport(Portal portal) { - assert portal.getOtherNormal().isPresent(); - final double y = portal.getNormal().y; - final double oy = portal.getOtherNormal().get().y; - return (y > 0 && oy < 0) || y < 0; - } - - @Unique - private void performTeleport( - Player thisEntity, - Portal portal, - Vec3 entityVelocity, - Vec3 basePosition - ) { - assert portal.getDestination().isPresent(); - assert portal.getOtherNormal().isPresent(); - - if (this.level().isClientSide && thisEntity.isLocalPlayer()) { - Vec3 invert = (portal.getNormal().multiply(portal.getNormal())).scale(-1); - if (invert.x != 0) { - invert = invert.add(0, 1, 1); - } else if (invert.y != 0) { - invert = invert.add(1, 0, 1); - } else if (invert.z != 0) { - invert = invert.add(1, 1, 0); - } - final Optional cameraInterp = interpCamera(); - var byteBuf = PacketByteBufs.create(); - byteBuf.writeVarInt(portal.getId()); - byteBuf.writeFloat(thisEntity.getYRot()); - byteBuf.writeFloat(thisEntity.getXRot()); - byteBuf.writeOptional(cameraInterp, (b, q) -> { - b.writeDouble(q.x); - b.writeDouble(q.y); - b.writeDouble(q.z); - b.writeDouble(q.w); - }); - byteBuf.writeDouble(entityVelocity.x); - byteBuf.writeDouble(entityVelocity.y); - byteBuf.writeDouble(entityVelocity.z); - Vec3 teleportOffset = new Vec3( - ((basePosition.x()) - portal.position().x()) * invert.x, - ((basePosition.y()) - portal.position().y()) * invert.y, - ((basePosition.z()) - portal.position().z()) * invert.z - ); - Vec3 teleportOffsetNoRotate = Vec3.ZERO; - if (portal.getNormal().y < 0 && portal.getOtherNormal().get().y <= 0) { - teleportOffset = teleportOffset.add( - 0, - thisEntity.getEyeHeight() - Math.sqrt( - portal.getBoundingBox().distanceToSqr(thisEntity.position()) - ), - 0 - ); - if (portal.getOtherNormal().get().y > -1e-7) { - teleportOffsetNoRotate = teleportOffsetNoRotate.add(0, -thisEntity.getEyeHeight(), 0); - } - } else if (portal.getNormal().y > 0 && portal.getOtherNormal().get().y > 0) { - teleportOffset = teleportOffset.add(0, thisEntity.getEyeHeight(), 0); - } - if (portal.getOtherNormal().get().y < 0 && portal.getNormal().y <= 0) { - teleportOffsetNoRotate = teleportOffsetNoRotate.add(0, -thisEntity.getEyeHeight(), 0); - } - byteBuf.writeDouble(teleportOffset.x); - byteBuf.writeDouble(teleportOffset.y); - byteBuf.writeDouble(teleportOffset.z); - byteBuf.writeDouble(teleportOffsetNoRotate.x); - byteBuf.writeDouble(teleportOffsetNoRotate.y); - byteBuf.writeDouble(teleportOffsetNoRotate.z); - NetworkingSafetyWrapper.sendFromClient("use_portal", byteBuf); -// CalledValues.setIsTeleporting(thisEntity, true); - - final TeleportResult result = PortalCubed.commonTeleport( - portal, - entityVelocity, - teleportOffset, - teleportOffsetNoRotate, - thisEntity, - cameraInterp, - thisEntity.getXRot(), - thisEntity.getYRot() - ); - final Vec3 dest = result.dest(); - moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); - setDeltaMovement(result.velocity()); - interpCamera( - IPQuaternion.getCameraRotation(result.pitch(), result.yaw()) - .getConjugated() - .hamiltonProduct(result.immediateFinalRot()) - ); - } - } - - @Unique - @ClientOnly - private static Optional interpCamera() { - return PortalCubedClient.interpCamera(); - } - - @Unique - @ClientOnly - private static void interpCamera(IPQuaternion interp) { - PortalCubedClient.cameraInterpStart = interp; - PortalCubedClient.cameraInterpStartTime = System.currentTimeMillis(); - } - - @Inject( - method = "drop(Lnet/minecraft/world/item/ItemStack;ZZ)Lnet/minecraft/world/entity/item/ItemEntity;", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/entity/player/Player;getEyeY()D" - ) - ) - public void portalCubed$dropItem(ItemStack stack, boolean throwRandomly, boolean retainOwnership, CallbackInfoReturnable<@Nullable ItemEntity> cir) { - if (!this.level().isClientSide && stack.getItem().equals(PortalCubedItems.PORTAL_GUN)) { - CompoundTag tag = stack.getOrCreateTag(); - CompoundTag portalsTag = tag.getCompound(level().dimension().location().toString()); - Portal portalHolder; - if (portalsTag.contains(("Left") + "Portal")) { - portalHolder = (Portal) ((ServerLevel) level()).getEntity(portalsTag.getUUID(("Left") + "Portal")); - if (portalHolder != null) { - portalHolder.kill(); - } - } - if (portalsTag.contains(("Right") + "Portal")) { - portalHolder = (Portal) ((ServerLevel) level()).getEntity(portalsTag.getUUID(("Right") + "Portal")); - if (portalHolder != null) { - portalHolder.kill(); - } - } - } - } - - @Override - public boolean cfg() { - return cfg; - } - - @Override - public void setCFG() { - cfg = true; - } - - @WrapOperation( - method = "updatePlayerPose", - at = @At( - value = "FIELD", - target = "Lnet/minecraft/world/entity/Pose;CROUCHING:Lnet/minecraft/world/entity/Pose;", - opcode = Opcodes.GETSTATIC - ) - ) - private Pose playerCrouching(Operation original) { - return PortalCubed.portalHudModeServerOrClient(level()) ? Pose.SWIMMING : original.call(); - } + @Unique + private boolean cfg; + + protected PlayerMixin(EntityType entityType, Level world) { + super(entityType, world); + } + + @NotNull + @Shadow + @Override + public abstract ItemStack getItemBySlot(@NotNull EquipmentSlot slot); + + @Shadow + @Override + public abstract void playSound(@NotNull SoundEvent sound, float volume, float pitch); + + @Shadow + @Override + public abstract boolean isSwimming(); + + @Shadow @Final private Abilities abilities; + + @Override + @Shadow public abstract float getSpeed(); + + @ModifyVariable(method = "travel", at = @At("HEAD"), argsOnly = true) + private Vec3 portalCubed$what(Vec3 travelVectorOriginal) { + if (!this.isNoGravity() && !this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && this.getItemBySlot(EquipmentSlot.FEET).getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel()) { + double mathVal = 1; + double horizontalVelocity = Math.abs(this.getDeltaMovement().x) + Math.abs(this.getDeltaMovement().z); + if (horizontalVelocity / 0.01783440120041885 > 1) { + mathVal = horizontalVelocity / 0.01783440120041885; + } + travelVectorOriginal = new Vec3(travelVectorOriginal.x / mathVal, travelVectorOriginal.y, travelVectorOriginal.z / mathVal); + } + if (CalledValues.getIsTeleporting(this)) { + travelVectorOriginal = Vec3.ZERO; + } + + return travelVectorOriginal; + } + + @Inject(method = "getFlyingSpeed", at = @At("HEAD"), cancellable = true) + private void replaceFlyingSpeed(CallbackInfoReturnable cir) { + if (!this.isNoGravity() && !this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && this.getItemBySlot(EquipmentSlot.FEET).getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel()) { + cir.setReturnValue(0.04f); + } + } + + @Unique + private boolean enableNoDrag2; + + @Inject(method = "tick", at = @At("HEAD")) + public void tickHead(CallbackInfo ci) { + Player thisEntity = ((Player) (Object) this); + + if (level().isClientSide && CalledValues.getHasTeleportationHappened(thisEntity)) { + var byteBuf = PacketByteBufs.create(); + NetworkingSafetyWrapper.sendFromClient("client_teleport_update", byteBuf); + CalledValues.setHasTeleportationHappened(thisEntity, false); + ((EntityExt) thisEntity).setMaxFallHeight(-99999999); + CalledValues.setIsTeleporting(thisEntity, false); + this.setDeltaMovement(CalledValues.getVelocityUpdateAfterTeleport(thisEntity)); + } + + GeneralUtil.setupPortalShapes(this); + + ItemStack itemFeet = this.getItemBySlot(EquipmentSlot.FEET); + if ((!this.onGround() && PortalCubedConfig.enableAccurateMovement && !this.isSwimming() && !this.abilities.flying && !this.isFallFlying() && itemFeet.getItem().equals(PortalCubedItems.LONG_FALL_BOOTS) && !this.isInFunnel())) { + if (!enableNoDrag2) { + enableNoDrag2 = true; + } + this.setDiscardFriction(true); + } else if (enableNoDrag2) { + enableNoDrag2 = false; + this.setDiscardFriction(false); + } + + if (itemFeet.getItem().equals(PortalCubedItems.LONG_FALL_BOOTS)) { + if (this.getDeltaMovement().y < -3.92) { + this.setDeltaMovement(this.getDeltaMovement().add(0, .081d, 0)); + } + } + + if (!( + level().isClientSide + ? pc$allowCfgClient() + : level().getGameRules().getBoolean(PortalCubedGameRules.ALLOW_CROUCH_FLY_GLITCH) + ) || !isShiftKeyDown() + ) { + cfg = false; + } + } + + @Unique + @ClientOnly + private static boolean pc$allowCfgClient() { + return PortalCubedClient.allowCfg; + } + + @Inject(method = "tick", at = @At("TAIL")) + public void tickTail(CallbackInfo ci) { + if (this.level().isClientSide) { + Player thisEntity = ((Player) (Object) this); + + Vec3 entityVelocity = thisEntity.getDeltaMovement(); + + AABB portalCheckBox = getBoundingBox(); + + portalCheckBox = portalCheckBox.expandTowards(entityVelocity).expandTowards(entityVelocity.scale(-1)); + + List list = level().getEntitiesOfClass(Portal.class, portalCheckBox); + + Set> possiblePortals = new HashSet<>(); + + for (Portal portalCheck : list) { + if (this.canChangeDimensions() && portalCheck.getActive() && !CalledValues.getHasTeleportationHappened(thisEntity) && !CalledValues.getIsTeleporting(thisEntity)) { + assert portalCheck.getOtherNormal().isPresent(); + Direction portalFacing = portalCheck.getFacingDirection(); + entityVelocity = thisEntity.getDeltaMovement(); + + if (thisEntity.shouldDiscardFriction()) { + entityVelocity = entityVelocity.add(0, .08, 0); + } else { + entityVelocity = entityVelocity.add(0, .08 * .98, 0); + } +// Vec3 entityPos = portalCheck.getNormal().y > 0 ? thisEntity.position() : thisEntity.getEyePosition(); + Vec3 entityPos = thisEntity.position().add(0, doFeetTeleport(portalCheck) ? 0.02 - entityVelocity.y : thisEntity.getEyeHeight(), 0); + final boolean isColliding = portalCheck.getBoundingBox().distanceToSqr(entityPos) <= entityVelocity.lengthSqr(); + if (portalFacing.step().x() < 0) { + if (entityPos.x() + entityVelocity.x >= portalCheck.position().x() && entityVelocity.x() > 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + if (portalFacing.step().y() < 0) { + if (entityPos.y() + entityVelocity.y >= portalCheck.position().y() && entityVelocity.y() > 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + if (portalFacing.step().z() < 0) { + if (entityPos.z() + entityVelocity.z >= portalCheck.position().z() && entityVelocity.z() > 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + if (portalFacing.step().x() > 0) { + if (entityPos.x() + entityVelocity.x <= portalCheck.position().x() && entityVelocity.x() < 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + if (portalFacing.step().y() > 0) { + if (entityPos.y() + entityVelocity.y <= portalCheck.position().y() && entityVelocity.y() < 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + if (portalFacing.step().z() > 0) { + if (entityPos.z() + entityVelocity.z <= portalCheck.position().z() && entityVelocity.z() < 0 && isColliding) { + possiblePortals.add(Pair.of(portalCheck, entityPos)); + } + } + + } + } + Pair portal = null; + double distance = 100; + for (var portalTry : possiblePortals) { + double checkDistance = portalTry.first().position().distanceTo(thisEntity.getBoundingBox().getCenter()); + if (checkDistance < distance) { + distance = checkDistance; + portal = portalTry; + } + } + if (portal != null) { + performTeleport(thisEntity, portal.first(), entityVelocity, portal.second()); + } + + PortalCubedComponents.HOLDER_COMPONENT.get(this).tick(); + + } + } + + @Unique + private static boolean doFeetTeleport(Portal portal) { + assert portal.getOtherNormal().isPresent(); + final double y = portal.getNormal().y; + final double oy = portal.getOtherNormal().get().y; + return (y > 0 && oy < 0) || y < 0; + } + + @Unique + private void performTeleport( + Player thisEntity, + Portal portal, + Vec3 entityVelocity, + Vec3 basePosition + ) { + assert portal.getDestination().isPresent(); + assert portal.getOtherNormal().isPresent(); + + if (this.level().isClientSide && thisEntity.isLocalPlayer()) { + Vec3 invert = (portal.getNormal().multiply(portal.getNormal())).scale(-1); + if (invert.x != 0) { + invert = invert.add(0, 1, 1); + } else if (invert.y != 0) { + invert = invert.add(1, 0, 1); + } else if (invert.z != 0) { + invert = invert.add(1, 1, 0); + } + final Optional cameraInterp = interpCamera(); + var byteBuf = PacketByteBufs.create(); + byteBuf.writeVarInt(portal.getId()); + byteBuf.writeFloat(thisEntity.getYRot()); + byteBuf.writeFloat(thisEntity.getXRot()); + byteBuf.writeOptional(cameraInterp, (b, q) -> { + b.writeDouble(q.x); + b.writeDouble(q.y); + b.writeDouble(q.z); + b.writeDouble(q.w); + }); + byteBuf.writeDouble(entityVelocity.x); + byteBuf.writeDouble(entityVelocity.y); + byteBuf.writeDouble(entityVelocity.z); + Vec3 teleportOffset = new Vec3( + ((basePosition.x()) - portal.position().x()) * invert.x, + ((basePosition.y()) - portal.position().y()) * invert.y, + ((basePosition.z()) - portal.position().z()) * invert.z + ); + Vec3 teleportOffsetNoRotate = Vec3.ZERO; + if (portal.getNormal().y < 0 && portal.getOtherNormal().get().y <= 0) { + teleportOffset = teleportOffset.add( + 0, + thisEntity.getEyeHeight() - Math.sqrt( + portal.getBoundingBox().distanceToSqr(thisEntity.position()) + ), + 0 + ); + if (portal.getOtherNormal().get().y > -1e-7) { + teleportOffsetNoRotate = teleportOffsetNoRotate.add(0, -thisEntity.getEyeHeight(), 0); + } + } else if (portal.getNormal().y > 0 && portal.getOtherNormal().get().y > 0) { + teleportOffset = teleportOffset.add(0, thisEntity.getEyeHeight(), 0); + } + if (portal.getOtherNormal().get().y < 0 && portal.getNormal().y <= 0) { + teleportOffsetNoRotate = teleportOffsetNoRotate.add(0, -thisEntity.getEyeHeight(), 0); + } + byteBuf.writeDouble(teleportOffset.x); + byteBuf.writeDouble(teleportOffset.y); + byteBuf.writeDouble(teleportOffset.z); + byteBuf.writeDouble(teleportOffsetNoRotate.x); + byteBuf.writeDouble(teleportOffsetNoRotate.y); + byteBuf.writeDouble(teleportOffsetNoRotate.z); + NetworkingSafetyWrapper.sendFromClient("use_portal", byteBuf); +// CalledValues.setIsTeleporting(thisEntity, true); + + final TeleportResult result = PortalCubed.commonTeleport( + portal, + entityVelocity, + teleportOffset, + teleportOffsetNoRotate, + thisEntity, + cameraInterp, + thisEntity.getXRot(), + thisEntity.getYRot() + ); + final Vec3 dest = result.dest(); + moveTo(dest.x, dest.y, dest.z, result.yaw(), result.pitch()); + setDeltaMovement(result.velocity()); + interpCamera( + IPQuaternion.getCameraRotation(result.pitch(), result.yaw()) + .getConjugated() + .hamiltonProduct(result.immediateFinalRot()) + ); + } + } + + @Unique + @ClientOnly + private static Optional interpCamera() { + return PortalCubedClient.interpCamera(); + } + + @Unique + @ClientOnly + private static void interpCamera(IPQuaternion interp) { + PortalCubedClient.cameraInterpStart = interp; + PortalCubedClient.cameraInterpStartTime = System.currentTimeMillis(); + } + + @Inject( + method = "drop(Lnet/minecraft/world/item/ItemStack;ZZ)Lnet/minecraft/world/entity/item/ItemEntity;", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/entity/player/Player;getEyeY()D" + ) + ) + public void portalCubed$dropItem(ItemStack stack, boolean throwRandomly, boolean retainOwnership, CallbackInfoReturnable<@Nullable ItemEntity> cir) { + if (!this.level().isClientSide && stack.getItem().equals(PortalCubedItems.PORTAL_GUN)) { + CompoundTag tag = stack.getOrCreateTag(); + CompoundTag portalsTag = tag.getCompound(level().dimension().location().toString()); + Portal portalHolder; + if (portalsTag.contains(("Left") + "Portal")) { + portalHolder = (Portal) ((ServerLevel) level()).getEntity(portalsTag.getUUID(("Left") + "Portal")); + if (portalHolder != null) { + portalHolder.kill(); + } + } + if (portalsTag.contains(("Right") + "Portal")) { + portalHolder = (Portal) ((ServerLevel) level()).getEntity(portalsTag.getUUID(("Right") + "Portal")); + if (portalHolder != null) { + portalHolder.kill(); + } + } + } + } + + @Override + public boolean cfg() { + return cfg; + } + + @Override + public void setCFG() { + cfg = true; + } + + @WrapOperation( + method = "updatePlayerPose", + at = @At( + value = "FIELD", + target = "Lnet/minecraft/world/entity/Pose;CROUCHING:Lnet/minecraft/world/entity/Pose;", + opcode = Opcodes.GETSTATIC + ) + ) + private Pose playerCrouching(Operation original) { + return PortalCubed.portalHudModeServerOrClient(level()) ? Pose.SWIMMING : original.call(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/ServerGamePacketListenerImplMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/ServerGamePacketListenerImplMixin.java index 6d66c42a..89b4399b 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/ServerGamePacketListenerImplMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/ServerGamePacketListenerImplMixin.java @@ -14,47 +14,47 @@ @Mixin(ServerGamePacketListenerImpl.class) public abstract class ServerGamePacketListenerImplMixin { - @Shadow public ServerPlayer player; - - @Shadow public abstract ServerPlayer getPlayer(); - - @WrapOperation( - method = "handleUseItemOn", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/Vec3;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", - ordinal = 0 - ) - ) - private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck1(Vec3 instance, Vec3 to, Operation original) { - final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, to); - return distance == Double.NEGATIVE_INFINITY ? original.call(instance, to) : distance; - } - - @WrapOperation( - method = "handleUseItemOn", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/server/level/ServerPlayer;distanceToSqr(DDD)D", - ordinal = 0 - ) - ) - private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck2(ServerPlayer instance, double x, double y, double z, Operation original) { - final double distance = CrossPortalInteraction.interactionDistance(player, 64, new Vec3(x, y, z)); - return distance == Double.NEGATIVE_INFINITY ? original.call(instance, x, y, z) : distance; - } - - @WrapOperation( - method = "handleInteract", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/AABB;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", - ordinal = 0 - ) - ) - private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck3(AABB instance, Vec3 eyePos, Operation original) { - final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, instance.getCenter()); - return distance == Double.NEGATIVE_INFINITY ? original.call(instance, eyePos) : distance; - } + @Shadow public ServerPlayer player; + + @Shadow public abstract ServerPlayer getPlayer(); + + @WrapOperation( + method = "handleUseItemOn", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/Vec3;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", + ordinal = 0 + ) + ) + private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck1(Vec3 instance, Vec3 to, Operation original) { + final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, to); + return distance == Double.NEGATIVE_INFINITY ? original.call(instance, to) : distance; + } + + @WrapOperation( + method = "handleUseItemOn", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/server/level/ServerPlayer;distanceToSqr(DDD)D", + ordinal = 0 + ) + ) + private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck2(ServerPlayer instance, double x, double y, double z, Operation original) { + final double distance = CrossPortalInteraction.interactionDistance(player, 64, new Vec3(x, y, z)); + return distance == Double.NEGATIVE_INFINITY ? original.call(instance, x, y, z) : distance; + } + + @WrapOperation( + method = "handleInteract", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/AABB;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", + ordinal = 0 + ) + ) + private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck3(AABB instance, Vec3 eyePos, Operation original) { + final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, instance.getCenter()); + return distance == Double.NEGATIVE_INFINITY ? original.call(instance, eyePos) : distance; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/ServerPlayerGameModeMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/ServerPlayerGameModeMixin.java index 6dbf34db..eb4b3293 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/ServerPlayerGameModeMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/ServerPlayerGameModeMixin.java @@ -15,18 +15,18 @@ @Mixin(value = ServerPlayerGameMode.class, priority = 1001) public abstract class ServerPlayerGameModeMixin { - @Shadow @Final protected ServerPlayer player; + @Shadow @Final protected ServerPlayer player; - @WrapOperation( - method = "handleBlockBreakAction", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/phys/Vec3;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", - ordinal = 0 - ) - ) - private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck4(Vec3 instance, Vec3 to, Operation original) { - final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, to); - return distance == Double.NEGATIVE_INFINITY ? original.call(instance, to) : distance; - } + @WrapOperation( + method = "handleBlockBreakAction", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/phys/Vec3;distanceToSqr(Lnet/minecraft/world/phys/Vec3;)D", + ordinal = 0 + ) + ) + private double portalCubed$replaceWithCrossPortalInteractionDistanceCheck4(Vec3 instance, Vec3 to, Operation original) { + final double distance = CrossPortalInteraction.interactionDistance(player, ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE, to); + return distance == Double.NEGATIVE_INFINITY ? original.call(instance, to) : distance; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractContainerScreenMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractContainerScreenMixin.java index d2a183a4..bccea44e 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractContainerScreenMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractContainerScreenMixin.java @@ -11,14 +11,14 @@ @Mixin(AbstractContainerScreen.class) public class AbstractContainerScreenMixin { - @Inject(method = "onClose", at = @At("HEAD")) - private void floorButtonEasterEgg(CallbackInfo ci) { - //noinspection ConstantValue - if ((Object)this instanceof EffectRenderingInventoryScreen) { - if (FloorButtonBlock.enableEasterEgg) { - FloorButtonBlock.enableEasterEgg = false; - CreativeModeTabsAccessor.setCACHED_PARAMETERS(null); - } - } - } + @Inject(method = "onClose", at = @At("HEAD")) + private void floorButtonEasterEgg(CallbackInfo ci) { + //noinspection ConstantValue + if ((Object)this instanceof EffectRenderingInventoryScreen) { + if (FloorButtonBlock.enableEasterEgg) { + FloorButtonBlock.enableEasterEgg = false; + CreativeModeTabsAccessor.setCACHED_PARAMETERS(null); + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractSoundInstanceAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractSoundInstanceAccessor.java index dff7472a..d2b8a138 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractSoundInstanceAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/AbstractSoundInstanceAccessor.java @@ -6,6 +6,6 @@ @Mixin(AbstractSoundInstance.class) public interface AbstractSoundInstanceAccessor { - @Accessor("volume") - void setVolume(float volume); + @Accessor("volume") + void setVolume(float volume); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/BakedQuadMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/BakedQuadMixin.java index 94c80e73..ca8909ea 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/BakedQuadMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/BakedQuadMixin.java @@ -9,16 +9,16 @@ @Mixin(BakedQuad.class) public class BakedQuadMixin implements BakedQuadExt { - @Unique - private String portalcubed$renderType; + @Unique + private String portalcubed$renderType; - @Override - public @Nullable String portalcubed$getRenderType() { - return portalcubed$renderType; - } + @Override + public @Nullable String portalcubed$getRenderType() { + return portalcubed$renderType; + } - @Override - public void portalcubed$setRenderType(String type) { - portalcubed$renderType = type; - } + @Override + public void portalcubed$setRenderType(String type) { + portalcubed$renderType = type; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElementMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElementMixin.java index 67f0b74f..c149c86d 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElementMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElementMixin.java @@ -9,17 +9,17 @@ @Mixin(BlockElement.class) public class BlockElementMixin implements BlockElementExt { - @Unique - private String portalcubed$renderType; + @Unique + private String portalcubed$renderType; - @Override - @Nullable - public String portalcubed$getRenderType() { - return portalcubed$renderType; - } + @Override + @Nullable + public String portalcubed$getRenderType() { + return portalcubed$renderType; + } - @Override - public void portalcubed$setRenderType(String type) { - this.portalcubed$renderType = type; - } + @Override + public void portalcubed$setRenderType(String type) { + this.portalcubed$renderType = type; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElement_DeserializerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElement_DeserializerMixin.java index 42de2ea1..07c6a7f7 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElement_DeserializerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockElement_DeserializerMixin.java @@ -12,18 +12,18 @@ @SuppressWarnings("checkstyle:TypeName") @Mixin(targets = "net.minecraft.client.renderer.block.model.BlockElement$Deserializer") public class BlockElement_DeserializerMixin { - @ModifyReturnValue(method = "deserialize", at = @At("RETURN")) - private BlockElement portalcubed$addRenderType(BlockElement element, - JsonElement json, Type type, JsonDeserializationContext context) { - JsonObject obj = json.getAsJsonObject(); - JsonElement renderTypeElement = obj.get("portalcubed:render_type"); - if (renderTypeElement != null) { - if (!(renderTypeElement instanceof JsonPrimitive primitive) || !primitive.isString()) { - throw new JsonParseException("portalcubed:render_type must be a string"); - } - String renderType = primitive.getAsString(); - ((BlockElementExt) element).portalcubed$setRenderType(renderType); - } - return element; - } + @ModifyReturnValue(method = "deserialize", at = @At("RETURN")) + private BlockElement portalcubed$addRenderType(BlockElement element, + JsonElement json, Type type, JsonDeserializationContext context) { + JsonObject obj = json.getAsJsonObject(); + JsonElement renderTypeElement = obj.get("portalcubed:render_type"); + if (renderTypeElement != null) { + if (!(renderTypeElement instanceof JsonPrimitive primitive) || !primitive.isString()) { + throw new JsonParseException("portalcubed:render_type must be a string"); + } + String renderType = primitive.getAsString(); + ((BlockElementExt) element).portalcubed$setRenderType(renderType); + } + return element; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModelMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModelMixin.java index 7e51fd6c..36e58c7a 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModelMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModelMixin.java @@ -22,33 +22,33 @@ @Mixin(BlockModel.class) public abstract class BlockModelMixin { - @Shadow - public abstract List getElements(); + @Shadow + public abstract List getElements(); - @ModifyReturnValue( - method = "bake(Lnet/minecraft/client/resources/model/ModelBaker;Lnet/minecraft/client/renderer/block/model/BlockModel;Ljava/util/function/Function;Lnet/minecraft/client/resources/model/ModelState;Lnet/minecraft/resources/ResourceLocation;Z)Lnet/minecraft/client/resources/model/BakedModel;", - at = @At("RETURN") - ) - private BakedModel portalcubed$useMultiRenderTypeModel(BakedModel model) { - if (model instanceof SimpleBakedModel simple) { - for (BlockElement element : getElements()) { - String renderType = ((BlockElementExt) element).portalcubed$getRenderType(); - if (renderType != null) { - return new MultiRenderTypeSimpleBakedModel(simple); - } - } - } - return model; - } + @ModifyReturnValue( + method = "bake(Lnet/minecraft/client/resources/model/ModelBaker;Lnet/minecraft/client/renderer/block/model/BlockModel;Ljava/util/function/Function;Lnet/minecraft/client/resources/model/ModelState;Lnet/minecraft/resources/ResourceLocation;Z)Lnet/minecraft/client/resources/model/BakedModel;", + at = @At("RETURN") + ) + private BakedModel portalcubed$useMultiRenderTypeModel(BakedModel model) { + if (model instanceof SimpleBakedModel simple) { + for (BlockElement element : getElements()) { + String renderType = ((BlockElementExt) element).portalcubed$getRenderType(); + if (renderType != null) { + return new MultiRenderTypeSimpleBakedModel(simple); + } + } + } + return model; + } - @ModifyReturnValue(method = "bakeFace", at = @At("RETURN")) - private static BakedQuad portalcubed$giveQuadRenderType(BakedQuad quad, - BlockElement part, BlockElementFace partFace, TextureAtlasSprite sprite, - Direction direction, ModelState transform, ResourceLocation location) { - String renderType = ((BlockElementExt) part).portalcubed$getRenderType(); - if (renderType != null) { - ((BakedQuadExt) quad).portalcubed$setRenderType(renderType); - } - return quad; - } + @ModifyReturnValue(method = "bakeFace", at = @At("RETURN")) + private static BakedQuad portalcubed$giveQuadRenderType(BakedQuad quad, + BlockElement part, BlockElementFace partFace, TextureAtlasSprite sprite, + Direction direction, ModelState transform, ResourceLocation location) { + String renderType = ((BlockElementExt) part).portalcubed$getRenderType(); + if (renderType != null) { + ((BakedQuadExt) quad).portalcubed$setRenderType(renderType); + } + return quad; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModel_DeserializerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModel_DeserializerMixin.java index 37592cf8..7dcb03c0 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModel_DeserializerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/BlockModel_DeserializerMixin.java @@ -12,18 +12,18 @@ @SuppressWarnings("checkstyle:TypeName") @Mixin(BlockModel.Deserializer.class) public class BlockModel_DeserializerMixin { - // failing in parsing is much better than in baking. - @ModifyReturnValue(method = "deserialize", at = @At("RETURN")) - private BlockModel portalcubed$validateMultiRenderTypeModel(BlockModel original) { - if (!RenderMaterials.ARE_SUPPORTED) - return original; + // failing in parsing is much better than in baking. + @ModifyReturnValue(method = "deserialize", at = @At("RETURN")) + private BlockModel portalcubed$validateMultiRenderTypeModel(BlockModel original) { + if (!RenderMaterials.ARE_SUPPORTED) + return original; - for (BlockElement element : original.getElements()) { - String renderType = ((BlockElementExt) element).portalcubed$getRenderType(); - if (renderType != null) { - MultiRenderTypeSimpleBakedModel.parseType(renderType); - } - } - return original; - } + for (BlockElement element : original.getElements()) { + String renderType = ((BlockElementExt) element).portalcubed$getRenderType(); + if (renderType != null) { + MultiRenderTypeSimpleBakedModel.parseType(renderType); + } + } + return original; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/CameraMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/CameraMixin.java index 3b3185a4..43187929 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/CameraMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/CameraMixin.java @@ -19,57 +19,57 @@ @Mixin(Camera.class) public abstract class CameraMixin implements CameraExt { - @Shadow - private BlockGetter level; - @Shadow - @Final - private BlockPos.MutableBlockPos blockPosition; + @Shadow + private BlockGetter level; + @Shadow + @Final + private BlockPos.MutableBlockPos blockPosition; - @Shadow private Entity entity; + @Shadow private Entity entity; - @Shadow private boolean initialized; + @Shadow private boolean initialized; - @Shadow protected abstract void move(double distanceOffset, double verticalOffset, double horizontalOffset); + @Shadow protected abstract void move(double distanceOffset, double verticalOffset, double horizontalOffset); - @Shadow protected abstract double getMaxZoom(double startingDistance); + @Shadow protected abstract double getMaxZoom(double startingDistance); - @Shadow protected abstract void setPosition(Vec3 pos); - @Shadow protected abstract void setRotation(float yaw, float pitch); + @Shadow protected abstract void setPosition(Vec3 pos); + @Shadow protected abstract void setRotation(float yaw, float pitch); - @Inject(method = "setup", at = @At("RETURN")) - private void portalCubed$redirectSetup(BlockGetter level, Entity entity, boolean detached, boolean thirdPersonReverse, float partialTick, CallbackInfo ci) { - var cameraType = CameraType.FIRST_PERSON; - if (detached) { - cameraType = thirdPersonReverse ? CameraType.THIRD_PERSON_FRONT : CameraType.THIRD_PERSON_BACK; - } - final Camera camera = (Camera)(Object)this; - final CameraControl ctrl = new CameraControl(camera.getPosition(), camera.getYRot(), camera.getXRot()); - PortalCubedClient.moveCameraIfDead(camera, entity, cameraType, partialTick, ctrl); - PortalCubedClient.transformCameraIntersectingPortal(camera, entity, cameraType, partialTick, ctrl); - if (ctrl.getPos() != camera.getPosition()) { - setPosition(ctrl.getPos()); - } - if (ctrl.getYaw() != camera.getYRot() || ctrl.getPitch() != camera.getXRot()) { - setRotation(ctrl.getYaw(), ctrl.getPitch()); - } - } + @Inject(method = "setup", at = @At("RETURN")) + private void portalCubed$redirectSetup(BlockGetter level, Entity entity, boolean detached, boolean thirdPersonReverse, float partialTick, CallbackInfo ci) { + var cameraType = CameraType.FIRST_PERSON; + if (detached) { + cameraType = thirdPersonReverse ? CameraType.THIRD_PERSON_FRONT : CameraType.THIRD_PERSON_BACK; + } + final Camera camera = (Camera)(Object)this; + final CameraControl ctrl = new CameraControl(camera.getPosition(), camera.getYRot(), camera.getXRot()); + PortalCubedClient.moveCameraIfDead(camera, entity, cameraType, partialTick, ctrl); + PortalCubedClient.transformCameraIntersectingPortal(camera, entity, cameraType, partialTick, ctrl); + if (ctrl.getPos() != camera.getPosition()) { + setPosition(ctrl.getPos()); + } + if (ctrl.getYaw() != camera.getYRot() || ctrl.getPitch() != camera.getXRot()) { + setRotation(ctrl.getYaw(), ctrl.getPitch()); + } + } - @Override - public FluidState portalcubed$getSubmergedFluidState() { - return this.level.getFluidState(blockPosition); - } + @Override + public FluidState portalcubed$getSubmergedFluidState() { + return this.level.getFluidState(blockPosition); + } - @Override - public void updateSimple(BlockGetter area, Entity focusedEntity) { - this.level = area; - this.entity = focusedEntity; - initialized = true; - } + @Override + public void updateSimple(BlockGetter area, Entity focusedEntity) { + this.level = area; + this.entity = focusedEntity; + initialized = true; + } - @Override - public void backCameraUp(Vec3 from) { - setPosition(from); - move(-getMaxZoom(4), 0, 0); - } + @Override + public void backCameraUp(Vec3 from) { + setPosition(from); + move(-getMaxZoom(4), 0, 0); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientAdvancementMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientAdvancementMixin.java index 975e5763..a6fadd14 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientAdvancementMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientAdvancementMixin.java @@ -13,17 +13,17 @@ @Mixin(ClientAdvancements.class) public class ClientAdvancementMixin { - @Inject( - method = "update", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/network/protocol/game/ClientboundUpdateAdvancementsPacket;shouldReset()Z", - ordinal = 1 - ) - ) - private void addGlobalAdvancement(ClientboundUpdateAdvancementsPacket packet, CallbackInfo ci, @Local Advancement advancement, @Local AdvancementProgress advancementProgress) { - if (advancementProgress.isDone()) { - PortalCubedClient.addGlobalAdvancement(advancement.getId()); - } - } + @Inject( + method = "update", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/network/protocol/game/ClientboundUpdateAdvancementsPacket;shouldReset()Z", + ordinal = 1 + ) + ) + private void addGlobalAdvancement(ClientboundUpdateAdvancementsPacket packet, CallbackInfo ci, @Local Advancement advancement, @Local AdvancementProgress advancementProgress) { + if (advancementProgress.isDone()) { + PortalCubedClient.addGlobalAdvancement(advancement.getId()); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientLevelMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientLevelMixin.java index 7c98930e..7a18058a 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientLevelMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientLevelMixin.java @@ -17,23 +17,23 @@ @Mixin(ClientLevel.class) public class ClientLevelMixin { - @WrapOperation( - method = "getMarkerParticleTarget", - at = @At( - value = "INVOKE", - target = "Ljava/util/Set;contains(Ljava/lang/Object;)Z" - ), - require = 0 - ) - private static boolean specialHiddenBlocks(Set instance, Object item, Operation original) { - if (item instanceof BlockItem blockItem && blockItem.getBlock() instanceof SpecialHiddenBlock) { - return !PortalCubedClient.hiddenBlocksVisible(); - } - return original.call(instance, item); - } + @WrapOperation( + method = "getMarkerParticleTarget", + at = @At( + value = "INVOKE", + target = "Ljava/util/Set;contains(Ljava/lang/Object;)Z" + ), + require = 0 + ) + private static boolean specialHiddenBlocks(Set instance, Object item, Operation original) { + if (item instanceof BlockItem blockItem && blockItem.getBlock() instanceof SpecialHiddenBlock) { + return !PortalCubedClient.hiddenBlocksVisible(); + } + return original.call(instance, item); + } - @ModifyReturnValue(method = "entitiesForRendering", at = @At("TAIL")) - private Iterable wrapRenderedEntityIterator(Iterable entities) { - return () -> new LateRenderedEntitySortingIterator(entities.iterator()); - } + @ModifyReturnValue(method = "entitiesForRendering", at = @At("TAIL")) + private Iterable wrapRenderedEntityIterator(Iterable entities) { + return () -> new LateRenderedEntitySortingIterator(entities.iterator()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientPacketListenerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientPacketListenerMixin.java index 8a7de6eb..47b2be72 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientPacketListenerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ClientPacketListenerMixin.java @@ -10,14 +10,14 @@ @Mixin(ClientPacketListener.class) public class ClientPacketListenerMixin { - @WrapOperation( - method = "handlePlayerCombatKill", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/player/LocalPlayer;shouldShowDeathScreen()Z" - ) - ) - private boolean portal2Death(LocalPlayer instance, Operation original) { - return PortalCubedClient.isPortalHudMode() || original.call(instance); - } + @WrapOperation( + method = "handlePlayerCombatKill", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/player/LocalPlayer;shouldShowDeathScreen()Z" + ) + ) + private boolean portal2Death(LocalPlayer instance, Operation original) { + return PortalCubedClient.isPortalHudMode() || original.call(instance); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenAccessor.java index 4f55eb1f..0f0de752 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenAccessor.java @@ -6,6 +6,6 @@ @Mixin(DeathScreen.class) public interface DeathScreenAccessor { - @Accessor - int getDelayTicker(); + @Accessor + int getDelayTicker(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenMixin.java index 094e511b..75a6a9ff 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/DeathScreenMixin.java @@ -13,40 +13,40 @@ @Mixin(DeathScreen.class) public class DeathScreenMixin extends Screen { - @Shadow private int delayTicker; + @Shadow private int delayTicker; - protected DeathScreenMixin(Component title) { - super(title); - throw new AssertionError(); - } + protected DeathScreenMixin(Component title) { + super(title); + throw new AssertionError(); + } - @Inject(method = "init", at = @At("HEAD"), cancellable = true) - private void noDeathScreenI(CallbackInfo ci) { - assert minecraft != null; - if (PortalCubedClient.isPortalHudMode()) { - delayTicker = 0; - ci.cancel(); - } - } + @Inject(method = "init", at = @At("HEAD"), cancellable = true) + private void noDeathScreenI(CallbackInfo ci) { + assert minecraft != null; + if (PortalCubedClient.isPortalHudMode()) { + delayTicker = 0; + ci.cancel(); + } + } - @Inject(method = "render", at = @At("HEAD"), cancellable = true) - private void noDeathScreenR(GuiGraphics graphics, int mouseX, int mouseY, float delta, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - assert minecraft != null; - minecraft.mouseHandler.grabMouse(); - ci.cancel(); - } - } + @Inject(method = "render", at = @At("HEAD"), cancellable = true) + private void noDeathScreenR(GuiGraphics graphics, int mouseX, int mouseY, float delta, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + assert minecraft != null; + minecraft.mouseHandler.grabMouse(); + ci.cancel(); + } + } - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - assert minecraft != null; - assert minecraft.player != null; - if (PortalCubedClient.isPortalHudMode() && delayTicker >= (minecraft.player.shouldShowDeathScreen() ? 20 : 0)) { - minecraft.player.respawn(); - minecraft.setScreen(null); - return true; - } - return super.keyPressed(keyCode, scanCode, modifiers); - } + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + assert minecraft != null; + assert minecraft.player != null; + if (PortalCubedClient.isPortalHudMode() && delayTicker >= (minecraft.player.shouldShowDeathScreen() ? 20 : 0)) { + minecraft.player.respawn(); + minecraft.setScreen(null); + return true; + } + return super.keyPressed(keyCode, scanCode, modifiers); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/FogRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/FogRendererMixin.java index 90fa7a13..54de0373 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/FogRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/FogRendererMixin.java @@ -19,107 +19,107 @@ @Mixin(FogRenderer.class) public abstract class FogRendererMixin { - @Shadow - private static float fogRed; - @Shadow - private static float fogGreen; - @Shadow - private static float fogBlue; - @Shadow - private static long biomeChangedTime; - - @Inject(method = "setupColor", at = @At("HEAD"), cancellable = true) - private static void renderToxicGooFog(Camera camera, float tickDelta, ClientLevel world, int viewDistance, float skyDarkness, CallbackInfo ci) { - FluidState cameraSubmergedFluidState = ((CameraExt) camera).portalcubed$getSubmergedFluidState(); - - if (cameraSubmergedFluidState.getType() instanceof ToxicGooFluid) { - ci.cancel(); - - // Dark brownish "red" - fogRed = 99 / 255f; - fogGreen = 29 / 255f; - fogBlue = 1 / 255f; - - biomeChangedTime = -1L; - - // Dark brownish "red" - RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0f); - } - } - - @Inject( - method = "setupColor", - at = @At( - value = "INVOKE", - target = "Ljava/lang/Math;pow(DD)D" - ), - cancellable = true - ) - private static void renderPortalFog(Camera camera, float tickDelta, ClientLevel world, int viewDistance, float skyDarkness, CallbackInfo ci) { - final FogSettings fog = PortalCubedClient.customFog; - if (fog != null) { - ci.cancel(); - - fogRed = fog.color().r() / 255f; - fogGreen = fog.color().g() / 255f; - fogBlue = fog.color().b() / 255f; - - RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0f); - } - } - - @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) - private static void applyToxicGooFog(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { - FluidState cameraSubmergedFluidState = ((CameraExt) camera).portalcubed$getSubmergedFluidState(); - - if (cameraSubmergedFluidState.getType() instanceof ToxicGooFluid) { - ci.cancel(); - - if (camera.getEntity().isSpectator()) { - RenderSystem.setShaderFogStart(-8.0F); - RenderSystem.setShaderFogEnd(viewDistance * 0.5F); - } else { - // Same fog as lava with fire resistance - RenderSystem.setShaderFogStart(0.0F); - RenderSystem.setShaderFogEnd(3.0F); - } - RenderSystem.setShaderFogShape(FogShape.SPHERE); - } - } - - @Inject( - method = "setupFog", - at = @At( - value = "FIELD", - target = "Lnet/minecraft/client/renderer/FogRenderer$FogMode;FOG_SKY:Lnet/minecraft/client/renderer/FogRenderer$FogMode;", - opcode = Opcodes.GETSTATIC - ), - cancellable = true - ) - private static void applyPortalFog1(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { - applyPortalFog0(ci); - } - - @Inject( - method = "setupFog", - at = @At( - value = "INVOKE", - target = "Ljava/lang/Math;min(FF)F" - ), - cancellable = true - ) - private static void applyPortalFog2(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { - applyPortalFog0(ci); - } - - private static void applyPortalFog0(CallbackInfo ci) { - final FogSettings fog = PortalCubedClient.customFog; - if (fog != null) { - ci.cancel(); - - RenderSystem.setShaderFogStart(fog.start()); - RenderSystem.setShaderFogEnd(fog.end()); - RenderSystem.setShaderFogShape(fog.shape().toBlaze3d()); - } - } + @Shadow + private static float fogRed; + @Shadow + private static float fogGreen; + @Shadow + private static float fogBlue; + @Shadow + private static long biomeChangedTime; + + @Inject(method = "setupColor", at = @At("HEAD"), cancellable = true) + private static void renderToxicGooFog(Camera camera, float tickDelta, ClientLevel world, int viewDistance, float skyDarkness, CallbackInfo ci) { + FluidState cameraSubmergedFluidState = ((CameraExt) camera).portalcubed$getSubmergedFluidState(); + + if (cameraSubmergedFluidState.getType() instanceof ToxicGooFluid) { + ci.cancel(); + + // Dark brownish "red" + fogRed = 99 / 255f; + fogGreen = 29 / 255f; + fogBlue = 1 / 255f; + + biomeChangedTime = -1L; + + // Dark brownish "red" + RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0f); + } + } + + @Inject( + method = "setupColor", + at = @At( + value = "INVOKE", + target = "Ljava/lang/Math;pow(DD)D" + ), + cancellable = true + ) + private static void renderPortalFog(Camera camera, float tickDelta, ClientLevel world, int viewDistance, float skyDarkness, CallbackInfo ci) { + final FogSettings fog = PortalCubedClient.customFog; + if (fog != null) { + ci.cancel(); + + fogRed = fog.color().r() / 255f; + fogGreen = fog.color().g() / 255f; + fogBlue = fog.color().b() / 255f; + + RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0f); + } + } + + @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) + private static void applyToxicGooFog(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { + FluidState cameraSubmergedFluidState = ((CameraExt) camera).portalcubed$getSubmergedFluidState(); + + if (cameraSubmergedFluidState.getType() instanceof ToxicGooFluid) { + ci.cancel(); + + if (camera.getEntity().isSpectator()) { + RenderSystem.setShaderFogStart(-8.0F); + RenderSystem.setShaderFogEnd(viewDistance * 0.5F); + } else { + // Same fog as lava with fire resistance + RenderSystem.setShaderFogStart(0.0F); + RenderSystem.setShaderFogEnd(3.0F); + } + RenderSystem.setShaderFogShape(FogShape.SPHERE); + } + } + + @Inject( + method = "setupFog", + at = @At( + value = "FIELD", + target = "Lnet/minecraft/client/renderer/FogRenderer$FogMode;FOG_SKY:Lnet/minecraft/client/renderer/FogRenderer$FogMode;", + opcode = Opcodes.GETSTATIC + ), + cancellable = true + ) + private static void applyPortalFog1(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { + applyPortalFog0(ci); + } + + @Inject( + method = "setupFog", + at = @At( + value = "INVOKE", + target = "Ljava/lang/Math;min(FF)F" + ), + cancellable = true + ) + private static void applyPortalFog2(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, float tickDelta, CallbackInfo ci) { + applyPortalFog0(ci); + } + + private static void applyPortalFog0(CallbackInfo ci) { + final FogSettings fog = PortalCubedClient.customFog; + if (fog != null) { + ci.cancel(); + + RenderSystem.setShaderFogStart(fog.start()); + RenderSystem.setShaderFogEnd(fog.end()); + RenderSystem.setShaderFogShape(fog.shape().toBlaze3d()); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/GameRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/GameRendererMixin.java index 31e7e6ea..f5b1935f 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/GameRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/GameRendererMixin.java @@ -24,52 +24,52 @@ @Mixin(GameRenderer.class) public abstract class GameRendererMixin implements GameRendererExt { - @Shadow - @Final - Minecraft minecraft; + @Shadow + @Final + Minecraft minecraft; - @Mutable - @Shadow @Final private Camera mainCamera; + @Mutable + @Shadow @Final private Camera mainCamera; - @ModifyReturnValue(method = "getFov", at = @At("RETURN")) - private double portalCubed$modifyFov(double org) { - var fov = new MutableDouble(org); - PortalCubedClient.zoomGoBrrrr(fov); - return fov.getValue(); - } + @ModifyReturnValue(method = "getFov", at = @At("RETURN")) + private double portalCubed$modifyFov(double org) { + var fov = new MutableDouble(org); + PortalCubedClient.zoomGoBrrrr(fov); + return fov.getValue(); + } - @WrapOperation( - method = "pick", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/entity/projectile/ProjectileUtil;getEntityHitResult(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/phys/AABB;Ljava/util/function/Predicate;D)Lnet/minecraft/world/phys/EntityHitResult;" - ) - ) - private EntityHitResult portalCubed$portalCompatibleEntityRaycast(Entity entity, Vec3 min, Vec3 max, AABB box, Predicate predicate, double d, Operation original) { - if (minecraft.hitResult instanceof AdvancedRaycastResultHolder resultHolder && resultHolder.getResult().isPresent()) { - return resultHolder.getResult().get().entityRaycast(entity, predicate); - } else { - return original.call(entity, min, max, box, predicate, d); - } - } + @WrapOperation( + method = "pick", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/entity/projectile/ProjectileUtil;getEntityHitResult(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/phys/AABB;Ljava/util/function/Predicate;D)Lnet/minecraft/world/phys/EntityHitResult;" + ) + ) + private EntityHitResult portalCubed$portalCompatibleEntityRaycast(Entity entity, Vec3 min, Vec3 max, AABB box, Predicate predicate, double d, Operation original) { + if (minecraft.hitResult instanceof AdvancedRaycastResultHolder resultHolder && resultHolder.getResult().isPresent()) { + return resultHolder.getResult().get().entityRaycast(entity, predicate); + } else { + return original.call(entity, min, max, box, predicate, d); + } + } - @WrapOperation( - method = {"getFov", "bobViewWhenHurt"}, - at = @At( - value = "INVOKE", - target = "Ljava/lang/Math;min(FF)F", - remap = false - ) - ) - private float noDeathEffects(float a, float b, Operation original) { - if (PortalCubedClient.isPortalHudMode()) { - return 0; - } - return original.call(a, b); - } + @WrapOperation( + method = {"getFov", "bobViewWhenHurt"}, + at = @At( + value = "INVOKE", + target = "Ljava/lang/Math;min(FF)F", + remap = false + ) + ) + private float noDeathEffects(float a, float b, Operation original) { + if (PortalCubedClient.isPortalHudMode()) { + return 0; + } + return original.call(a, b); + } - @Override - public void setMainCamera(Camera camera) { - mainCamera = camera; - } + @Override + public void setMainCamera(Camera camera) { + mainCamera = camera; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/GuiMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/GuiMixin.java index 89b163f3..087b4b9f 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/GuiMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/GuiMixin.java @@ -11,38 +11,38 @@ @Mixin(Gui.class) public class GuiMixin { - @Inject(method = "renderHotbar", at = @At("HEAD"), cancellable = true) - private void notWithPortalHudRH(float tickDelta, GuiGraphics graphics, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderHotbar", at = @At("HEAD"), cancellable = true) + private void notWithPortalHudRH(float tickDelta, GuiGraphics graphics, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } - @Inject(method = "renderPlayerHealth", at = @At("HEAD"), cancellable = true) - private void notWithPortalHudRSB(GuiGraphics graphics, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderPlayerHealth", at = @At("HEAD"), cancellable = true) + private void notWithPortalHudRSB(GuiGraphics graphics, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } - @Inject(method = "renderVehicleHealth", at = @At("HEAD"), cancellable = true) - private void notWithPortalHudRMH(GuiGraphics graphics, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderVehicleHealth", at = @At("HEAD"), cancellable = true) + private void notWithPortalHudRMH(GuiGraphics graphics, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } - @Inject(method = "renderJumpMeter", at = @At("HEAD"), cancellable = true) - private void notWithPortalHudRMJB(PlayerRideableJumping rideable, GuiGraphics graphics, int x, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderJumpMeter", at = @At("HEAD"), cancellable = true) + private void notWithPortalHudRMJB(PlayerRideableJumping rideable, GuiGraphics graphics, int x, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } - @Inject(method = "renderExperienceBar", at = @At("HEAD"), cancellable = true) - private void notWithPortalHudREB(GuiGraphics graphics, int x, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderExperienceBar", at = @At("HEAD"), cancellable = true) + private void notWithPortalHudREB(GuiGraphics graphics, int x, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemEntityRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemEntityRendererMixin.java index 8cdecd02..158decfc 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemEntityRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemEntityRendererMixin.java @@ -19,61 +19,61 @@ @Mixin(ItemEntityRenderer.class) public class ItemEntityRendererMixin { - @Inject( - method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", - at = @At("HEAD") - ) - private void laysOnFloor( - ItemEntity itemEntity, - float f, - float g, - PoseStack matrixStack, - MultiBufferSource vertexConsumerProvider, - int i, - CallbackInfo ci, - @Share("laysOnFloor") LocalBooleanRef laysOnFloor - ) { - if (!PortalCubedConfig.staticPortalItemDrops) { - laysOnFloor.set(false); - return; - } - final ItemStack stack = itemEntity.getItem(); - laysOnFloor.set(stack.getCount() == 1 && stack.is(PortalCubedItems.LAYS_ON_FLOOR)); - } + @Inject( + method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", + at = @At("HEAD") + ) + private void laysOnFloor( + ItemEntity itemEntity, + float f, + float g, + PoseStack matrixStack, + MultiBufferSource vertexConsumerProvider, + int i, + CallbackInfo ci, + @Share("laysOnFloor") LocalBooleanRef laysOnFloor + ) { + if (!PortalCubedConfig.staticPortalItemDrops) { + laysOnFloor.set(false); + return; + } + final ItemStack stack = itemEntity.getItem(); + laysOnFloor.set(stack.getCount() == 1 && stack.is(PortalCubedItems.LAYS_ON_FLOOR)); + } - @WrapOperation( - method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", - at = @At( - value = "INVOKE", - target = "Lcom/mojang/blaze3d/vertex/PoseStack;translate(FFF)V", - ordinal = 0 - ) - ) - private void dontTranslate( - PoseStack instance, - float x, - float y, - float z, - Operation original, - @Share("laysOnFloor") LocalBooleanRef laysOnFloor, - @Local(ordinal = 2) float yOffset - ) { - original.call(instance, x, laysOnFloor.get() ? 0.25f * yOffset : y, z); - } + @WrapOperation( + method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", + at = @At( + value = "INVOKE", + target = "Lcom/mojang/blaze3d/vertex/PoseStack;translate(FFF)V", + ordinal = 0 + ) + ) + private void dontTranslate( + PoseStack instance, + float x, + float y, + float z, + Operation original, + @Share("laysOnFloor") LocalBooleanRef laysOnFloor, + @Local(ordinal = 2) float yOffset + ) { + original.call(instance, x, laysOnFloor.get() ? 0.25f * yOffset : y, z); + } - @WrapOperation( - method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/entity/item/ItemEntity;getSpin(F)F" - ) - ) - private float dontRotate( - ItemEntity instance, - float tickDelta, - Operation original, - @Share("laysOnFloor") LocalBooleanRef laysOnFloor - ) { - return laysOnFloor.get() ? instance.bobOffs : original.call(instance, tickDelta); - } + @WrapOperation( + method = "render(Lnet/minecraft/world/entity/item/ItemEntity;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/entity/item/ItemEntity;getSpin(F)F" + ) + ) + private float dontRotate( + ItemEntity instance, + float tickDelta, + Operation original, + @Share("laysOnFloor") LocalBooleanRef laysOnFloor + ) { + return laysOnFloor.get() ? instance.bobOffs : original.call(instance, tickDelta); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemInHandRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemInHandRendererMixin.java index 8194ec22..c3103124 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemInHandRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ItemInHandRendererMixin.java @@ -27,73 +27,73 @@ @Mixin(ItemInHandRenderer.class) public class ItemInHandRendererMixin implements ItemInHandRendererExt { - @Shadow @Final private Minecraft minecraft; + @Shadow @Final private Minecraft minecraft; - @Unique - private boolean isHoldingInvisible; - @Unique - private boolean handFaker; + @Unique + private boolean isHoldingInvisible; + @Unique + private boolean handFaker; - @Inject( - method = "renderArmWithItem", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderItem(Lnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemDisplayContext;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", - ordinal = 1 - ) - ) - private void shakeGun(AbstractClientPlayer player, float tickDelta, float pitch, InteractionHand hand, float swingProgress, ItemStack item, float equipProgress, PoseStack matrices, MultiBufferSource vertexConsumers, int light, CallbackInfo ci) { - final long time = Util.getMillis() - PortalCubedClient.shakeStart; - if (time > 440) return; - matrices.mulPose(Axis.ZP.rotationDegrees((float)Math.sin(time / 35.0) * 6)); - } + @Inject( + method = "renderArmWithItem", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderItem(Lnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemDisplayContext;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", + ordinal = 1 + ) + ) + private void shakeGun(AbstractClientPlayer player, float tickDelta, float pitch, InteractionHand hand, float swingProgress, ItemStack item, float equipProgress, PoseStack matrices, MultiBufferSource vertexConsumers, int light, CallbackInfo ci) { + final long time = Util.getMillis() - PortalCubedClient.shakeStart; + if (time > 440) return; + matrices.mulPose(Axis.ZP.rotationDegrees((float)Math.sin(time / 35.0) * 6)); + } - @Inject( - method = "tick", - at = @At( - value = "FIELD", - target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;mainHandItem:Lnet/minecraft/world/item/ItemStack;", - opcode = Opcodes.PUTFIELD, - ordinal = 1 - ) - ) - private void isHoldingInvisible(CallbackInfo ci) { - assert minecraft.player != null; - isHoldingInvisible = - !minecraft.player.getMainHandItem().is(PortalCubedItems.HOLDS_OBJECT) && - PortalCubedComponents.HOLDER_COMPONENT.get(minecraft.player).entityBeingHeld() != null; - handFaker = false; - } + @Inject( + method = "tick", + at = @At( + value = "FIELD", + target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;mainHandItem:Lnet/minecraft/world/item/ItemStack;", + opcode = Opcodes.PUTFIELD, + ordinal = 1 + ) + ) + private void isHoldingInvisible(CallbackInfo ci) { + assert minecraft.player != null; + isHoldingInvisible = + !minecraft.player.getMainHandItem().is(PortalCubedItems.HOLDS_OBJECT) && + PortalCubedComponents.HOLDER_COMPONENT.get(minecraft.player).entityBeingHeld() != null; + handFaker = false; + } - @Inject(method = "renderArmWithItem", at = @At("HEAD"), cancellable = true) - private void noHandObject(AbstractClientPlayer player, float tickDelta, float pitch, InteractionHand hand, float swingProgress, ItemStack item, float equipProgress, PoseStack matrices, MultiBufferSource vertexConsumers, int light, CallbackInfo ci) { - if (hand == InteractionHand.MAIN_HAND && isHoldingInvisible) { - ci.cancel(); - } - } + @Inject(method = "renderArmWithItem", at = @At("HEAD"), cancellable = true) + private void noHandObject(AbstractClientPlayer player, float tickDelta, float pitch, InteractionHand hand, float swingProgress, ItemStack item, float equipProgress, PoseStack matrices, MultiBufferSource vertexConsumers, int light, CallbackInfo ci) { + if (hand == InteractionHand.MAIN_HAND && isHoldingInvisible) { + ci.cancel(); + } + } - @Inject(method = "renderPlayerArm", at = @At("HEAD"), cancellable = true) - private void noHandHud(PoseStack matrices, MultiBufferSource vertexConsumers, int light, float equipProgress, float swingProgress, HumanoidArm arm, CallbackInfo ci) { - if (PortalCubedClient.isPortalHudMode()) { - ci.cancel(); - } - } + @Inject(method = "renderPlayerArm", at = @At("HEAD"), cancellable = true) + private void noHandHud(PoseStack matrices, MultiBufferSource vertexConsumers, int light, float equipProgress, float swingProgress, HumanoidArm arm, CallbackInfo ci) { + if (PortalCubedClient.isPortalHudMode()) { + ci.cancel(); + } + } - @WrapOperation( - method = "tick", - at = @At( - value = "FIELD", - target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;mainHandItem:Lnet/minecraft/world/item/ItemStack;", - opcode = Opcodes.GETFIELD, - ordinal = 1 - ) - ) - private ItemStack handFaker(ItemInHandRenderer instance, Operation original) { - return handFaker ? null : original.call(instance); - } + @WrapOperation( + method = "tick", + at = @At( + value = "FIELD", + target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;mainHandItem:Lnet/minecraft/world/item/ItemStack;", + opcode = Opcodes.GETFIELD, + ordinal = 1 + ) + ) + private ItemStack handFaker(ItemInHandRenderer instance, Operation original) { + return handFaker ? null : original.call(instance); + } - @Override - public void startHandFaker() { - handFaker = true; - } + @Override + public void startHandFaker() { + handFaker = true; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyMappingAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyMappingAccessor.java index ca66600d..c5027da4 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyMappingAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyMappingAccessor.java @@ -9,8 +9,8 @@ @Mixin(KeyMapping.class) public interface KeyMappingAccessor { - @Accessor("MAP") - static Map getMAP() { - throw new AssertionError(); - } + @Accessor("MAP") + static Map getMAP() { + throw new AssertionError(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardHandlerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardHandlerMixin.java index 3aee82ab..a9109f5f 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardHandlerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardHandlerMixin.java @@ -16,20 +16,20 @@ @Mixin(KeyboardHandler.class) public class KeyboardHandlerMixin { - @Shadow @Final private Minecraft minecraft; + @Shadow @Final private Minecraft minecraft; - @WrapWithCondition( - method = "keyPress", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/KeyMapping;click(Lcom/mojang/blaze3d/platform/InputConstants$Key;)V" - ) - ) - private boolean dontSpamGrab(InputConstants.Key instance, long window, int key, int scancode, int action, int modifiers) { - if (action != GLFW_REPEAT) { - return true; - } - final KeyMapping keybind = KeyMappingAccessor.getMAP().get(instance); - return keybind != PortalCubedKeyBindings.GRAB && (!PortalCubedClient.isPortalHudMode() || keybind != minecraft.options.keyInventory); - } + @WrapWithCondition( + method = "keyPress", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/KeyMapping;click(Lcom/mojang/blaze3d/platform/InputConstants$Key;)V" + ) + ) + private boolean dontSpamGrab(InputConstants.Key instance, long window, int key, int scancode, int action, int modifiers) { + if (action != GLFW_REPEAT) { + return true; + } + final KeyMapping keybind = KeyMappingAccessor.getMAP().get(instance); + return keybind != PortalCubedKeyBindings.GRAB && (!PortalCubedClient.isPortalHudMode() || keybind != minecraft.options.keyInventory); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardInputMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardInputMixin.java index dc66e0d0..569c58cf 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardInputMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/KeyboardInputMixin.java @@ -13,19 +13,19 @@ @Mixin(KeyboardInput.class) public class KeyboardInputMixin { - @Shadow @Final private Options options; + @Shadow @Final private Options options; - @WrapOperation( - method = "tick", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/KeyMapping;isDown()Z" - ) - ) - private boolean ctrlToCrouch(KeyMapping instance, Operation original) { - if (instance != options.keyShift || !PortalCubedClient.isPortalHudMode()) { - return original.call(instance); - } - return original.call(instance) || options.keySprint.isDown(); - } + @WrapOperation( + method = "tick", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/KeyMapping;isDown()Z" + ) + ) + private boolean ctrlToCrouch(KeyMapping instance, Operation original) { + if (instance != options.keyShift || !PortalCubedClient.isPortalHudMode()) { + return original.call(instance); + } + return original.call(instance) || options.keySprint.isDown(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/LevelRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/LevelRendererMixin.java index cfa833d3..ea76f899 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/LevelRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/LevelRendererMixin.java @@ -29,100 +29,100 @@ @Mixin(LevelRenderer.class) public class LevelRendererMixin implements LevelRendererExt { - @Shadow private Frustum cullingFrustum; + @Shadow private Frustum cullingFrustum; - @Mutable - @Shadow @Final private RenderBuffers renderBuffers; + @Mutable + @Shadow @Final private RenderBuffers renderBuffers; - @Shadow @Final private Minecraft minecraft; + @Shadow @Final private Minecraft minecraft; - @Shadow private @Nullable ClientLevel level; + @Shadow private @Nullable ClientLevel level; - @Inject(method = "prepareCullFrustum", at = @At("HEAD")) - private void modifyCameraRotation(PoseStack poseStack, Vec3 cameraPos, Matrix4f projectionMatrix, CallbackInfo ci) { - PortalCubedClient.interpCamera().ifPresent(q -> poseStack.mulPose(q.toQuaternionf())); - if (PortalCubedClient.cameraTransformedThroughPortal != null && !minecraft.gameRenderer.getMainCamera().isDetached()) { - poseStack.mulPose(PortalCubedClient.cameraTransformedThroughPortal.getTransformQuat().toQuaternionf().conjugate()); - } - } + @Inject(method = "prepareCullFrustum", at = @At("HEAD")) + private void modifyCameraRotation(PoseStack poseStack, Vec3 cameraPos, Matrix4f projectionMatrix, CallbackInfo ci) { + PortalCubedClient.interpCamera().ifPresent(q -> poseStack.mulPose(q.toQuaternionf())); + if (PortalCubedClient.cameraTransformedThroughPortal != null && !minecraft.gameRenderer.getMainCamera().isDetached()) { + poseStack.mulPose(PortalCubedClient.cameraTransformedThroughPortal.getTransformQuat().toQuaternionf().conjugate()); + } + } - @Override - public Frustum getCullingFrustum() { - return cullingFrustum; - } + @Override + public Frustum getCullingFrustum() { + return cullingFrustum; + } - @Override - public void setCullingFrustum(Frustum cullingFrustum) { - this.cullingFrustum = cullingFrustum; - } + @Override + public void setCullingFrustum(Frustum cullingFrustum) { + this.cullingFrustum = cullingFrustum; + } - @Override - public RenderBuffers getRenderBuffers() { - return renderBuffers; - } + @Override + public RenderBuffers getRenderBuffers() { + return renderBuffers; + } - @Override - public void setRenderBuffers(RenderBuffers renderBuffers) { - this.renderBuffers = renderBuffers; - } + @Override + public void setRenderBuffers(RenderBuffers renderBuffers) { + this.renderBuffers = renderBuffers; + } - @WrapOperation( - method = "renderLevel", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/Camera;isDetached()Z" - ) - ) - private boolean overrideDetached(Camera instance, Operation original) { - return PortalCubedClient.cameraTransformedThroughPortal != null || original.call(instance); - } + @WrapOperation( + method = "renderLevel", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/Camera;isDetached()Z" + ) + ) + private boolean overrideDetached(Camera instance, Operation original) { + return PortalCubedClient.cameraTransformedThroughPortal != null || original.call(instance); + } - @Inject( - method = "renderLevel", - at = @At("RETURN") - ) - private void renderEndNoFapi( - PoseStack poseStack, - float partialTick, - long finishNanoTime, - boolean renderBlockOutline, - Camera camera, - GameRenderer gameRenderer, - LightTexture lightTexture, - Matrix4f projectionMatrix, - CallbackInfo ci - ) { - assert level != null; + @Inject( + method = "renderLevel", + at = @At("RETURN") + ) + private void renderEndNoFapi( + PoseStack poseStack, + float partialTick, + long finishNanoTime, + boolean renderBlockOutline, + Camera camera, + GameRenderer gameRenderer, + LightTexture lightTexture, + Matrix4f projectionMatrix, + CallbackInfo ci + ) { + assert level != null; - if (PortalCubedClient.getRenderer().targetPhase() != PortalRenderPhase.FINAL) return; - final MultiBufferSource.BufferSource consumers = renderBuffers.bufferSource(); - final var cameraPos = camera.getPosition(); - poseStack.pushPose(); - poseStack.translate(-cameraPos.x, -cameraPos.y, -cameraPos.z); - final PortalRenderPhase oldRenderPhase = PortalRenderer.renderPhase; - PortalRenderer.renderPhase = PortalRenderPhase.FINAL; + if (PortalCubedClient.getRenderer().targetPhase() != PortalRenderPhase.FINAL) return; + final MultiBufferSource.BufferSource consumers = renderBuffers.bufferSource(); + final var cameraPos = camera.getPosition(); + poseStack.pushPose(); + poseStack.translate(-cameraPos.x, -cameraPos.y, -cameraPos.z); + final PortalRenderPhase oldRenderPhase = PortalRenderer.renderPhase; + PortalRenderer.renderPhase = PortalRenderPhase.FINAL; - final EntityRenderDispatcher dispatcher = minecraft.getEntityRenderDispatcher(); - for (final Entity entity : level.entitiesForRendering()) { - if (!(entity instanceof Portal portal) || !portal.getActive()) continue; - final PortalRenderer renderer = (PortalRenderer)dispatcher.getRenderer(portal); - renderer.shouldRender(portal, cullingFrustum, cameraPos.x, cameraPos.y, cameraPos.z); - poseStack.pushPose(); - poseStack.translate(entity.getX(), entity.getY(), entity.getZ()); - poseStack.mulPose(portal.getRotation().get(partialTick)); - poseStack.mulPose(Axis.YP.rotationDegrees(180f)); - renderer.renderPortal( - poseStack, - consumers, - portal, - 0, 1, 1, 1, - partialTick - ); - poseStack.popPose(); - } + final EntityRenderDispatcher dispatcher = minecraft.getEntityRenderDispatcher(); + for (final Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof Portal portal) || !portal.getActive()) continue; + final PortalRenderer renderer = (PortalRenderer)dispatcher.getRenderer(portal); + renderer.shouldRender(portal, cullingFrustum, cameraPos.x, cameraPos.y, cameraPos.z); + poseStack.pushPose(); + poseStack.translate(entity.getX(), entity.getY(), entity.getZ()); + poseStack.mulPose(portal.getRotation().get(partialTick)); + poseStack.mulPose(Axis.YP.rotationDegrees(180f)); + renderer.renderPortal( + poseStack, + consumers, + portal, + 0, 1, 1, 1, + partialTick + ); + poseStack.popPose(); + } - poseStack.popPose(); - consumers.endLastBatch(); - PortalRenderer.renderPhase = oldRenderPhase; - } + poseStack.popPose(); + consumers.endLastBatch(); + PortalRenderer.renderPhase = oldRenderPhase; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/LocalPlayerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/LocalPlayerMixin.java index 241017ef..aa5123f1 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/LocalPlayerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/LocalPlayerMixin.java @@ -26,46 +26,46 @@ @Mixin(LocalPlayer.class) public class LocalPlayerMixin extends AbstractClientPlayer implements HasMovementInputAccessor { - @Shadow @Final protected Minecraft minecraft; + @Shadow @Final protected Minecraft minecraft; - @Shadow public Input input; + @Shadow public Input input; - public LocalPlayerMixin(ClientLevel clientLevel, GameProfile gameProfile) { - super(clientLevel, gameProfile); - } + public LocalPlayerMixin(ClientLevel clientLevel, GameProfile gameProfile) { + super(clientLevel, gameProfile); + } - @Override - public boolean hasMovementInputPublic() { - Vec2 vec2f = this.input.getMoveVector(); - return vec2f.x != 0.0F || vec2f.y != 0.0F; - } + @Override + public boolean hasMovementInputPublic() { + Vec2 vec2f = this.input.getMoveVector(); + return vec2f.x != 0.0F || vec2f.y != 0.0F; + } - @Inject( - method = "canStartSprinting", - at = @At("HEAD"), - cancellable = true - ) - private void noSprintingInPortalHud(CallbackInfoReturnable cir) { - if (PortalCubedClient.isPortalHudMode()) { - cir.setReturnValue(false); - } - } + @Inject( + method = "canStartSprinting", + at = @At("HEAD"), + cancellable = true + ) + private void noSprintingInPortalHud(CallbackInfoReturnable cir) { + if (PortalCubedClient.isPortalHudMode()) { + cir.setReturnValue(false); + } + } - @Inject( - method = "suffocatesAt", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/player/LocalPlayer;level()Lnet/minecraft/world/level/Level;" - ), - cancellable = true - ) - private void noSuffocate(BlockPos pos, CallbackInfoReturnable cir, @Local(ordinal = 1) AABB aabb) { - final VoxelShape cutout = CalledValues.getPortalCutout(this); - if (cutout.isEmpty()) return; - if (Shapes.joinIsNotEmpty(Shapes.create(aabb), cutout, BooleanOp.AND)) { - cir.setReturnValue(false); - } - } + @Inject( + method = "suffocatesAt", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/player/LocalPlayer;level()Lnet/minecraft/world/level/Level;" + ), + cancellable = true + ) + private void noSuffocate(BlockPos pos, CallbackInfoReturnable cir, @Local(ordinal = 1) AABB aabb) { + final VoxelShape cutout = CalledValues.getPortalCutout(this); + if (cutout.isEmpty()) return; + if (Shapes.joinIsNotEmpty(Shapes.create(aabb), cutout, BooleanOp.AND)) { + cir.setReturnValue(false); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftAccessor.java index 5fd66458..2ae10ead 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftAccessor.java @@ -8,7 +8,7 @@ @Mixin(Minecraft.class) public interface MinecraftAccessor { - @Mutable - @Accessor("mainRenderTarget") - void setMainRenderTarget(RenderTarget target); + @Mutable + @Accessor("mainRenderTarget") + void setMainRenderTarget(RenderTarget target); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftMixin.java index f190ba30..a9cf45bc 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/MinecraftMixin.java @@ -38,124 +38,124 @@ @Mixin(Minecraft.class) public abstract class MinecraftMixin implements MinecraftExt { - @Shadow @Final public Options options; - @Shadow public LocalPlayer player; - @Shadow - protected abstract void startUseItem(); - @Shadow - protected abstract boolean startAttack(); + @Shadow @Final public Options options; + @Shadow public LocalPlayer player; + @Shadow + protected abstract void startUseItem(); + @Shadow + protected abstract boolean startAttack(); - @Shadow @Nullable public HitResult hitResult; + @Shadow @Nullable public HitResult hitResult; - @Mutable - @Shadow @Final private RenderBuffers renderBuffers; + @Mutable + @Shadow @Final private RenderBuffers renderBuffers; - @Redirect( - method = "handleKeybinds", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/Minecraft;startUseItem()V", - ordinal = 1 - ) - ) - private void portalCubed$stopPortalSpamming(Minecraft self) { - if (!(player != null && player.getMainHandItem().getItem() instanceof PortalGun)) { - startUseItem(); - } - } + @Redirect( + method = "handleKeybinds", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/Minecraft;startUseItem()V", + ordinal = 1 + ) + ) + private void portalCubed$stopPortalSpamming(Minecraft self) { + if (!(player != null && player.getMainHandItem().getItem() instanceof PortalGun)) { + startUseItem(); + } + } - @Inject(method = "continueAttack", at = @At("HEAD"), cancellable = true) - private void portalCubed$fixContinueAttack(boolean leftClick, CallbackInfo ci) { - if (player != null) { - final var heldItem = player.getMainHandItem().getItem(); - if (heldItem instanceof PaintGun && leftClick) startAttack(); - if (heldItem instanceof ClickHandlingItem) ci.cancel(); - } - } + @Inject(method = "continueAttack", at = @At("HEAD"), cancellable = true) + private void portalCubed$fixContinueAttack(boolean leftClick, CallbackInfo ci) { + if (player != null) { + final var heldItem = player.getMainHandItem().getItem(); + if (heldItem instanceof PaintGun && leftClick) startAttack(); + if (heldItem instanceof ClickHandlingItem) ci.cancel(); + } + } - @Inject(method = "startAttack", at = @At("HEAD"), cancellable = true) - private void portalCubed$customLeftClickHandling(CallbackInfoReturnable cir) { - if (player != null && player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { - if (chi.onLeftClick(player, InteractionHand.MAIN_HAND).consumesAction()) { - ClientPlayNetworking.send(PortalCubedServerPackets.LEFT_CLICK, PacketByteBufs.empty()); - cir.setReturnValue(false); - } else { - cir.setReturnValue(false); - } - } - } + @Inject(method = "startAttack", at = @At("HEAD"), cancellable = true) + private void portalCubed$customLeftClickHandling(CallbackInfoReturnable cir) { + if (player != null && player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { + if (chi.onLeftClick(player, InteractionHand.MAIN_HAND).consumesAction()) { + ClientPlayNetworking.send(PortalCubedServerPackets.LEFT_CLICK, PacketByteBufs.empty()); + cir.setReturnValue(false); + } else { + cir.setReturnValue(false); + } + } + } - @Inject(method = "startUseItem", at = @At("HEAD"), cancellable = true) - private void portalCubed$customRightClickHandling(CallbackInfo ci) { - if (player != null && player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { - if (chi.onRightClick(player, InteractionHand.MAIN_HAND).consumesAction()) { - ClientPlayNetworking.send(PortalCubedServerPackets.RIGHT_CLICK, PacketByteBufs.empty()); - ci.cancel(); - } else { - ci.cancel(); - } - } - } + @Inject(method = "startUseItem", at = @At("HEAD"), cancellable = true) + private void portalCubed$customRightClickHandling(CallbackInfo ci) { + if (player != null && player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { + if (chi.onRightClick(player, InteractionHand.MAIN_HAND).consumesAction()) { + ClientPlayNetworking.send(PortalCubedServerPackets.RIGHT_CLICK, PacketByteBufs.empty()); + ci.cancel(); + } else { + ci.cancel(); + } + } + } - @WrapOperation( - method = "handleKeybinds", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/KeyMapping;consumeClick()Z" - ) - ) - private boolean portalHudDisableKeys(KeyMapping instance, Operation original) { - final boolean result = original.call(instance); - if (!PortalCubedClient.isPortalHudMode()) { - return result; - } - for (final KeyMapping bind : options.keyHotbarSlots) { - if (instance == bind) { - return false; - } - } - if ( - instance == options.keyInventory || - instance == options.keySwapOffhand || - instance == options.keyDrop - ) { - return false; - } - return result; - } + @WrapOperation( + method = "handleKeybinds", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/KeyMapping;consumeClick()Z" + ) + ) + private boolean portalHudDisableKeys(KeyMapping instance, Operation original) { + final boolean result = original.call(instance); + if (!PortalCubedClient.isPortalHudMode()) { + return result; + } + for (final KeyMapping bind : options.keyHotbarSlots) { + if (instance == bind) { + return false; + } + } + if ( + instance == options.keyInventory || + instance == options.keySwapOffhand || + instance == options.keyDrop + ) { + return false; + } + return result; + } - @WrapOperation( - method = {"startAttack", "continueAttack"}, - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/multiplayer/ClientLevel;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", - ordinal = 0 - ) - ) - private BlockState noMineInPortalHud(ClientLevel instance, BlockPos pos, Operation original) { - return PortalCubedClient.isPortalHudMode() || player.getMainHandItem().is(PortalCubedItems.CROWBAR) - ? Blocks.AIR.defaultBlockState() : original.call(instance, pos); - } + @WrapOperation( + method = {"startAttack", "continueAttack"}, + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/multiplayer/ClientLevel;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", + ordinal = 0 + ) + ) + private BlockState noMineInPortalHud(ClientLevel instance, BlockPos pos, Operation original) { + return PortalCubedClient.isPortalHudMode() || player.getMainHandItem().is(PortalCubedItems.CROWBAR) + ? Blocks.AIR.defaultBlockState() : original.call(instance, pos); + } - @WrapOperation( - method = "startAttack", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/multiplayer/ClientLevel;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", - ordinal = 0 - ) - ) - private BlockState crowbarAttack(ClientLevel instance, BlockPos pos, Operation original) { - if (player.getMainHandItem().is(PortalCubedItems.CROWBAR)) { - final FriendlyByteBuf buf = PacketByteBufs.create(); - buf.writeBlockHitResult((BlockHitResult)hitResult); - ClientPlayNetworking.send(PortalCubedServerPackets.CROWBAR_ATTACK, buf); - } - return original.call(instance, pos); - } + @WrapOperation( + method = "startAttack", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/multiplayer/ClientLevel;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", + ordinal = 0 + ) + ) + private BlockState crowbarAttack(ClientLevel instance, BlockPos pos, Operation original) { + if (player.getMainHandItem().is(PortalCubedItems.CROWBAR)) { + final FriendlyByteBuf buf = PacketByteBufs.create(); + buf.writeBlockHitResult((BlockHitResult)hitResult); + ClientPlayNetworking.send(PortalCubedServerPackets.CROWBAR_ATTACK, buf); + } + return original.call(instance, pos); + } - @Override - public void setRenderBuffers(RenderBuffers buffers) { - renderBuffers = buffers; - } + @Override + public void setRenderBuffers(RenderBuffers buffers) { + renderBuffers = buffers; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelBakery_ModelBakerImplMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelBakery_ModelBakerImplMixin.java index 48eb14f2..a82436b7 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelBakery_ModelBakerImplMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelBakery_ModelBakerImplMixin.java @@ -17,26 +17,26 @@ @SuppressWarnings("checkstyle:TypeName") @Mixin(targets = "net.minecraft.client.resources.model.ModelBakery$ModelBakerImpl") public class ModelBakery_ModelBakerImplMixin { - @Final - @Shadow - @SuppressWarnings("checkstyle:MemberName") - ModelBakery field_40571; + @Final + @Shadow + @SuppressWarnings("checkstyle:MemberName") + ModelBakery field_40571; - @Inject(method = "bake", at = @At("RETURN"), cancellable = true) - private void portalcubed$injectEmissiveModels( - ResourceLocation location, - ModelState transform, - CallbackInfoReturnable cir, - @Local ModelBakery.BakedCacheKey bakedCacheKey - ) { - if (field_40571.bakedCache.get(bakedCacheKey) instanceof EmissiveBakedModel || !location.getNamespace().equals(PortalCubed.MOD_ID)) - return; + @Inject(method = "bake", at = @At("RETURN"), cancellable = true) + private void portalcubed$injectEmissiveModels( + ResourceLocation location, + ModelState transform, + CallbackInfoReturnable cir, + @Local ModelBakery.BakedCacheKey bakedCacheKey + ) { + if (field_40571.bakedCache.get(bakedCacheKey) instanceof EmissiveBakedModel || !location.getNamespace().equals(PortalCubed.MOD_ID)) + return; - final BakedModel modelToWrap = cir.getReturnValue(); - final BakedModel customModel = EmissiveBakedModel.wrap(location, modelToWrap).orElse(modelToWrap); - if (customModel == null || customModel == modelToWrap) return; + final BakedModel modelToWrap = cir.getReturnValue(); + final BakedModel customModel = EmissiveBakedModel.wrap(location, modelToWrap).orElse(modelToWrap); + if (customModel == null || customModel == modelToWrap) return; - field_40571.bakedCache.replace(bakedCacheKey, customModel); - cir.setReturnValue(customModel); - } + field_40571.bakedCache.replace(bakedCacheKey, customModel); + cir.setReturnValue(customModel); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelManagerAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelManagerAccessor.java index 82802e21..7b0128f5 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelManagerAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ModelManagerAccessor.java @@ -11,6 +11,6 @@ @Mixin(ModelManager.class) public interface ModelManagerAccessor { - @Accessor - Map getBakedRegistry(); + @Accessor + Map getBakedRegistry(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/MouseHandlerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/MouseHandlerMixin.java index b2f78a32..469e60d4 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/MouseHandlerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/MouseHandlerMixin.java @@ -16,30 +16,30 @@ @Mixin(MouseHandler.class) public class MouseHandlerMixin { - @Shadow @Final private Minecraft minecraft; + @Shadow @Final private Minecraft minecraft; - @WrapWithCondition( - method = "grabMouse", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/Minecraft;setScreen(Lnet/minecraft/client/gui/screens/Screen;)V" - ) - ) - private boolean notPortalHud(Minecraft client, Screen screen) { - return screen != null || !(client.screen instanceof DeathScreen) || !PortalCubedClient.isPortalHudMode(); - } + @WrapWithCondition( + method = "grabMouse", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/Minecraft;setScreen(Lnet/minecraft/client/gui/screens/Screen;)V" + ) + ) + private boolean notPortalHud(Minecraft client, Screen screen) { + return screen != null || !(client.screen instanceof DeathScreen) || !PortalCubedClient.isPortalHudMode(); + } - @WrapOperation( - method = "turnPlayer", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/OptionInstance;get()Ljava/lang/Object;" - ) - ) - private Object slowLook(OptionInstance instance, Operation original) { - if (instance == minecraft.options.sensitivity() && PortalCubedClient.zoomDir > 0) { - return original.call(instance) / 2; - } - return original.call(instance); - } + @WrapOperation( + method = "turnPlayer", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/OptionInstance;get()Ljava/lang/Object;" + ) + ) + private Object slowLook(OptionInstance instance, Operation original) { + if (instance == minecraft.options.sensitivity() && PortalCubedClient.zoomDir > 0) { + return original.call(instance) / 2; + } + return original.call(instance); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/MultiPlayerGameModeMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/MultiPlayerGameModeMixin.java index c64d9431..58d502ce 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/MultiPlayerGameModeMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/MultiPlayerGameModeMixin.java @@ -15,17 +15,17 @@ @Mixin(MultiPlayerGameMode.class) public class MultiPlayerGameModeMixin { - @WrapOperation( - method = "performUseItemOn", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;use(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;" - ) - ) - private InteractionResult noPlaceInPortalHud(BlockState instance, Level world, Player player, InteractionHand hand, BlockHitResult hit, Operation original) { - if (PortalCubedClient.isPortalHudMode()) { - return InteractionResult.PASS; - } - return original.call(instance, world, player, hand, hit); - } + @WrapOperation( + method = "performUseItemOn", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/block/state/BlockState;use(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;" + ) + ) + private InteractionResult noPlaceInPortalHud(BlockState instance, Level world, Player player, InteractionHand hand, BlockHitResult hit, Operation original) { + if (PortalCubedClient.isPortalHudMode()) { + return InteractionResult.PASS; + } + return original.call(instance, world, player, hand, hit); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/MusicManagerAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/MusicManagerAccessor.java index d6db75d1..954dadb9 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/MusicManagerAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/MusicManagerAccessor.java @@ -8,7 +8,7 @@ @Mixin(MusicManager.class) public interface MusicManagerAccessor { - @Accessor - @Nullable - SoundInstance getCurrentMusic(); + @Accessor + @Nullable + SoundInstance getCurrentMusic(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ParticleEngineMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ParticleEngineMixin.java index 6f648259..d3950b73 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ParticleEngineMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ParticleEngineMixin.java @@ -15,34 +15,34 @@ @Mixin(ParticleEngine.class) public class ParticleEngineMixin { - @WrapOperation( - method = "crack", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;getRenderShape()Lnet/minecraft/world/level/block/RenderShape;" - ) - ) - private RenderShape fixSpecialHiddenCrash(BlockState blockState, Operation original) { - if (blockState.getBlock() instanceof SpecialHiddenBlock) { - return RenderShape.INVISIBLE; - } - return original.call(blockState); - } + @WrapOperation( + method = "crack", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/block/state/BlockState;getRenderShape()Lnet/minecraft/world/level/block/RenderShape;" + ) + ) + private RenderShape fixSpecialHiddenCrash(BlockState blockState, Operation original) { + if (blockState.getBlock() instanceof SpecialHiddenBlock) { + return RenderShape.INVISIBLE; + } + return original.call(blockState); + } - @WrapOperation( - method = "", - at = @At( - value = "INVOKE", - target = "Lcom/google/common/collect/ImmutableList;of(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/common/collect/ImmutableList;", - remap = false - ) - ) - private static ImmutableList addCustomRenderType( - Object e1, Object e2, Object e3, Object e4, Object e5, Operation> original - ) { - return Stream.concat( - original.call(e1, e2, e3, e4, e5).stream(), - Stream.of(DecalParticle.PARTICLE_SHEET_MULTIPLY) - ).collect(ImmutableList.toImmutableList()); - } + @WrapOperation( + method = "", + at = @At( + value = "INVOKE", + target = "Lcom/google/common/collect/ImmutableList;of(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/common/collect/ImmutableList;", + remap = false + ) + ) + private static ImmutableList addCustomRenderType( + Object e1, Object e2, Object e3, Object e4, Object e5, Operation> original + ) { + return Stream.concat( + original.call(e1, e2, e3, e4, e5).stream(), + Stream.of(DecalParticle.PARTICLE_SHEET_MULTIPLY) + ).collect(ImmutableList.toImmutableList()); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/PlayerRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/PlayerRendererMixin.java index 5442f453..e4861b1d 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/PlayerRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/PlayerRendererMixin.java @@ -10,17 +10,17 @@ @Mixin(PlayerRenderer.class) public class PlayerRendererMixin { - @WrapOperation( - method = "setModelProperties", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/player/AbstractClientPlayer;isCrouching()Z" - ) - ) - private boolean fixAss(AbstractClientPlayer instance, Operation original) { - if (PortalCubedClient.isPortalHudModeServer()) { - return false; - } - return original.call(instance); - } + @WrapOperation( + method = "setModelProperties", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/player/AbstractClientPlayer;isCrouching()Z" + ) + ) + private boolean fixAss(AbstractClientPlayer instance, Operation original) { + if (PortalCubedClient.isPortalHudModeServer()) { + return false; + } + return original.call(instance); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderSystemMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderSystemMixin.java index 126012a8..a9f99f96 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderSystemMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderSystemMixin.java @@ -11,9 +11,9 @@ @Mixin(RenderSystem.class) public abstract class RenderSystemMixin { - @ModifyVariable(method = "depthFunc", at = @At("HEAD"), argsOnly = true, remap = false) - private static int portalCubed$fixPortalTracerDepthFunc(int originalDepthFunc) { - return PortalRenderPhase.TRACER == PortalRenderer.renderPhase ? GL11.GL_GEQUAL : originalDepthFunc; - } + @ModifyVariable(method = "depthFunc", at = @At("HEAD"), argsOnly = true, remap = false) + private static int portalCubed$fixPortalTracerDepthFunc(int originalDepthFunc) { + return PortalRenderPhase.TRACER == PortalRenderer.renderPhase ? GL11.GL_GEQUAL : originalDepthFunc; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderTargetMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderTargetMixin.java index f5c90342..84538245 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderTargetMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/RenderTargetMixin.java @@ -17,54 +17,54 @@ // Based on https://github.com/iPortalTeam/ImmersivePortalsMod/blob/55c9c1e7e298e09d8d43b0114e64e30271aa43b6/imm_ptl_core/src/main/java/qouteall/imm_ptl/core/mixin/client/render/framebuffer/MixinRenderTarget.java#L3 @Mixin(RenderTarget.class) public abstract class RenderTargetMixin implements RenderTargetExt { - @Shadow public abstract void resize(int width, int height, boolean getError); + @Shadow public abstract void resize(int width, int height, boolean getError); - @Shadow public int width; - @Shadow public int height; + @Shadow public int width; + @Shadow public int height; - @Unique - private boolean stencilBufferEnabled; + @Unique + private boolean stencilBufferEnabled; - @ModifyArgs( - method = "createBuffers", - at = @At( - value = "INVOKE", - target = "Lcom/mojang/blaze3d/platform/GlStateManager;_texImage2D(IIIIIIIILjava/nio/IntBuffer;)V", - remap = false - ) - ) - private void texImage2D(Args args) { - if (stencilBufferEnabled && args.get(2).equals(GL_DEPTH_COMPONENT)) { - args.set(2, GL_DEPTH24_STENCIL8); - args.set(6, ARBFramebufferObject.GL_DEPTH_STENCIL); - args.set(7, GL_UNSIGNED_INT_24_8); - } - } + @ModifyArgs( + method = "createBuffers", + at = @At( + value = "INVOKE", + target = "Lcom/mojang/blaze3d/platform/GlStateManager;_texImage2D(IIIIIIIILjava/nio/IntBuffer;)V", + remap = false + ) + ) + private void texImage2D(Args args) { + if (stencilBufferEnabled && args.get(2).equals(GL_DEPTH_COMPONENT)) { + args.set(2, GL_DEPTH24_STENCIL8); + args.set(6, ARBFramebufferObject.GL_DEPTH_STENCIL); + args.set(7, GL_UNSIGNED_INT_24_8); + } + } - @ModifyArgs( - method = "createBuffers", - at = @At( - value = "INVOKE", - target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glFramebufferTexture2D(IIIII)V", - remap = false - ) - ) - private void framebufferTexture2D(Args args) { - if (stencilBufferEnabled && args.get(1).equals(GL_DEPTH_ATTACHMENT)) { - args.set(1, GL_DEPTH_STENCIL_ATTACHMENT); - } - } + @ModifyArgs( + method = "createBuffers", + at = @At( + value = "INVOKE", + target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glFramebufferTexture2D(IIIII)V", + remap = false + ) + ) + private void framebufferTexture2D(Args args) { + if (stencilBufferEnabled && args.get(1).equals(GL_DEPTH_ATTACHMENT)) { + args.set(1, GL_DEPTH_STENCIL_ATTACHMENT); + } + } - @Override - public boolean isStencilBufferEnabled() { - return stencilBufferEnabled; - } + @Override + public boolean isStencilBufferEnabled() { + return stencilBufferEnabled; + } - @Override - public void setStencilBufferEnabled(boolean enabled) { - if (enabled != stencilBufferEnabled) { - stencilBufferEnabled = enabled; - resize(width, height, Minecraft.ON_OSX); - } - } + @Override + public void setStencilBufferEnabled(boolean enabled) { + if (enabled != stencilBufferEnabled) { + stencilBufferEnabled = enabled; + resize(width, height, Minecraft.ON_OSX); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/ScreenEffectRendererMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/ScreenEffectRendererMixin.java index 35415456..66aafab9 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/ScreenEffectRendererMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/ScreenEffectRendererMixin.java @@ -12,16 +12,16 @@ @Mixin(ScreenEffectRenderer.class) public class ScreenEffectRendererMixin { - @WrapWithCondition( - method = "renderScreenEffect", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/renderer/ScreenEffectRenderer;renderTex(Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;Lcom/mojang/blaze3d/vertex/PoseStack;)V" - ) - ) - @SuppressWarnings("unused") - private static boolean renderOverlays(TextureAtlasSprite sprite, PoseStack matrices) { - return CalledValues.getPortalCutout(Minecraft.getInstance().player).isEmpty(); - } + @WrapWithCondition( + method = "renderScreenEffect", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ScreenEffectRenderer;renderTex(Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;Lcom/mojang/blaze3d/vertex/PoseStack;)V" + ) + ) + @SuppressWarnings("unused") + private static boolean renderOverlays(TextureAtlasSprite sprite, PoseStack matrices) { + return CalledValues.getPortalCutout(Minecraft.getInstance().player).isEmpty(); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/SimpleBakedModelAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/SimpleBakedModelAccessor.java index e1711d04..58858feb 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/SimpleBakedModelAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/SimpleBakedModelAccessor.java @@ -12,9 +12,9 @@ @Mixin(SimpleBakedModel.class) public interface SimpleBakedModelAccessor { - @Accessor - List getUnculledFaces(); + @Accessor + List getUnculledFaces(); - @Accessor - Map> getCulledFaces(); + @Accessor + Map> getCulledFaces(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/SoundEngineMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/SoundEngineMixin.java index 18e2ba4f..8f38b3d6 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/SoundEngineMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/SoundEngineMixin.java @@ -16,24 +16,24 @@ @Mixin(SoundEngine.class) public abstract class SoundEngineMixin { - @Shadow public abstract void play(SoundInstance sound); + @Shadow public abstract void play(SoundInstance sound); - @Inject( - method = "play", - at = @At( - value = "INVOKE", - target = "Ljava/util/Set;add(Ljava/lang/Object;)Z", - ordinal = 1 - ) - ) - private void ohFiddlesticks(SoundInstance sound, CallbackInfo ci) { - if ( - !sound.getLocation().getNamespace().equals(PortalCubed.MOD_ID) || - BuiltInRegistries.SOUND_EVENT.getOrCreateTag(PortalCubedSounds.NO_ERROR_SOUND) - .contains(BuiltInRegistries.SOUND_EVENT.getHolderOrThrow( - ResourceKey.create(Registries.SOUND_EVENT, sound.getLocation()) - )) - ) return; - play(SimpleSoundInstance.forUI(PortalCubedSounds.ERROR_EVENT, 1f)); - } + @Inject( + method = "play", + at = @At( + value = "INVOKE", + target = "Ljava/util/Set;add(Ljava/lang/Object;)Z", + ordinal = 1 + ) + ) + private void ohFiddlesticks(SoundInstance sound, CallbackInfo ci) { + if ( + !sound.getLocation().getNamespace().equals(PortalCubed.MOD_ID) || + BuiltInRegistries.SOUND_EVENT.getOrCreateTag(PortalCubedSounds.NO_ERROR_SOUND) + .contains(BuiltInRegistries.SOUND_EVENT.getHolderOrThrow( + ResourceKey.create(Registries.SOUND_EVENT, sound.getLocation()) + )) + ) return; + play(SimpleSoundInstance.forUI(PortalCubedSounds.ERROR_EVENT, 1f)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/SpriteContentsAccessor.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/SpriteContentsAccessor.java index e5fbb022..a04beda8 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/SpriteContentsAccessor.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/SpriteContentsAccessor.java @@ -7,6 +7,6 @@ @Mixin(SpriteContents.class) public interface SpriteContentsAccessor { - @Accessor - NativeImage getOriginalImage(); + @Accessor + NativeImage getOriginalImage(); } diff --git a/src/main/java/com/fusionflux/portalcubed/mixin/client/VertexConsumerMixin.java b/src/main/java/com/fusionflux/portalcubed/mixin/client/VertexConsumerMixin.java index fe9e8b82..d1b46d60 100644 --- a/src/main/java/com/fusionflux/portalcubed/mixin/client/VertexConsumerMixin.java +++ b/src/main/java/com/fusionflux/portalcubed/mixin/client/VertexConsumerMixin.java @@ -10,15 +10,15 @@ @Mixin(VertexConsumer.class) public interface VertexConsumerMixin { - @ModifyArg( - method = "putBulkData(Lcom/mojang/blaze3d/vertex/PoseStack$Pose;Lnet/minecraft/client/renderer/block/model/BakedQuad;[FFFF[IIZ)V", - at = @At( - value = "INVOKE", - target = "Lcom/mojang/blaze3d/vertex/VertexConsumer;vertex(FFFFFFFFFIIFFF)V" - ), - index = 6 - ) - default float modifyAlpha(float original) { - return EnergyPelletRenderer.pelletAlpha == null ? original : EnergyPelletRenderer.pelletAlpha; - } + @ModifyArg( + method = "putBulkData(Lcom/mojang/blaze3d/vertex/PoseStack$Pose;Lnet/minecraft/client/renderer/block/model/BakedQuad;[FFFF[IIZ)V", + at = @At( + value = "INVOKE", + target = "Lcom/mojang/blaze3d/vertex/VertexConsumer;vertex(FFFFFFFFFIIFFF)V" + ), + index = 6 + ) + default float modifyAlpha(float original) { + return EnergyPelletRenderer.pelletAlpha == null ? original : EnergyPelletRenderer.pelletAlpha; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/packet/NetworkingSafetyWrapper.java b/src/main/java/com/fusionflux/portalcubed/packet/NetworkingSafetyWrapper.java index 5d0b420d..4541d039 100644 --- a/src/main/java/com/fusionflux/portalcubed/packet/NetworkingSafetyWrapper.java +++ b/src/main/java/com/fusionflux/portalcubed/packet/NetworkingSafetyWrapper.java @@ -8,7 +8,7 @@ //gotta have the `ClientPlayNetworking` call in a separate class //so that Mixin can resolve all the classes used when patching public class NetworkingSafetyWrapper { - public static void sendFromClient(String name, FriendlyByteBuf buf) { - ClientPlayNetworking.send(PortalCubed.id(name), buf); - } + public static void sendFromClient(String name, FriendlyByteBuf buf) { + ClientPlayNetworking.send(PortalCubed.id(name), buf); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/packet/PortalCubedServerPackets.java b/src/main/java/com/fusionflux/portalcubed/packet/PortalCubedServerPackets.java index 9c4292e1..27ae30a2 100644 --- a/src/main/java/com/fusionflux/portalcubed/packet/PortalCubedServerPackets.java +++ b/src/main/java/com/fusionflux/portalcubed/packet/PortalCubedServerPackets.java @@ -49,181 +49,181 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedServerPackets { - public static final ResourceLocation GRAB_KEY_PRESSED = id("grab_key_pressed"); - public static final ResourceLocation REMOVE_PORTALS = id("remove_portals"); - public static final ResourceLocation VELOCITY_HELPER_CONFIGURE = id("velocity_helper_configure"); - public static final ResourceLocation PLAY_BOUNCE_SOUND = id("play_bounce_sound"); - public static final ResourceLocation CROWBAR_ATTACK = id("crowbar_attack"); - public static final ResourceLocation LEFT_CLICK = id("left_click"); - public static final ResourceLocation RIGHT_CLICK = id("right_click"); - public static final ResourceLocation SYNC_SHOOTER_ROT = id("sync_shooter_rot"); - public static final ResourceLocation NBT_SYNC = id("nbt_sync"); + public static final ResourceLocation GRAB_KEY_PRESSED = id("grab_key_pressed"); + public static final ResourceLocation REMOVE_PORTALS = id("remove_portals"); + public static final ResourceLocation VELOCITY_HELPER_CONFIGURE = id("velocity_helper_configure"); + public static final ResourceLocation PLAY_BOUNCE_SOUND = id("play_bounce_sound"); + public static final ResourceLocation CROWBAR_ATTACK = id("crowbar_attack"); + public static final ResourceLocation LEFT_CLICK = id("left_click"); + public static final ResourceLocation RIGHT_CLICK = id("right_click"); + public static final ResourceLocation SYNC_SHOOTER_ROT = id("sync_shooter_rot"); + public static final ResourceLocation NBT_SYNC = id("nbt_sync"); - public static void onGrabKeyPressed(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { + public static void onGrabKeyPressed(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { - Vec3 vec3d = player.getEyePosition(0); - double d = 3 * PehkuiScaleTypes.ENTITY_REACH.getScaleData(player).getScale(); + Vec3 vec3d = player.getEyePosition(0); + double d = 3 * PehkuiScaleTypes.ENTITY_REACH.getScaleData(player).getScale(); - Vec3 vec3d2 = player.getViewVector(1.0F); - Vec3 vec3d3 = vec3d.add(vec3d2.x * d, vec3d2.y * d, vec3d2.z * d); + Vec3 vec3d2 = player.getViewVector(1.0F); + Vec3 vec3d3 = vec3d.add(vec3d2.x * d, vec3d2.y * d, vec3d2.z * d); - server.execute(() -> { - final AdvancedEntityRaycast.Result advancedCast = PortalDirectionUtils.raycast(player.level(), new ClipContext( - vec3d, vec3d3, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, player - )); - EntityHitResult entityHitResult = advancedCast.entityRaycast(player, (entity) -> !entity.isSpectator() && entity.isPickable()); - if (entityHitResult != null) { - if (entityHitResult.getEntity() instanceof CorePhysicsEntity entity && !PortalCubedComponents.HOLDER_COMPONENT.get(player).hold(entity)) { - PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding(); - } - } else if (!PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding()) { - if (advancedCast.finalHit().getType() == HitResult.Type.BLOCK) { - final BlockHitResult hit = (BlockHitResult)advancedCast.finalHit(); - final BlockState state = player.level().getBlockState(hit.getBlockPos()); - if ( - state.getBlock() instanceof TallButtonVariant button && - player.gameMode.useItemOn(player, player.level(), ItemStack.EMPTY, InteractionHand.OFF_HAND, hit) != InteractionResult.PASS - ) { - player.level().playSound(null, hit.getBlockPos(), button.getClickSound(true), SoundSource.BLOCKS, 0.8f, 1f); - return; - } - } - // bc: only do fail stuff if holding portal gun - if (player.isHolding(stack -> stack.getItem() instanceof PortalGun)) { - player.playNotifySound(PortalCubedSounds.HOLD_FAIL_EVENT, SoundSource.NEUTRAL, 0.3f, 1f); - ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); - } - } - }); - } + server.execute(() -> { + final AdvancedEntityRaycast.Result advancedCast = PortalDirectionUtils.raycast(player.level(), new ClipContext( + vec3d, vec3d3, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, player + )); + EntityHitResult entityHitResult = advancedCast.entityRaycast(player, (entity) -> !entity.isSpectator() && entity.isPickable()); + if (entityHitResult != null) { + if (entityHitResult.getEntity() instanceof CorePhysicsEntity entity && !PortalCubedComponents.HOLDER_COMPONENT.get(player).hold(entity)) { + PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding(); + } + } else if (!PortalCubedComponents.HOLDER_COMPONENT.get(player).stopHolding()) { + if (advancedCast.finalHit().getType() == HitResult.Type.BLOCK) { + final BlockHitResult hit = (BlockHitResult)advancedCast.finalHit(); + final BlockState state = player.level().getBlockState(hit.getBlockPos()); + if ( + state.getBlock() instanceof TallButtonVariant button && + player.gameMode.useItemOn(player, player.level(), ItemStack.EMPTY, InteractionHand.OFF_HAND, hit) != InteractionResult.PASS + ) { + player.level().playSound(null, hit.getBlockPos(), button.getClickSound(true), SoundSource.BLOCKS, 0.8f, 1f); + return; + } + } + // bc: only do fail stuff if holding portal gun + if (player.isHolding(stack -> stack.getItem() instanceof PortalGun)) { + player.playNotifySound(PortalCubedSounds.HOLD_FAIL_EVENT, SoundSource.NEUTRAL, 0.3f, 1f); + ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); + } + } + }); + } - public static void onRemovePortalKeyPressed(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { - server.execute(() -> { - boolean foundPortal = false; - for (final UUID portal : List.copyOf(CalledValues.getPortals(player))) { - final Entity checkPortal = player.serverLevel().getEntity(portal); - if (checkPortal != null) { - foundPortal = true; - checkPortal.kill(); - } - } - if (foundPortal) { - ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); - player.playNotifySound(PortalCubedSounds.ENTITY_PORTAL_FIZZLE, SoundSource.NEUTRAL, 0.5f, 1f); - ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); - } - }); - } + public static void onRemovePortalKeyPressed(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { + server.execute(() -> { + boolean foundPortal = false; + for (final UUID portal : List.copyOf(CalledValues.getPortals(player))) { + final Entity checkPortal = player.serverLevel().getEntity(portal); + if (checkPortal != null) { + foundPortal = true; + checkPortal.kill(); + } + } + if (foundPortal) { + ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); + player.playNotifySound(PortalCubedSounds.ENTITY_PORTAL_FIZZLE, SoundSource.NEUTRAL, 0.5f, 1f); + ServerPlayNetworking.send(player, PortalCubedClientPackets.HAND_SHAKE_PACKET, PacketByteBufs.create()); + } + }); + } - @SuppressWarnings("unchecked") - public static void onVelocityHelperConfigure(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { - final BlockPos origin = buf.readBlockPos(); - final int mode = buf.readByte(); - final Object arg = switch (mode) { - case VelocityHelperBlock.CONFIG_DEST -> buf.readOptional(FriendlyByteBuf::readBlockPos); - case VelocityHelperBlock.CONFIG_OTHER -> Triple.of(buf.readVarInt(), buf.readUtf(), buf.readUtf()); - default -> { - PortalCubed.LOGGER.error("Malformed velocity_helper_configure packet. Unknown mode {}.", mode); - yield null; - } - }; - if (arg == null) return; - server.execute(() -> player.level().getBlockEntity(origin, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).ifPresentOrElse( - entity -> { - switch (mode) { - case VelocityHelperBlock.CONFIG_DEST -> { - if (!player.isHolding(s -> s.is(PortalCubedItems.WRENCHES))) { - PortalCubed.LOGGER.warn("Received velocity_helper_configure from {}, who's not holding a hammer.", player); - return; - } - entity.setDestination(((Optional)arg).orElse(null)); - } - case VelocityHelperBlock.CONFIG_OTHER -> { - final var triple = (Triple)arg; - entity.setFlightDuration(triple.getLeft()); - entity.setCondition(triple.getMiddle()); - entity.setInterpolationCurve(triple.getRight()); - } - } - entity.updateListeners(); - }, - () -> PortalCubed.LOGGER.warn("Received velocity_helper_configure for unloaded velocity helper at {}.", origin) - )); - } + @SuppressWarnings("unchecked") + public static void onVelocityHelperConfigure(MinecraftServer server, ServerPlayer player, @SuppressWarnings("unused") ServerGamePacketListenerImpl handler, @SuppressWarnings("unused") FriendlyByteBuf buf, @SuppressWarnings("unused") PacketSender sender) { + final BlockPos origin = buf.readBlockPos(); + final int mode = buf.readByte(); + final Object arg = switch (mode) { + case VelocityHelperBlock.CONFIG_DEST -> buf.readOptional(FriendlyByteBuf::readBlockPos); + case VelocityHelperBlock.CONFIG_OTHER -> Triple.of(buf.readVarInt(), buf.readUtf(), buf.readUtf()); + default -> { + PortalCubed.LOGGER.error("Malformed velocity_helper_configure packet. Unknown mode {}.", mode); + yield null; + } + }; + if (arg == null) return; + server.execute(() -> player.level().getBlockEntity(origin, PortalCubedBlocks.VELOCITY_HELPER_BLOCK_ENTITY).ifPresentOrElse( + entity -> { + switch (mode) { + case VelocityHelperBlock.CONFIG_DEST -> { + if (!player.isHolding(s -> s.is(PortalCubedItems.WRENCHES))) { + PortalCubed.LOGGER.warn("Received velocity_helper_configure from {}, who's not holding a hammer.", player); + return; + } + entity.setDestination(((Optional)arg).orElse(null)); + } + case VelocityHelperBlock.CONFIG_OTHER -> { + final var triple = (Triple)arg; + entity.setFlightDuration(triple.getLeft()); + entity.setCondition(triple.getMiddle()); + entity.setInterpolationCurve(triple.getRight()); + } + } + entity.updateListeners(); + }, + () -> PortalCubed.LOGGER.warn("Received velocity_helper_configure for unloaded velocity helper at {}.", origin) + )); + } - public static void registerPackets() { - ServerPlayNetworking.registerGlobalReceiver(GRAB_KEY_PRESSED, PortalCubedServerPackets::onGrabKeyPressed); - ServerPlayNetworking.registerGlobalReceiver(REMOVE_PORTALS, PortalCubedServerPackets::onRemovePortalKeyPressed); - ServerPlayNetworking.registerGlobalReceiver(VELOCITY_HELPER_CONFIGURE, PortalCubedServerPackets::onVelocityHelperConfigure); - ServerPlayNetworking.registerGlobalReceiver( - PLAY_BOUNCE_SOUND, (server, player, handler, buf, responseSender) -> PortalCubed.playBounceSound(player) - ); - ServerPlayNetworking.registerGlobalReceiver(CROWBAR_ATTACK, (server, player, handler, buf, responseSender) -> { - final BlockHitResult hit = buf.readBlockHitResult(); - if (hit.getLocation().distanceToSqr(player.position()) > 100) { - PortalCubed.LOGGER.warn( - "Player {} tried to use a crowbar to attack a distant block ({})", - player, hit.getLocation().distanceTo(player.position()) - ); - } - server.execute(() -> { - player.level().playSound( - player, - player.getX(), player.getY(), player.getZ(), - PortalCubedSounds.CROWBAR_SWOOSH_EVENT, SoundSource.PLAYERS, - 1f, 1f - ); - TurretEntity.makeBulletHole(player.serverLevel(), hit, SoundSource.PLAYERS); - }); - }); - ServerPlayNetworking.registerGlobalReceiver(LEFT_CLICK, (server, player, handler, buf, responseSender) -> server.execute(() -> { - if (player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { - if (chi.onLeftClick(player, InteractionHand.MAIN_HAND).shouldSwing()) player.swing(InteractionHand.MAIN_HAND, true); - } - })); - ServerPlayNetworking.registerGlobalReceiver(RIGHT_CLICK, (server, player, handler, buf, responseSender) -> server.execute(() -> { - if (player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { - if (chi.onRightClick(player, InteractionHand.MAIN_HAND).shouldSwing()) player.swing(InteractionHand.MAIN_HAND, true); - } - })); - ServerPlayNetworking.registerGlobalReceiver(SYNC_SHOOTER_ROT, (server, player, handler, buf, responseSender) -> { - final float xRot = buf.readFloat(); - final float yRot = buf.readFloat(); - server.execute(() -> { - player.setXRot(xRot); - player.setYRot(yRot); - player.setYHeadRot(yRot); - // The O's are the ones that are actually used for getViewVector! - player.xRotO = xRot; - player.yHeadRotO = yRot; - }); - }); - ServerPlayNetworking.registerGlobalReceiver(NBT_SYNC, (server, player, handler, buf, responseSender) -> { - final BlockPos pos = buf.readBlockPos(); - final CompoundTag nbt = buf.readNbt(); - server.execute(() -> { - final Vec3 originPos = Vec3.atCenterOf(pos); - if (player.position().distanceToSqr(originPos) > 100) { - PortalCubed.LOGGER.warn( - "Player {} tried to update distant block entity ({})", - player, player.position().distanceTo(originPos) - ); - return; - } - if (player.level().getBlockState(pos) instanceof NbtSyncable syncable) { - try { - syncable.syncNbt(nbt, player); - } catch (CommandRuntimeException e) { - player.connection.disconnect(e.getComponent()); - PortalCubed.LOGGER.warn("Player {} sent invalid sync NBT: {}", player, e.getLocalizedMessage()); - } catch (Exception e) { - player.connection.disconnect(Component.translatable("disconnect.genericReason", e.getLocalizedMessage())); - PortalCubed.LOGGER.error("Error in handling nbt_sync", e); - } - } else { - PortalCubed.LOGGER.warn("{} failed to update non-existent block entity at {}", player, pos); - } - }); - }); - } + public static void registerPackets() { + ServerPlayNetworking.registerGlobalReceiver(GRAB_KEY_PRESSED, PortalCubedServerPackets::onGrabKeyPressed); + ServerPlayNetworking.registerGlobalReceiver(REMOVE_PORTALS, PortalCubedServerPackets::onRemovePortalKeyPressed); + ServerPlayNetworking.registerGlobalReceiver(VELOCITY_HELPER_CONFIGURE, PortalCubedServerPackets::onVelocityHelperConfigure); + ServerPlayNetworking.registerGlobalReceiver( + PLAY_BOUNCE_SOUND, (server, player, handler, buf, responseSender) -> PortalCubed.playBounceSound(player) + ); + ServerPlayNetworking.registerGlobalReceiver(CROWBAR_ATTACK, (server, player, handler, buf, responseSender) -> { + final BlockHitResult hit = buf.readBlockHitResult(); + if (hit.getLocation().distanceToSqr(player.position()) > 100) { + PortalCubed.LOGGER.warn( + "Player {} tried to use a crowbar to attack a distant block ({})", + player, hit.getLocation().distanceTo(player.position()) + ); + } + server.execute(() -> { + player.level().playSound( + player, + player.getX(), player.getY(), player.getZ(), + PortalCubedSounds.CROWBAR_SWOOSH_EVENT, SoundSource.PLAYERS, + 1f, 1f + ); + TurretEntity.makeBulletHole(player.serverLevel(), hit, SoundSource.PLAYERS); + }); + }); + ServerPlayNetworking.registerGlobalReceiver(LEFT_CLICK, (server, player, handler, buf, responseSender) -> server.execute(() -> { + if (player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { + if (chi.onLeftClick(player, InteractionHand.MAIN_HAND).shouldSwing()) player.swing(InteractionHand.MAIN_HAND, true); + } + })); + ServerPlayNetworking.registerGlobalReceiver(RIGHT_CLICK, (server, player, handler, buf, responseSender) -> server.execute(() -> { + if (player.getMainHandItem().getItem() instanceof ClickHandlingItem chi) { + if (chi.onRightClick(player, InteractionHand.MAIN_HAND).shouldSwing()) player.swing(InteractionHand.MAIN_HAND, true); + } + })); + ServerPlayNetworking.registerGlobalReceiver(SYNC_SHOOTER_ROT, (server, player, handler, buf, responseSender) -> { + final float xRot = buf.readFloat(); + final float yRot = buf.readFloat(); + server.execute(() -> { + player.setXRot(xRot); + player.setYRot(yRot); + player.setYHeadRot(yRot); + // The O's are the ones that are actually used for getViewVector! + player.xRotO = xRot; + player.yHeadRotO = yRot; + }); + }); + ServerPlayNetworking.registerGlobalReceiver(NBT_SYNC, (server, player, handler, buf, responseSender) -> { + final BlockPos pos = buf.readBlockPos(); + final CompoundTag nbt = buf.readNbt(); + server.execute(() -> { + final Vec3 originPos = Vec3.atCenterOf(pos); + if (player.position().distanceToSqr(originPos) > 100) { + PortalCubed.LOGGER.warn( + "Player {} tried to update distant block entity ({})", + player, player.position().distanceTo(originPos) + ); + return; + } + if (player.level().getBlockState(pos) instanceof NbtSyncable syncable) { + try { + syncable.syncNbt(nbt, player); + } catch (CommandRuntimeException e) { + player.connection.disconnect(e.getComponent()); + PortalCubed.LOGGER.warn("Player {} sent invalid sync NBT: {}", player, e.getLocalizedMessage()); + } catch (Exception e) { + player.connection.disconnect(Component.translatable("disconnect.genericReason", e.getLocalizedMessage())); + PortalCubed.LOGGER.error("Error in handling nbt_sync", e); + } + } else { + PortalCubed.LOGGER.warn("{} failed to update non-existent block entity at {}", player, pos); + } + }); + }); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/particle/DecalParticleOption.java b/src/main/java/com/fusionflux/portalcubed/particle/DecalParticleOption.java index d3cdf2b0..44f4e548 100644 --- a/src/main/java/com/fusionflux/portalcubed/particle/DecalParticleOption.java +++ b/src/main/java/com/fusionflux/portalcubed/particle/DecalParticleOption.java @@ -17,102 +17,102 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class DecalParticleOption implements ParticleOptions { - public static final ResourceLocation BULLET_HOLE_CONCRETE = id("bullet_hole_concrete"); - public static final ResourceLocation BULLET_HOLE_GLASS = id("bullet_hole_glass"); - public static final ResourceLocation BULLET_HOLE_METAL = id("bullet_hole_metal"); - public static final ResourceLocation SCORCH = id("scorch"); - - @SuppressWarnings("deprecation") - public static final ParticleOptions.Deserializer PARAMETERS_FACTORY = new Deserializer<>() { - @NotNull - @Override - public DecalParticleOption fromCommand(ParticleType type, StringReader reader) throws CommandSyntaxException { - reader.expect(' '); - final ResourceLocation texture = ResourceLocationArgument.id().parse(reader); - reader.expect(' '); - final Direction direction = DirectionArgumentType.direction().parse(reader); - final boolean multiply; - if (reader.canRead()) { - reader.expect(' '); - multiply = reader.readBoolean(); - } else { - multiply = false; - } - return new DecalParticleOption(type, texture, direction, multiply); - } - - @NotNull - @Override - public DecalParticleOption fromNetwork(ParticleType type, FriendlyByteBuf buf) { - return new DecalParticleOption( - type, - buf.readResourceLocation(), - buf.readEnum(Direction.class), - buf.readBoolean() - ); - } - }; - - private final ParticleType particleType; - private final ResourceLocation texture; - private final Direction direction; - private final boolean multiply; - - public DecalParticleOption(ParticleType particleType, ResourceLocation texture, Direction direction, boolean multiply) { - this.particleType = particleType; - this.texture = texture; - this.direction = direction; - this.multiply = multiply; - } - - public DecalParticleOption(ResourceLocation texture, Direction direction, boolean multiply) { - this(PortalCubedParticleTypes.DECAL, texture, direction, multiply); - } - - public DecalParticleOption(ResourceLocation texture, Direction direction) { - this(texture, direction, false); - } - - @NotNull - @Override - public ParticleType getType() { - return particleType; - } - - @Override - public void writeToNetwork(FriendlyByteBuf buf) { - buf.writeResourceLocation(texture); - buf.writeEnum(direction); - buf.writeBoolean(multiply); - } - - @NotNull - @Override - public String writeToString() { - return BuiltInRegistries.PARTICLE_TYPE.getKey(particleType) + " " + texture; - } - - public ResourceLocation getTexture() { - return texture; - } - - public Direction getDirection() { - return direction; - } - - public boolean isMultiply() { - return multiply; - } - - public static Codec codec(ParticleType particleType) { - return RecordCodecBuilder.create( - instance -> instance.group( - ResourceLocation.CODEC.fieldOf("texture").forGetter(DecalParticleOption::getTexture), - Direction.CODEC.fieldOf("direction").forGetter(DecalParticleOption::getDirection), - Codec.BOOL.fieldOf("multiply").forGetter(DecalParticleOption::isMultiply) - ).apply(instance, (texture, direction, multiply) -> - new DecalParticleOption(particleType, texture, direction, multiply) - ) - ); - } + public static final ResourceLocation BULLET_HOLE_CONCRETE = id("bullet_hole_concrete"); + public static final ResourceLocation BULLET_HOLE_GLASS = id("bullet_hole_glass"); + public static final ResourceLocation BULLET_HOLE_METAL = id("bullet_hole_metal"); + public static final ResourceLocation SCORCH = id("scorch"); + + @SuppressWarnings("deprecation") + public static final ParticleOptions.Deserializer PARAMETERS_FACTORY = new Deserializer<>() { + @NotNull + @Override + public DecalParticleOption fromCommand(ParticleType type, StringReader reader) throws CommandSyntaxException { + reader.expect(' '); + final ResourceLocation texture = ResourceLocationArgument.id().parse(reader); + reader.expect(' '); + final Direction direction = DirectionArgumentType.direction().parse(reader); + final boolean multiply; + if (reader.canRead()) { + reader.expect(' '); + multiply = reader.readBoolean(); + } else { + multiply = false; + } + return new DecalParticleOption(type, texture, direction, multiply); + } + + @NotNull + @Override + public DecalParticleOption fromNetwork(ParticleType type, FriendlyByteBuf buf) { + return new DecalParticleOption( + type, + buf.readResourceLocation(), + buf.readEnum(Direction.class), + buf.readBoolean() + ); + } + }; + + private final ParticleType particleType; + private final ResourceLocation texture; + private final Direction direction; + private final boolean multiply; + + public DecalParticleOption(ParticleType particleType, ResourceLocation texture, Direction direction, boolean multiply) { + this.particleType = particleType; + this.texture = texture; + this.direction = direction; + this.multiply = multiply; + } + + public DecalParticleOption(ResourceLocation texture, Direction direction, boolean multiply) { + this(PortalCubedParticleTypes.DECAL, texture, direction, multiply); + } + + public DecalParticleOption(ResourceLocation texture, Direction direction) { + this(texture, direction, false); + } + + @NotNull + @Override + public ParticleType getType() { + return particleType; + } + + @Override + public void writeToNetwork(FriendlyByteBuf buf) { + buf.writeResourceLocation(texture); + buf.writeEnum(direction); + buf.writeBoolean(multiply); + } + + @NotNull + @Override + public String writeToString() { + return BuiltInRegistries.PARTICLE_TYPE.getKey(particleType) + " " + texture; + } + + public ResourceLocation getTexture() { + return texture; + } + + public Direction getDirection() { + return direction; + } + + public boolean isMultiply() { + return multiply; + } + + public static Codec codec(ParticleType particleType) { + return RecordCodecBuilder.create( + instance -> instance.group( + ResourceLocation.CODEC.fieldOf("texture").forGetter(DecalParticleOption::getTexture), + Direction.CODEC.fieldOf("direction").forGetter(DecalParticleOption::getDirection), + Codec.BOOL.fieldOf("multiply").forGetter(DecalParticleOption::isMultiply) + ).apply(instance, (texture, direction, multiply) -> + new DecalParticleOption(particleType, texture, direction, multiply) + ) + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/particle/PortalCubedParticleTypes.java b/src/main/java/com/fusionflux/portalcubed/particle/PortalCubedParticleTypes.java index 6fd3bb36..92902638 100644 --- a/src/main/java/com/fusionflux/portalcubed/particle/PortalCubedParticleTypes.java +++ b/src/main/java/com/fusionflux/portalcubed/particle/PortalCubedParticleTypes.java @@ -14,27 +14,27 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedParticleTypes { - public static final ParticleType DECAL = register( - "decal", false, DecalParticleOption.PARAMETERS_FACTORY, DecalParticleOption::codec - ); + public static final ParticleType DECAL = register( + "decal", false, DecalParticleOption.PARAMETERS_FACTORY, DecalParticleOption::codec + ); - private static SimpleParticleType register(String key, boolean overrideLimiter) { - return Registry.register(BuiltInRegistries.PARTICLE_TYPE, id(key), FabricParticleTypes.simple(overrideLimiter)); - } + private static SimpleParticleType register(String key, boolean overrideLimiter) { + return Registry.register(BuiltInRegistries.PARTICLE_TYPE, id(key), FabricParticleTypes.simple(overrideLimiter)); + } - @SuppressWarnings("deprecation") - private static ParticleType register( - String name, boolean alwaysShow, ParticleOptions.Deserializer parameterFactory, Function, Codec> codecProvider - ) { - return Registry.register(BuiltInRegistries.PARTICLE_TYPE, id(name), new ParticleType(alwaysShow, parameterFactory) { - @NotNull - @Override - public Codec codec() { - return codecProvider.apply(this); - } - }); - } + @SuppressWarnings("deprecation") + private static ParticleType register( + String name, boolean alwaysShow, ParticleOptions.Deserializer parameterFactory, Function, Codec> codecProvider + ) { + return Registry.register(BuiltInRegistries.PARTICLE_TYPE, id(name), new ParticleType(alwaysShow, parameterFactory) { + @NotNull + @Override + public Codec codec() { + return codecProvider.apply(this); + } + }); + } - public static void register() { - } + public static void register() { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/sound/ExcursionFunnelEnterSoundInstance.java b/src/main/java/com/fusionflux/portalcubed/sound/ExcursionFunnelEnterSoundInstance.java index b82e9fe6..122891d2 100644 --- a/src/main/java/com/fusionflux/portalcubed/sound/ExcursionFunnelEnterSoundInstance.java +++ b/src/main/java/com/fusionflux/portalcubed/sound/ExcursionFunnelEnterSoundInstance.java @@ -5,22 +5,22 @@ import net.minecraft.sounds.SoundSource; public class ExcursionFunnelEnterSoundInstance extends AbstractTickableSoundInstance { - private int ticks = 0; + private int ticks = 0; - public ExcursionFunnelEnterSoundInstance() { - super(PortalCubedSounds.TBEAM_ENTER_EVENT, SoundSource.BLOCKS, SoundInstance.createUnseededRandom()); - volume =.5f; - this.attenuation = Attenuation.NONE; - } + public ExcursionFunnelEnterSoundInstance() { + super(PortalCubedSounds.TBEAM_ENTER_EVENT, SoundSource.BLOCKS, SoundInstance.createUnseededRandom()); + volume =.5f; + this.attenuation = Attenuation.NONE; + } - @Override - public void tick() { - ticks++; - if (ticks > 80) { - volume = .5f - 0.05f * (ticks - 80); - if (volume <= 0) { - stop(); - } - } - } + @Override + public void tick() { + ticks++; + if (ticks > 80) { + volume = .5f - 0.05f * (ticks - 80); + if (volume <= 0) { + stop(); + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/sound/PortalCubedSounds.java b/src/main/java/com/fusionflux/portalcubed/sound/PortalCubedSounds.java index d39e158f..edb04013 100644 --- a/src/main/java/com/fusionflux/portalcubed/sound/PortalCubedSounds.java +++ b/src/main/java/com/fusionflux/portalcubed/sound/PortalCubedSounds.java @@ -12,244 +12,244 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedSounds { - public static final ResourceLocation ERROR = id("error"); - - public static final ResourceLocation GEL_BOUNCE = id("gel_bounce"); - public static final ResourceLocation GEL_RUN = id("gel_run"); - public static final ResourceLocation GEL_SPLAT = id("gel_splat"); - public static final ResourceLocation PORTAL_GUN_PRIMARY = id("portal_gun_primary"); - public static final ResourceLocation PORTAL_GUN_SECONDARY = id("portal_gun_secondary"); - public static final ResourceLocation PORTAL_INVALID_SURFACE = id("portal_invalid_surface"); - public static final ResourceLocation PORTAL_AMBIANCE = id("portal_ambience"); - public static final ResourceLocation PORTAL_ENTER = id("portal_enter"); - public static final ResourceLocation PORTAL_EXIT = id("portal_exit"); - public static final ResourceLocation PORTAL_OPEN = id("portal_open"); - public static final ResourceLocation PORTAL_CLOSE = id("portal_close"); - public static final ResourceLocation PORTAL_FIZZLE = id("portal_fizzle"); - public static final ResourceLocation CUBE_HIT_HIGH = id("cube_hit_high"); - public static final ResourceLocation CUBE_HIT_LOW = id("cube_hit_low"); - public static final ResourceLocation CUBE_SCRAPE = id("cube_scrape"); - public static final ResourceLocation COMPANION_CUBE_AMBIANCE = id("companion_cube_ambiance"); - public static final ResourceLocation MATERIAL_EMANCIPATION = id("material_emancipation"); - public static final ResourceLocation CATAPULT_LAUNCH = id("catapult_launch"); - - public static final ResourceLocation PEDESTAL_BUTTON_PRESS = id("pedestal_button_press"); - public static final ResourceLocation PEDESTAL_BUTTON_RELEASE = id("pedestal_button_release"); - public static final ResourceLocation OLD_AP_PEDESTAL_BUTTON_PRESS = id("old_ap_pedestal_button_press"); - public static final ResourceLocation OLD_AP_PEDESTAL_BUTTON_RELEASE = id("old_ap_pedestal_button_release"); - public static final ResourceLocation FLOOR_BUTTON_PRESS = id("floor_button_press"); - public static final ResourceLocation FLOOR_BUTTON_RELEASE = id("floor_button_release"); - public static final ResourceLocation OLD_AP_FLOOR_BUTTON_PRESS = id("old_ap_floor_button_press"); - public static final ResourceLocation OLD_AP_FLOOR_BUTTON_RELEASE = id("old_ap_floor_button_release"); - - public static final ResourceLocation ROCKET_FIRE = id("rocket/fire"); - public static final ResourceLocation ROCKET_FLY = id("rocket/fly"); - public static final ResourceLocation ROCKET_LOCKED = id("rocket/locked"); - public static final ResourceLocation ROCKET_LOCKING = id("rocket/locking"); - public static final ResourceLocation ROCKET_EXPLODE = id("rocket/explode"); - public static final ResourceLocation ROCKET_GOO = id("rocket/goo"); - - public static final ResourceLocation LASER_EMITTER_ACTIVATE = id("laser/emitter_activate"); - public static final ResourceLocation LASER_BEAM_MUSIC = id("laser/beam_music"); - public static final ResourceLocation LASER_NODE_MUSIC = id("laser/node_music"); - public static final ResourceLocation LASER_NODE_ACTIVATE = id("laser/node_activate"); - public static final ResourceLocation LASER_NODE_DEACTIVATE = id("laser/node_deactivate"); - public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_1 = id("laser/triple_laser_sound_demo_1"); - public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_2 = id("laser/triple_laser_sound_demo_2"); - public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_3 = id("laser/triple_laser_sound_demo_3"); - - public static final ResourceLocation PELLET_BOUNCE = id("pellet/bounce"); - public static final ResourceLocation PELLET_EXPLODE = id("pellet/explode"); - public static final ResourceLocation PELLET_SPAWN = id("pellet/spawn"); - public static final ResourceLocation PELLET_TRAVEL = id("pellet/travel"); - - public static final ResourceLocation TBEAM_ENTER = id("tbeam/enter"); - public static final ResourceLocation TBEAM_TRAVEL = id("tbeam/travel"); - - public static final ResourceLocation BULLET_CONCRETE = id("bullet/concrete"); - public static final ResourceLocation BULLET_GLASS = id("bullet/glass"); - public static final ResourceLocation BULLET_METAL = id("bullet/metal"); - - public static final ResourceLocation RADIO_MUSIC = id("radio"); - public static final ResourceLocation EXILE_SONG = id("exile_vilify"); - public static final ResourceLocation CURIOSITY_CORE_SOUND = id("curiosity_core"); - public static final ResourceLocation ANGER_CORE_SOUND = id("anger_core"); - public static final ResourceLocation CAKE_CORE_SOUND = id("cake_core"); - - public static final ResourceLocation SPACE_CORE_SOUND = id("space_core"); - public static final ResourceLocation FACT_CORE_SOUND = id("fact_core"); - public static final ResourceLocation ADVENTURE_CORE_SOUND = id("adventure_core"); - - public static final ResourceLocation SEWAGE_STEP = id("sewage_step"); - - public static final ResourceLocation CROWBAR_SWOOSH = id("crowbar_swoosh"); - - public static final ResourceLocation GENERIC_PHYSICS_FALL = id("generic_physics_fall"); - - public static final ResourceLocation HOLD_FAIL = id("hold/fail"); - public static final ResourceLocation HOLD_START = id("hold/start"); - public static final ResourceLocation HOLD_LOOP = id("hold/loop"); - public static final ResourceLocation HOLD_STOP = id("hold/stop"); - - public static final SoundEvent ERROR_EVENT = SoundEvent.createVariableRangeEvent(ERROR); - - public static final SoundEvent GEL_BOUNCE_EVENT = SoundEvent.createVariableRangeEvent(GEL_BOUNCE); - public static final SoundEvent GEL_RUN_EVENT = SoundEvent.createVariableRangeEvent(GEL_RUN); - public static final SoundEvent GEL_SPLAT_EVENT = SoundEvent.createVariableRangeEvent(GEL_SPLAT); - public static final SoundEvent PORTAL_AMBIENT_EVENT = SoundEvent.createVariableRangeEvent(PORTAL_AMBIANCE); - public static final SoundEvent FIRE_EVENT_PRIMARY = SoundEvent.createVariableRangeEvent(PORTAL_GUN_PRIMARY); - public static final SoundEvent FIRE_EVENT_SECONDARY = SoundEvent.createVariableRangeEvent(PORTAL_GUN_SECONDARY); - public static final SoundEvent INVALID_PORTAL_EVENT = SoundEvent.createVariableRangeEvent(PORTAL_INVALID_SURFACE); - public static final SoundEvent ENTITY_ENTER_PORTAL = SoundEvent.createVariableRangeEvent(PORTAL_ENTER); - public static final SoundEvent ENTITY_EXIT_PORTAL = SoundEvent.createVariableRangeEvent(PORTAL_EXIT); - public static final SoundEvent ENTITY_PORTAL_OPEN = SoundEvent.createVariableRangeEvent(PORTAL_OPEN); - public static final SoundEvent ENTITY_PORTAL_CLOSE = SoundEvent.createVariableRangeEvent(PORTAL_CLOSE); - public static final SoundEvent ENTITY_PORTAL_FIZZLE = SoundEvent.createVariableRangeEvent(PORTAL_FIZZLE); - public static final SoundEvent CUBE_HIGH_HIT_EVENT = SoundEvent.createVariableRangeEvent(CUBE_HIT_HIGH); - public static final SoundEvent CUBE_LOW_HIT_EVENT = SoundEvent.createVariableRangeEvent(CUBE_HIT_LOW); - public static final SoundEvent CUBE_SCRAPE_EVENT = SoundEvent.createVariableRangeEvent(CUBE_SCRAPE); - public static final SoundEvent COMPANION_CUBE_AMBIANCE_EVENT = SoundEvent.createVariableRangeEvent(COMPANION_CUBE_AMBIANCE); - public static final SoundEvent MATERIAL_EMANCIPATION_EVENT = SoundEvent.createVariableRangeEvent(MATERIAL_EMANCIPATION); - public static final SoundEvent CATAPULT_LAUNCH_EVENT = SoundEvent.createVariableRangeEvent(CATAPULT_LAUNCH); - - public static final SoundEvent PEDESTAL_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(PEDESTAL_BUTTON_PRESS); - public static final SoundEvent PEDESTAL_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(PEDESTAL_BUTTON_RELEASE); - public static final SoundEvent OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_PEDESTAL_BUTTON_PRESS); - public static final SoundEvent OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_PEDESTAL_BUTTON_RELEASE); - public static final SoundEvent FLOOR_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(FLOOR_BUTTON_PRESS); - public static final SoundEvent FLOOR_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(FLOOR_BUTTON_RELEASE); - public static final SoundEvent OLD_AP_FLOOR_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_FLOOR_BUTTON_PRESS); - public static final SoundEvent OLD_AP_FLOOR_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_FLOOR_BUTTON_RELEASE); - - public static final SoundEvent ROCKET_FIRE_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_FIRE); - public static final SoundEvent ROCKET_FLY_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_FLY); - public static final SoundEvent ROCKET_LOCKED_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_LOCKED); - public static final SoundEvent ROCKET_LOCKING_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_LOCKING); - public static final SoundEvent ROCKET_EXPLODE_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_EXPLODE); - public static final SoundEvent ROCKET_GOO_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_GOO); - - public static final SoundEvent LASER_EMITTER_ACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_EMITTER_ACTIVATE); - public static final SoundEvent LASER_BEAM_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(LASER_BEAM_MUSIC); - public static final SoundEvent LASER_NODE_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_MUSIC); - public static final SoundEvent LASER_NODE_ACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_ACTIVATE); - public static final SoundEvent LASER_NODE_DEACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_DEACTIVATE); - public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_1_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_1); - public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_2_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_2); - public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_3_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_3); - - public static final SoundEvent PELLET_BOUNCE_EVENT = SoundEvent.createVariableRangeEvent(PELLET_BOUNCE); - public static final SoundEvent PELLET_EXPLODE_EVENT = SoundEvent.createVariableRangeEvent(PELLET_EXPLODE); - public static final SoundEvent PELLET_SPAWN_EVENT = SoundEvent.createVariableRangeEvent(PELLET_SPAWN); - public static final SoundEvent PELLET_TRAVEL_EVENT = SoundEvent.createVariableRangeEvent(PELLET_TRAVEL); - - public static final SoundEvent TBEAM_ENTER_EVENT = SoundEvent.createVariableRangeEvent(TBEAM_ENTER); - public static final SoundEvent TBEAM_TRAVEL_EVENT = SoundEvent.createVariableRangeEvent(TBEAM_TRAVEL); - - public static final SoundEvent BULLET_CONCRETE_EVENT = SoundEvent.createVariableRangeEvent(BULLET_CONCRETE); - public static final SoundEvent BULLET_GLASS_EVENT = SoundEvent.createVariableRangeEvent(BULLET_GLASS); - public static final SoundEvent BULLET_METAL_EVENT = SoundEvent.createVariableRangeEvent(BULLET_METAL); - - public static final SoundEvent RADIO_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(RADIO_MUSIC); - public static final SoundEvent EXILE_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(EXILE_SONG); - public static final SoundEvent CURIOSITY_CORE_EVENT = SoundEvent.createVariableRangeEvent(CURIOSITY_CORE_SOUND); - public static final SoundEvent ANGER_CORE_EVENT = SoundEvent.createVariableRangeEvent(ANGER_CORE_SOUND); - public static final SoundEvent CAKE_CORE_EVENT = SoundEvent.createVariableRangeEvent(CAKE_CORE_SOUND); - public static final SoundEvent SPACE_CORE_EVENT = SoundEvent.createVariableRangeEvent(SPACE_CORE_SOUND); - public static final SoundEvent FACT_CORE_EVENT = SoundEvent.createVariableRangeEvent(FACT_CORE_SOUND); - public static final SoundEvent ADVENTURE_CORE_EVENT = SoundEvent.createVariableRangeEvent(ADVENTURE_CORE_SOUND); - - public static final SoundEvent SEWAGE_STEP_EVENT = SoundEvent.createVariableRangeEvent(SEWAGE_STEP); - - public static final SoundEvent CROWBAR_SWOOSH_EVENT = SoundEvent.createVariableRangeEvent(CROWBAR_SWOOSH); - - public static final SoundEvent GENERIC_PHYSICS_FALL_EVENT = SoundEvent.createVariableRangeEvent(GENERIC_PHYSICS_FALL); - - public static final SoundEvent HOLD_FAIL_EVENT = SoundEvent.createVariableRangeEvent(HOLD_FAIL); - public static final SoundEvent HOLD_START_EVENT = SoundEvent.createVariableRangeEvent(HOLD_START); - public static final SoundEvent HOLD_LOOP_EVENT = SoundEvent.createVariableRangeEvent(HOLD_LOOP); - public static final SoundEvent HOLD_STOP_EVENT = SoundEvent.createVariableRangeEvent(HOLD_STOP); - - public static final TagKey NO_ERROR_SOUND = QuiltTagKey.of(Registries.SOUND_EVENT, id("no_error_sound"), TagType.CLIENT_ONLY); - - public static void registerSounds() { - Registry.register(BuiltInRegistries.SOUND_EVENT, ERROR, ERROR_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_BOUNCE, GEL_BOUNCE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_RUN, GEL_RUN_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_SPLAT, GEL_SPLAT_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_AMBIANCE, PORTAL_AMBIENT_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_GUN_PRIMARY, FIRE_EVENT_PRIMARY); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_GUN_SECONDARY, FIRE_EVENT_SECONDARY); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_INVALID_SURFACE, INVALID_PORTAL_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_ENTER, ENTITY_ENTER_PORTAL); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_EXIT, ENTITY_EXIT_PORTAL); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_OPEN, ENTITY_PORTAL_OPEN); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_CLOSE, ENTITY_PORTAL_CLOSE); - Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_FIZZLE, ENTITY_PORTAL_FIZZLE); - Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_HIT_HIGH, CUBE_HIGH_HIT_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_HIT_LOW, CUBE_LOW_HIT_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_SCRAPE, CUBE_SCRAPE_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, COMPANION_CUBE_AMBIANCE, COMPANION_CUBE_AMBIANCE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, MATERIAL_EMANCIPATION, MATERIAL_EMANCIPATION_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, CATAPULT_LAUNCH, CATAPULT_LAUNCH_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, PEDESTAL_BUTTON_PRESS, PEDESTAL_BUTTON_PRESS_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PEDESTAL_BUTTON_RELEASE, PEDESTAL_BUTTON_RELEASE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_PEDESTAL_BUTTON_PRESS, OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_PEDESTAL_BUTTON_RELEASE, OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, FLOOR_BUTTON_PRESS, FLOOR_BUTTON_PRESS_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, FLOOR_BUTTON_RELEASE, FLOOR_BUTTON_RELEASE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_FLOOR_BUTTON_PRESS, OLD_AP_FLOOR_BUTTON_PRESS_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_FLOOR_BUTTON_RELEASE, OLD_AP_FLOOR_BUTTON_RELEASE_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_FIRE, ROCKET_FIRE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_FLY, ROCKET_FLY_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_LOCKED, ROCKET_LOCKED_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_LOCKING, ROCKET_LOCKING_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_EXPLODE, ROCKET_EXPLODE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_GOO, ROCKET_GOO_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_EMITTER_ACTIVATE, LASER_EMITTER_ACTIVATE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_BEAM_MUSIC, LASER_BEAM_MUSIC_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_MUSIC, LASER_NODE_MUSIC_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_ACTIVATE, LASER_NODE_ACTIVATE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_DEACTIVATE, LASER_NODE_DEACTIVATE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_1, LASER_TRIPLE_LASER_SOUND_DEMO_1_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_2, LASER_TRIPLE_LASER_SOUND_DEMO_2_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_3, LASER_TRIPLE_LASER_SOUND_DEMO_3_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_BOUNCE, PELLET_BOUNCE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_EXPLODE, PELLET_EXPLODE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_SPAWN, PELLET_SPAWN_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_TRAVEL, PELLET_TRAVEL_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, TBEAM_ENTER, TBEAM_ENTER_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, TBEAM_TRAVEL, TBEAM_TRAVEL_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_CONCRETE, BULLET_CONCRETE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_GLASS, BULLET_GLASS_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_METAL, BULLET_METAL_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, RADIO_MUSIC, RADIO_MUSIC_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, EXILE_SONG, EXILE_MUSIC_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, CURIOSITY_CORE_SOUND, CURIOSITY_CORE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ANGER_CORE_SOUND, ANGER_CORE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, CAKE_CORE_SOUND, CAKE_CORE_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, SPACE_CORE_SOUND, SPACE_CORE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, FACT_CORE_SOUND, FACT_CORE_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, ADVENTURE_CORE_SOUND, ADVENTURE_CORE_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, SEWAGE_STEP, SEWAGE_STEP_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, CROWBAR_SWOOSH, CROWBAR_SWOOSH_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, GENERIC_PHYSICS_FALL, GENERIC_PHYSICS_FALL_EVENT); - - Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_FAIL, HOLD_FAIL_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_START, HOLD_START_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_LOOP, HOLD_LOOP_EVENT); - Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_STOP, HOLD_STOP_EVENT); - } + public static final ResourceLocation ERROR = id("error"); + + public static final ResourceLocation GEL_BOUNCE = id("gel_bounce"); + public static final ResourceLocation GEL_RUN = id("gel_run"); + public static final ResourceLocation GEL_SPLAT = id("gel_splat"); + public static final ResourceLocation PORTAL_GUN_PRIMARY = id("portal_gun_primary"); + public static final ResourceLocation PORTAL_GUN_SECONDARY = id("portal_gun_secondary"); + public static final ResourceLocation PORTAL_INVALID_SURFACE = id("portal_invalid_surface"); + public static final ResourceLocation PORTAL_AMBIANCE = id("portal_ambience"); + public static final ResourceLocation PORTAL_ENTER = id("portal_enter"); + public static final ResourceLocation PORTAL_EXIT = id("portal_exit"); + public static final ResourceLocation PORTAL_OPEN = id("portal_open"); + public static final ResourceLocation PORTAL_CLOSE = id("portal_close"); + public static final ResourceLocation PORTAL_FIZZLE = id("portal_fizzle"); + public static final ResourceLocation CUBE_HIT_HIGH = id("cube_hit_high"); + public static final ResourceLocation CUBE_HIT_LOW = id("cube_hit_low"); + public static final ResourceLocation CUBE_SCRAPE = id("cube_scrape"); + public static final ResourceLocation COMPANION_CUBE_AMBIANCE = id("companion_cube_ambiance"); + public static final ResourceLocation MATERIAL_EMANCIPATION = id("material_emancipation"); + public static final ResourceLocation CATAPULT_LAUNCH = id("catapult_launch"); + + public static final ResourceLocation PEDESTAL_BUTTON_PRESS = id("pedestal_button_press"); + public static final ResourceLocation PEDESTAL_BUTTON_RELEASE = id("pedestal_button_release"); + public static final ResourceLocation OLD_AP_PEDESTAL_BUTTON_PRESS = id("old_ap_pedestal_button_press"); + public static final ResourceLocation OLD_AP_PEDESTAL_BUTTON_RELEASE = id("old_ap_pedestal_button_release"); + public static final ResourceLocation FLOOR_BUTTON_PRESS = id("floor_button_press"); + public static final ResourceLocation FLOOR_BUTTON_RELEASE = id("floor_button_release"); + public static final ResourceLocation OLD_AP_FLOOR_BUTTON_PRESS = id("old_ap_floor_button_press"); + public static final ResourceLocation OLD_AP_FLOOR_BUTTON_RELEASE = id("old_ap_floor_button_release"); + + public static final ResourceLocation ROCKET_FIRE = id("rocket/fire"); + public static final ResourceLocation ROCKET_FLY = id("rocket/fly"); + public static final ResourceLocation ROCKET_LOCKED = id("rocket/locked"); + public static final ResourceLocation ROCKET_LOCKING = id("rocket/locking"); + public static final ResourceLocation ROCKET_EXPLODE = id("rocket/explode"); + public static final ResourceLocation ROCKET_GOO = id("rocket/goo"); + + public static final ResourceLocation LASER_EMITTER_ACTIVATE = id("laser/emitter_activate"); + public static final ResourceLocation LASER_BEAM_MUSIC = id("laser/beam_music"); + public static final ResourceLocation LASER_NODE_MUSIC = id("laser/node_music"); + public static final ResourceLocation LASER_NODE_ACTIVATE = id("laser/node_activate"); + public static final ResourceLocation LASER_NODE_DEACTIVATE = id("laser/node_deactivate"); + public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_1 = id("laser/triple_laser_sound_demo_1"); + public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_2 = id("laser/triple_laser_sound_demo_2"); + public static final ResourceLocation LASER_TRIPLE_LASER_SOUND_DEMO_3 = id("laser/triple_laser_sound_demo_3"); + + public static final ResourceLocation PELLET_BOUNCE = id("pellet/bounce"); + public static final ResourceLocation PELLET_EXPLODE = id("pellet/explode"); + public static final ResourceLocation PELLET_SPAWN = id("pellet/spawn"); + public static final ResourceLocation PELLET_TRAVEL = id("pellet/travel"); + + public static final ResourceLocation TBEAM_ENTER = id("tbeam/enter"); + public static final ResourceLocation TBEAM_TRAVEL = id("tbeam/travel"); + + public static final ResourceLocation BULLET_CONCRETE = id("bullet/concrete"); + public static final ResourceLocation BULLET_GLASS = id("bullet/glass"); + public static final ResourceLocation BULLET_METAL = id("bullet/metal"); + + public static final ResourceLocation RADIO_MUSIC = id("radio"); + public static final ResourceLocation EXILE_SONG = id("exile_vilify"); + public static final ResourceLocation CURIOSITY_CORE_SOUND = id("curiosity_core"); + public static final ResourceLocation ANGER_CORE_SOUND = id("anger_core"); + public static final ResourceLocation CAKE_CORE_SOUND = id("cake_core"); + + public static final ResourceLocation SPACE_CORE_SOUND = id("space_core"); + public static final ResourceLocation FACT_CORE_SOUND = id("fact_core"); + public static final ResourceLocation ADVENTURE_CORE_SOUND = id("adventure_core"); + + public static final ResourceLocation SEWAGE_STEP = id("sewage_step"); + + public static final ResourceLocation CROWBAR_SWOOSH = id("crowbar_swoosh"); + + public static final ResourceLocation GENERIC_PHYSICS_FALL = id("generic_physics_fall"); + + public static final ResourceLocation HOLD_FAIL = id("hold/fail"); + public static final ResourceLocation HOLD_START = id("hold/start"); + public static final ResourceLocation HOLD_LOOP = id("hold/loop"); + public static final ResourceLocation HOLD_STOP = id("hold/stop"); + + public static final SoundEvent ERROR_EVENT = SoundEvent.createVariableRangeEvent(ERROR); + + public static final SoundEvent GEL_BOUNCE_EVENT = SoundEvent.createVariableRangeEvent(GEL_BOUNCE); + public static final SoundEvent GEL_RUN_EVENT = SoundEvent.createVariableRangeEvent(GEL_RUN); + public static final SoundEvent GEL_SPLAT_EVENT = SoundEvent.createVariableRangeEvent(GEL_SPLAT); + public static final SoundEvent PORTAL_AMBIENT_EVENT = SoundEvent.createVariableRangeEvent(PORTAL_AMBIANCE); + public static final SoundEvent FIRE_EVENT_PRIMARY = SoundEvent.createVariableRangeEvent(PORTAL_GUN_PRIMARY); + public static final SoundEvent FIRE_EVENT_SECONDARY = SoundEvent.createVariableRangeEvent(PORTAL_GUN_SECONDARY); + public static final SoundEvent INVALID_PORTAL_EVENT = SoundEvent.createVariableRangeEvent(PORTAL_INVALID_SURFACE); + public static final SoundEvent ENTITY_ENTER_PORTAL = SoundEvent.createVariableRangeEvent(PORTAL_ENTER); + public static final SoundEvent ENTITY_EXIT_PORTAL = SoundEvent.createVariableRangeEvent(PORTAL_EXIT); + public static final SoundEvent ENTITY_PORTAL_OPEN = SoundEvent.createVariableRangeEvent(PORTAL_OPEN); + public static final SoundEvent ENTITY_PORTAL_CLOSE = SoundEvent.createVariableRangeEvent(PORTAL_CLOSE); + public static final SoundEvent ENTITY_PORTAL_FIZZLE = SoundEvent.createVariableRangeEvent(PORTAL_FIZZLE); + public static final SoundEvent CUBE_HIGH_HIT_EVENT = SoundEvent.createVariableRangeEvent(CUBE_HIT_HIGH); + public static final SoundEvent CUBE_LOW_HIT_EVENT = SoundEvent.createVariableRangeEvent(CUBE_HIT_LOW); + public static final SoundEvent CUBE_SCRAPE_EVENT = SoundEvent.createVariableRangeEvent(CUBE_SCRAPE); + public static final SoundEvent COMPANION_CUBE_AMBIANCE_EVENT = SoundEvent.createVariableRangeEvent(COMPANION_CUBE_AMBIANCE); + public static final SoundEvent MATERIAL_EMANCIPATION_EVENT = SoundEvent.createVariableRangeEvent(MATERIAL_EMANCIPATION); + public static final SoundEvent CATAPULT_LAUNCH_EVENT = SoundEvent.createVariableRangeEvent(CATAPULT_LAUNCH); + + public static final SoundEvent PEDESTAL_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(PEDESTAL_BUTTON_PRESS); + public static final SoundEvent PEDESTAL_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(PEDESTAL_BUTTON_RELEASE); + public static final SoundEvent OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_PEDESTAL_BUTTON_PRESS); + public static final SoundEvent OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_PEDESTAL_BUTTON_RELEASE); + public static final SoundEvent FLOOR_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(FLOOR_BUTTON_PRESS); + public static final SoundEvent FLOOR_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(FLOOR_BUTTON_RELEASE); + public static final SoundEvent OLD_AP_FLOOR_BUTTON_PRESS_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_FLOOR_BUTTON_PRESS); + public static final SoundEvent OLD_AP_FLOOR_BUTTON_RELEASE_EVENT = SoundEvent.createVariableRangeEvent(OLD_AP_FLOOR_BUTTON_RELEASE); + + public static final SoundEvent ROCKET_FIRE_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_FIRE); + public static final SoundEvent ROCKET_FLY_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_FLY); + public static final SoundEvent ROCKET_LOCKED_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_LOCKED); + public static final SoundEvent ROCKET_LOCKING_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_LOCKING); + public static final SoundEvent ROCKET_EXPLODE_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_EXPLODE); + public static final SoundEvent ROCKET_GOO_EVENT = SoundEvent.createVariableRangeEvent(ROCKET_GOO); + + public static final SoundEvent LASER_EMITTER_ACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_EMITTER_ACTIVATE); + public static final SoundEvent LASER_BEAM_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(LASER_BEAM_MUSIC); + public static final SoundEvent LASER_NODE_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_MUSIC); + public static final SoundEvent LASER_NODE_ACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_ACTIVATE); + public static final SoundEvent LASER_NODE_DEACTIVATE_EVENT = SoundEvent.createVariableRangeEvent(LASER_NODE_DEACTIVATE); + public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_1_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_1); + public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_2_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_2); + public static final SoundEvent LASER_TRIPLE_LASER_SOUND_DEMO_3_EVENT = SoundEvent.createVariableRangeEvent(LASER_TRIPLE_LASER_SOUND_DEMO_3); + + public static final SoundEvent PELLET_BOUNCE_EVENT = SoundEvent.createVariableRangeEvent(PELLET_BOUNCE); + public static final SoundEvent PELLET_EXPLODE_EVENT = SoundEvent.createVariableRangeEvent(PELLET_EXPLODE); + public static final SoundEvent PELLET_SPAWN_EVENT = SoundEvent.createVariableRangeEvent(PELLET_SPAWN); + public static final SoundEvent PELLET_TRAVEL_EVENT = SoundEvent.createVariableRangeEvent(PELLET_TRAVEL); + + public static final SoundEvent TBEAM_ENTER_EVENT = SoundEvent.createVariableRangeEvent(TBEAM_ENTER); + public static final SoundEvent TBEAM_TRAVEL_EVENT = SoundEvent.createVariableRangeEvent(TBEAM_TRAVEL); + + public static final SoundEvent BULLET_CONCRETE_EVENT = SoundEvent.createVariableRangeEvent(BULLET_CONCRETE); + public static final SoundEvent BULLET_GLASS_EVENT = SoundEvent.createVariableRangeEvent(BULLET_GLASS); + public static final SoundEvent BULLET_METAL_EVENT = SoundEvent.createVariableRangeEvent(BULLET_METAL); + + public static final SoundEvent RADIO_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(RADIO_MUSIC); + public static final SoundEvent EXILE_MUSIC_EVENT = SoundEvent.createVariableRangeEvent(EXILE_SONG); + public static final SoundEvent CURIOSITY_CORE_EVENT = SoundEvent.createVariableRangeEvent(CURIOSITY_CORE_SOUND); + public static final SoundEvent ANGER_CORE_EVENT = SoundEvent.createVariableRangeEvent(ANGER_CORE_SOUND); + public static final SoundEvent CAKE_CORE_EVENT = SoundEvent.createVariableRangeEvent(CAKE_CORE_SOUND); + public static final SoundEvent SPACE_CORE_EVENT = SoundEvent.createVariableRangeEvent(SPACE_CORE_SOUND); + public static final SoundEvent FACT_CORE_EVENT = SoundEvent.createVariableRangeEvent(FACT_CORE_SOUND); + public static final SoundEvent ADVENTURE_CORE_EVENT = SoundEvent.createVariableRangeEvent(ADVENTURE_CORE_SOUND); + + public static final SoundEvent SEWAGE_STEP_EVENT = SoundEvent.createVariableRangeEvent(SEWAGE_STEP); + + public static final SoundEvent CROWBAR_SWOOSH_EVENT = SoundEvent.createVariableRangeEvent(CROWBAR_SWOOSH); + + public static final SoundEvent GENERIC_PHYSICS_FALL_EVENT = SoundEvent.createVariableRangeEvent(GENERIC_PHYSICS_FALL); + + public static final SoundEvent HOLD_FAIL_EVENT = SoundEvent.createVariableRangeEvent(HOLD_FAIL); + public static final SoundEvent HOLD_START_EVENT = SoundEvent.createVariableRangeEvent(HOLD_START); + public static final SoundEvent HOLD_LOOP_EVENT = SoundEvent.createVariableRangeEvent(HOLD_LOOP); + public static final SoundEvent HOLD_STOP_EVENT = SoundEvent.createVariableRangeEvent(HOLD_STOP); + + public static final TagKey NO_ERROR_SOUND = QuiltTagKey.of(Registries.SOUND_EVENT, id("no_error_sound"), TagType.CLIENT_ONLY); + + public static void registerSounds() { + Registry.register(BuiltInRegistries.SOUND_EVENT, ERROR, ERROR_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_BOUNCE, GEL_BOUNCE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_RUN, GEL_RUN_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, GEL_SPLAT, GEL_SPLAT_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_AMBIANCE, PORTAL_AMBIENT_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_GUN_PRIMARY, FIRE_EVENT_PRIMARY); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_GUN_SECONDARY, FIRE_EVENT_SECONDARY); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_INVALID_SURFACE, INVALID_PORTAL_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_ENTER, ENTITY_ENTER_PORTAL); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_EXIT, ENTITY_EXIT_PORTAL); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_OPEN, ENTITY_PORTAL_OPEN); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_CLOSE, ENTITY_PORTAL_CLOSE); + Registry.register(BuiltInRegistries.SOUND_EVENT, PORTAL_FIZZLE, ENTITY_PORTAL_FIZZLE); + Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_HIT_HIGH, CUBE_HIGH_HIT_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_HIT_LOW, CUBE_LOW_HIT_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, CUBE_SCRAPE, CUBE_SCRAPE_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, COMPANION_CUBE_AMBIANCE, COMPANION_CUBE_AMBIANCE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, MATERIAL_EMANCIPATION, MATERIAL_EMANCIPATION_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, CATAPULT_LAUNCH, CATAPULT_LAUNCH_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, PEDESTAL_BUTTON_PRESS, PEDESTAL_BUTTON_PRESS_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PEDESTAL_BUTTON_RELEASE, PEDESTAL_BUTTON_RELEASE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_PEDESTAL_BUTTON_PRESS, OLD_AP_PEDESTAL_BUTTON_PRESS_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_PEDESTAL_BUTTON_RELEASE, OLD_AP_PEDESTAL_BUTTON_RELEASE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, FLOOR_BUTTON_PRESS, FLOOR_BUTTON_PRESS_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, FLOOR_BUTTON_RELEASE, FLOOR_BUTTON_RELEASE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_FLOOR_BUTTON_PRESS, OLD_AP_FLOOR_BUTTON_PRESS_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, OLD_AP_FLOOR_BUTTON_RELEASE, OLD_AP_FLOOR_BUTTON_RELEASE_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_FIRE, ROCKET_FIRE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_FLY, ROCKET_FLY_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_LOCKED, ROCKET_LOCKED_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_LOCKING, ROCKET_LOCKING_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_EXPLODE, ROCKET_EXPLODE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ROCKET_GOO, ROCKET_GOO_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_EMITTER_ACTIVATE, LASER_EMITTER_ACTIVATE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_BEAM_MUSIC, LASER_BEAM_MUSIC_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_MUSIC, LASER_NODE_MUSIC_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_ACTIVATE, LASER_NODE_ACTIVATE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_NODE_DEACTIVATE, LASER_NODE_DEACTIVATE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_1, LASER_TRIPLE_LASER_SOUND_DEMO_1_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_2, LASER_TRIPLE_LASER_SOUND_DEMO_2_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, LASER_TRIPLE_LASER_SOUND_DEMO_3, LASER_TRIPLE_LASER_SOUND_DEMO_3_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_BOUNCE, PELLET_BOUNCE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_EXPLODE, PELLET_EXPLODE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_SPAWN, PELLET_SPAWN_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, PELLET_TRAVEL, PELLET_TRAVEL_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, TBEAM_ENTER, TBEAM_ENTER_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, TBEAM_TRAVEL, TBEAM_TRAVEL_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_CONCRETE, BULLET_CONCRETE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_GLASS, BULLET_GLASS_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, BULLET_METAL, BULLET_METAL_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, RADIO_MUSIC, RADIO_MUSIC_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, EXILE_SONG, EXILE_MUSIC_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, CURIOSITY_CORE_SOUND, CURIOSITY_CORE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ANGER_CORE_SOUND, ANGER_CORE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, CAKE_CORE_SOUND, CAKE_CORE_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, SPACE_CORE_SOUND, SPACE_CORE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, FACT_CORE_SOUND, FACT_CORE_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, ADVENTURE_CORE_SOUND, ADVENTURE_CORE_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, SEWAGE_STEP, SEWAGE_STEP_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, CROWBAR_SWOOSH, CROWBAR_SWOOSH_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, GENERIC_PHYSICS_FALL, GENERIC_PHYSICS_FALL_EVENT); + + Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_FAIL, HOLD_FAIL_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_START, HOLD_START_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_LOOP, HOLD_LOOP_EVENT); + Registry.register(BuiltInRegistries.SOUND_EVENT, HOLD_STOP, HOLD_STOP_EVENT); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/AdvancedEntityRaycast.java b/src/main/java/com/fusionflux/portalcubed/util/AdvancedEntityRaycast.java index 03bc5494..1ffa813f 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/AdvancedEntityRaycast.java +++ b/src/main/java/com/fusionflux/portalcubed/util/AdvancedEntityRaycast.java @@ -22,134 +22,134 @@ import java.util.function.Supplier; public class AdvancedEntityRaycast { - public record TransformInfo( - Predicate<@NotNull Entity> hittable, - Transform transform - ) { - @FunctionalInterface - public interface Transform { - @Nullable - TransformResult transform( - @NotNull ClipContext context, - @NotNull BlockHitResult blockHit, - @NotNull EntityHitResult entityHit - ); - } - } + public record TransformInfo( + Predicate<@NotNull Entity> hittable, + Transform transform + ) { + @FunctionalInterface + public interface Transform { + @Nullable + TransformResult transform( + @NotNull ClipContext context, + @NotNull BlockHitResult blockHit, + @NotNull EntityHitResult entityHit + ); + } + } - public record TransformResult( - Vec3 prevHitPos, - @Nullable ClipContext newContext, - Set ignoredEntities - ) { - public TransformResult(Vec3 prevHitPos, @Nullable ClipContext newContext) { - this(prevHitPos, newContext, Set.of()); - } - } + public record TransformResult( + Vec3 prevHitPos, + @Nullable ClipContext newContext, + Set ignoredEntities + ) { + public TransformResult(Vec3 prevHitPos, @Nullable ClipContext newContext) { + this(prevHitPos, newContext, Set.of()); + } + } - public record Result( - List rays - ) { - public record Ray(Vec3 start, Vec3 end, HitResult hit) { - public Ray(Vec3 start, HitResult hit) { - this(start, hit.getLocation(), hit); - } + public record Result( + List rays + ) { + public record Ray(Vec3 start, Vec3 end, HitResult hit) { + public Ray(Vec3 start, HitResult hit) { + this(start, hit.getLocation(), hit); + } - public Vec3 relative() { - return end.subtract(start); - } + public Vec3 relative() { + return end.subtract(start); + } - @Nullable - public EntityHitResult entityRaycast(@NotNull Entity owner, Predicate predicate) { - return ProjectileUtil.getEntityHitResult( - owner, start, end, new AABB(start, end).inflate(1), predicate, start.distanceToSqr(end) - ); - } - } + @Nullable + public EntityHitResult entityRaycast(@NotNull Entity owner, Predicate predicate) { + return ProjectileUtil.getEntityHitResult( + owner, start, end, new AABB(start, end).inflate(1), predicate, start.distanceToSqr(end) + ); + } + } - public Result { - Validate.isTrue(!rays.isEmpty(), "AdvancedEntityRaycast.Result must have at least one ray."); - } + public Result { + Validate.isTrue(!rays.isEmpty(), "AdvancedEntityRaycast.Result must have at least one ray."); + } - public Ray finalRay() { - return rays.get(rays.size() - 1); - } + public Ray finalRay() { + return rays.get(rays.size() - 1); + } - public HitResult finalHit() { - return finalRay().hit; - } + public HitResult finalHit() { + return finalRay().hit; + } - @Nullable - public EntityHitResult entityRaycast(@NotNull Entity owner, Predicate predicate) { - for (final Ray ray : rays) { - final EntityHitResult hit = ray.entityRaycast(owner, predicate); - if (hit != null) return hit; - } - return null; - } + @Nullable + public EntityHitResult entityRaycast(@NotNull Entity owner, Predicate predicate) { + for (final Ray ray : rays) { + final EntityHitResult hit = ray.entityRaycast(owner, predicate); + if (hit != null) return hit; + } + return null; + } - public double length() { - double length = 0; - for (final Ray ray : rays) { - length += ray.start.distanceTo(ray.end); - } - return length; - } - } + public double length() { + double length = 0; + for (final Ray ray : rays) { + length += ray.start.distanceTo(ray.end); + } + return length; + } + } - public static Result raycast( - Level level, - ClipContext context, - BiFunction clipper, - TransformInfo... transforms - ) { - final List hits = new ArrayList<>(); - final Supplier marker = Suppliers.memoize(() -> EntityType.MARKER.create(level)); - @SuppressWarnings("unchecked") Set[] ignoredEntities = new Set[] {Set.of()}; - final Predicate predicate = Arrays.stream(transforms) - .map(TransformInfo::hittable) - .reduce(Predicate::or) - .map(p -> p.and(e -> !ignoredEntities[0].contains(e))) - .orElse(null); - BlockHitResult result; - mainLoop: - while (true) { - result = clipper.apply(level, context); - if (predicate == null) break; - final Vec3 offset = result.getLocation().subtract(context.getFrom()); - final EntityHitResult hit = ProjectileUtil.getEntityHitResult( - marker.get(), context.getFrom(), result.getLocation(), new AABB(context.getFrom(), result.getLocation()).inflate(1), - predicate, offset.lengthSqr() - ); - if (hit == null) break; - for (final var transform : transforms) { - if (transform.hittable.test(hit.getEntity())) { - final TransformResult newContext = transform.transform.transform(context, result, hit); - if (newContext != null) { - ignoredEntities[0] = newContext.ignoredEntities; - hits.add(new Result.Ray(context.getFrom(), newContext.prevHitPos, hit)); - context = newContext.newContext; - if (context == null) { - return new Result(hits); - } - continue mainLoop; - } - } - } - break; - } - hits.add(new Result.Ray(context.getFrom(), result)); - return new Result(hits); - } + public static Result raycast( + Level level, + ClipContext context, + BiFunction clipper, + TransformInfo... transforms + ) { + final List hits = new ArrayList<>(); + final Supplier marker = Suppliers.memoize(() -> EntityType.MARKER.create(level)); + @SuppressWarnings("unchecked") Set[] ignoredEntities = new Set[] {Set.of()}; + final Predicate predicate = Arrays.stream(transforms) + .map(TransformInfo::hittable) + .reduce(Predicate::or) + .map(p -> p.and(e -> !ignoredEntities[0].contains(e))) + .orElse(null); + BlockHitResult result; + mainLoop: + while (true) { + result = clipper.apply(level, context); + if (predicate == null) break; + final Vec3 offset = result.getLocation().subtract(context.getFrom()); + final EntityHitResult hit = ProjectileUtil.getEntityHitResult( + marker.get(), context.getFrom(), result.getLocation(), new AABB(context.getFrom(), result.getLocation()).inflate(1), + predicate, offset.lengthSqr() + ); + if (hit == null) break; + for (final var transform : transforms) { + if (transform.hittable.test(hit.getEntity())) { + final TransformResult newContext = transform.transform.transform(context, result, hit); + if (newContext != null) { + ignoredEntities[0] = newContext.ignoredEntities; + hits.add(new Result.Ray(context.getFrom(), newContext.prevHitPos, hit)); + context = newContext.newContext; + if (context == null) { + return new Result(hits); + } + continue mainLoop; + } + } + } + break; + } + hits.add(new Result.Ray(context.getFrom(), result)); + return new Result(hits); + } - public static ClipContext withStartEnd(ClipContext context, Vec3 start, Vec3 end) { - //noinspection DataFlowIssue - return new ClipContext( - start, end, - ((ClipContextAccessor)context).getBlock(), - ((ClipContextAccessor)context).getFluid(), - ((ClipContextAccessor)context).getCollisionContext() instanceof EntityCollisionContext esc - ? esc.getEntity() : null - ); - } + public static ClipContext withStartEnd(ClipContext context, Vec3 start, Vec3 end) { + //noinspection DataFlowIssue + return new ClipContext( + start, end, + ((ClipContextAccessor)context).getBlock(), + ((ClipContextAccessor)context).getFluid(), + ((ClipContextAccessor)context).getCollisionContext() instanceof EntityCollisionContext esc + ? esc.getEntity() : null + ); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/BlockEntityWrapperEntity.java b/src/main/java/com/fusionflux/portalcubed/util/BlockEntityWrapperEntity.java index be3d8482..a0cd174f 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/BlockEntityWrapperEntity.java +++ b/src/main/java/com/fusionflux/portalcubed/util/BlockEntityWrapperEntity.java @@ -9,32 +9,32 @@ import org.jetbrains.annotations.NotNull; public final class BlockEntityWrapperEntity extends Entity { - private final E blockEntity; - - public BlockEntityWrapperEntity(E blockEntity) { - super(EntityType.PIG, blockEntity.getLevel()); - this.blockEntity = blockEntity; - } - - @Override - protected void defineSynchedData() { - } - - @Override - protected void readAdditionalSaveData(CompoundTag nbt) { - } - - @Override - protected void addAdditionalSaveData(CompoundTag nbt) { - } - - @NotNull - @Override - public Packet getAddEntityPacket() { - throw new UnsupportedOperationException("Shouldn't call getAddEntityPacket() on BlockEntityWrapperEntity."); - } - - public E getBlockEntity() { - return blockEntity; - } + private final E blockEntity; + + public BlockEntityWrapperEntity(E blockEntity) { + super(EntityType.PIG, blockEntity.getLevel()); + this.blockEntity = blockEntity; + } + + @Override + protected void defineSynchedData() { + } + + @Override + protected void readAdditionalSaveData(CompoundTag nbt) { + } + + @Override + protected void addAdditionalSaveData(CompoundTag nbt) { + } + + @NotNull + @Override + public Packet getAddEntityPacket() { + throw new UnsupportedOperationException("Shouldn't call getAddEntityPacket() on BlockEntityWrapperEntity."); + } + + public E getBlockEntity() { + return blockEntity; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/CameraControl.java b/src/main/java/com/fusionflux/portalcubed/util/CameraControl.java index 8d9b86ba..aad9cd99 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/CameraControl.java +++ b/src/main/java/com/fusionflux/portalcubed/util/CameraControl.java @@ -3,36 +3,36 @@ import net.minecraft.world.phys.Vec3; public class CameraControl { - private Vec3 pos; - private float yaw, pitch; - - public CameraControl(Vec3 pos, float yaw, float pitch) { - this.pos = pos; - this.yaw = yaw; - this.pitch = pitch; - } - - public Vec3 getPos() { - return pos; - } - - public void setPos(Vec3 pos) { - this.pos = pos; - } - - public float getYaw() { - return yaw; - } - - public void setYaw(float yaw) { - this.yaw = yaw; - } - - public float getPitch() { - return pitch; - } - - public void setPitch(float pitch) { - this.pitch = pitch; - } + private Vec3 pos; + private float yaw, pitch; + + public CameraControl(Vec3 pos, float yaw, float pitch) { + this.pos = pos; + this.yaw = yaw; + this.pitch = pitch; + } + + public Vec3 getPos() { + return pos; + } + + public void setPos(Vec3 pos) { + this.pos = pos; + } + + public float getYaw() { + return yaw; + } + + public void setYaw(float yaw) { + this.yaw = yaw; + } + + public float getPitch() { + return pitch; + } + + public void setPitch(float pitch) { + this.pitch = pitch; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/ClickHandlingItem.java b/src/main/java/com/fusionflux/portalcubed/util/ClickHandlingItem.java index baa10ca1..8dbc8385 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/ClickHandlingItem.java +++ b/src/main/java/com/fusionflux/portalcubed/util/ClickHandlingItem.java @@ -6,7 +6,7 @@ public interface ClickHandlingItem { - InteractionResult onLeftClick(Player user, InteractionHand hand); - InteractionResult onRightClick(Player user, InteractionHand hand); + InteractionResult onLeftClick(Player user, InteractionHand hand); + InteractionResult onRightClick(Player user, InteractionHand hand); } diff --git a/src/main/java/com/fusionflux/portalcubed/util/EntityComponent.java b/src/main/java/com/fusionflux/portalcubed/util/EntityComponent.java index af8b60f5..10b21fe6 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/EntityComponent.java +++ b/src/main/java/com/fusionflux/portalcubed/util/EntityComponent.java @@ -17,191 +17,191 @@ import java.util.UUID; public class EntityComponent implements PortalCubedComponent, AutoSyncedComponent { - VoxelShape portalCutout = Shapes.empty(); - VoxelShape crossPortalCollision = Shapes.empty(); - boolean hasTeleportationHappened = false; - public Set portals = new HashSet<>(); - private final Entity entity; - - boolean wasInfiniteFalling; - - boolean canFireGel; - - Vec3 teleportVelocity = Vec3.ZERO; - - Vec3 serverVelForGel = Vec3.ZERO; - - @Nullable - private BlockPos launcher; - - public EntityComponent(Entity entity) { - this.entity = entity; - } - - @Override - public VoxelShape getPortalCutout() { - return this.portalCutout; - } - - @Override - public void setPortalCutout(VoxelShape cutout) { - this.portalCutout = cutout; - } - - @Override - public VoxelShape getCrossPortalCollision() { - return this.crossPortalCollision; - } - - @Override - public void setCrossPortalCollision(VoxelShape collision) { - this.crossPortalCollision = collision; - } - - @Override - public boolean getHasTeleportationHappened() { - return hasTeleportationHappened; - } - - @Override - public void setHasTeleportationHappened(boolean hasHappened) { - if (hasTeleportationHappened != hasHappened) { - hasTeleportationHappened = hasHappened; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public boolean getWasInfiniteFalling() { - return wasInfiniteFalling; - } - - @Override - public void setWasInfiniteFalling(boolean infFall) { - if (wasInfiniteFalling != infFall) { - wasInfiniteFalling = infFall; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public Vec3 getVelocityUpdateAfterTeleport() { - return teleportVelocity; - } - - @Override - public void setVelocityUpdateAfterTeleport(Vec3 velocity) { - if (!teleportVelocity.equals(velocity)) { - teleportVelocity = velocity; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - - - @Override - public boolean getCanFireGel() { - return canFireGel; - } - - @Override - public void setCanFireGel(boolean canGel) { - if (canFireGel != canGel) { - canFireGel = canGel; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public Vec3 getServerVelForGel() { - return serverVelForGel; - } - - @Override - public void setServerVelForGel(Vec3 velocity) { - if (!serverVelForGel.equals(velocity)) { - serverVelForGel = velocity; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public Set getPortals() { - return portals; - } - - @Override - public void addPortals(UUID portalUUID) { - if (portals.add(portalUUID)) { - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public void removePortals(UUID portalUUID) { - if (portals.remove(portalUUID)) { - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Nullable - @Override - public BlockPos getLauncher() { - return launcher; - } - - @Override - public void setLauncher(@Nullable BlockPos launcher) { - if (!Objects.equals(this.launcher, launcher)) { - this.launcher = launcher; - PortalCubedComponents.ENTITY_COMPONENT.sync(entity); - } - } - - @Override - public void readFromNbt(CompoundTag tag) { - int size = tag.getInt("size"); - - if (!portals.isEmpty()) - portals.clear(); - - for (int i = 0; i < size; i++) { - portals.add(tag.getUUID("portals" + i)); - } - - hasTeleportationHappened = tag.getBoolean("hasTpHappened"); - - this.setVelocityUpdateAfterTeleport(NbtHelper.getVec3d(tag, "velocity")); - - setWasInfiniteFalling(tag.getBoolean("wasInfiniteFalling")); - - this.setServerVelForGel(NbtHelper.getVec3d(tag, "gelVelocity")); - - setCanFireGel(tag.getBoolean("canFireGel")); - - setLauncher(NbtHelper.readNullableBlockPos(tag, "launcher")); - } - - @Override - public void writeToNbt(@NotNull CompoundTag tag) { - int number = 0; - for (UUID portal : portals) { - tag.putUUID("portals" + number, portal); - number++; - } - tag.putInt("size", portals.size()); - tag.putBoolean("hasTpHappened", hasTeleportationHappened); - - NbtHelper.putVec3d(tag, "velocity", this.getVelocityUpdateAfterTeleport()); - - tag.putBoolean("wasInfiniteFalling", wasInfiniteFalling); - - NbtHelper.putVec3d(tag, "gelVelocity", this.getServerVelForGel()); - - tag.putBoolean("canFireGel", canFireGel); - - if (launcher != null) { - tag.put("launcher", NbtUtils.writeBlockPos(launcher)); - } - } + VoxelShape portalCutout = Shapes.empty(); + VoxelShape crossPortalCollision = Shapes.empty(); + boolean hasTeleportationHappened = false; + public Set portals = new HashSet<>(); + private final Entity entity; + + boolean wasInfiniteFalling; + + boolean canFireGel; + + Vec3 teleportVelocity = Vec3.ZERO; + + Vec3 serverVelForGel = Vec3.ZERO; + + @Nullable + private BlockPos launcher; + + public EntityComponent(Entity entity) { + this.entity = entity; + } + + @Override + public VoxelShape getPortalCutout() { + return this.portalCutout; + } + + @Override + public void setPortalCutout(VoxelShape cutout) { + this.portalCutout = cutout; + } + + @Override + public VoxelShape getCrossPortalCollision() { + return this.crossPortalCollision; + } + + @Override + public void setCrossPortalCollision(VoxelShape collision) { + this.crossPortalCollision = collision; + } + + @Override + public boolean getHasTeleportationHappened() { + return hasTeleportationHappened; + } + + @Override + public void setHasTeleportationHappened(boolean hasHappened) { + if (hasTeleportationHappened != hasHappened) { + hasTeleportationHappened = hasHappened; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public boolean getWasInfiniteFalling() { + return wasInfiniteFalling; + } + + @Override + public void setWasInfiniteFalling(boolean infFall) { + if (wasInfiniteFalling != infFall) { + wasInfiniteFalling = infFall; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public Vec3 getVelocityUpdateAfterTeleport() { + return teleportVelocity; + } + + @Override + public void setVelocityUpdateAfterTeleport(Vec3 velocity) { + if (!teleportVelocity.equals(velocity)) { + teleportVelocity = velocity; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + + + @Override + public boolean getCanFireGel() { + return canFireGel; + } + + @Override + public void setCanFireGel(boolean canGel) { + if (canFireGel != canGel) { + canFireGel = canGel; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public Vec3 getServerVelForGel() { + return serverVelForGel; + } + + @Override + public void setServerVelForGel(Vec3 velocity) { + if (!serverVelForGel.equals(velocity)) { + serverVelForGel = velocity; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public Set getPortals() { + return portals; + } + + @Override + public void addPortals(UUID portalUUID) { + if (portals.add(portalUUID)) { + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public void removePortals(UUID portalUUID) { + if (portals.remove(portalUUID)) { + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Nullable + @Override + public BlockPos getLauncher() { + return launcher; + } + + @Override + public void setLauncher(@Nullable BlockPos launcher) { + if (!Objects.equals(this.launcher, launcher)) { + this.launcher = launcher; + PortalCubedComponents.ENTITY_COMPONENT.sync(entity); + } + } + + @Override + public void readFromNbt(CompoundTag tag) { + int size = tag.getInt("size"); + + if (!portals.isEmpty()) + portals.clear(); + + for (int i = 0; i < size; i++) { + portals.add(tag.getUUID("portals" + i)); + } + + hasTeleportationHappened = tag.getBoolean("hasTpHappened"); + + this.setVelocityUpdateAfterTeleport(NbtHelper.getVec3d(tag, "velocity")); + + setWasInfiniteFalling(tag.getBoolean("wasInfiniteFalling")); + + this.setServerVelForGel(NbtHelper.getVec3d(tag, "gelVelocity")); + + setCanFireGel(tag.getBoolean("canFireGel")); + + setLauncher(NbtHelper.readNullableBlockPos(tag, "launcher")); + } + + @Override + public void writeToNbt(@NotNull CompoundTag tag) { + int number = 0; + for (UUID portal : portals) { + tag.putUUID("portals" + number, portal); + number++; + } + tag.putInt("size", portals.size()); + tag.putBoolean("hasTpHappened", hasTeleportationHappened); + + NbtHelper.putVec3d(tag, "velocity", this.getVelocityUpdateAfterTeleport()); + + tag.putBoolean("wasInfiniteFalling", wasInfiniteFalling); + + NbtHelper.putVec3d(tag, "gelVelocity", this.getServerVelForGel()); + + tag.putBoolean("canFireGel", canFireGel); + + if (launcher != null) { + tag.put("launcher", NbtUtils.writeBlockPos(launcher)); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/EntityReference.java b/src/main/java/com/fusionflux/portalcubed/util/EntityReference.java index d93dce0f..a473cc2a 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/EntityReference.java +++ b/src/main/java/com/fusionflux/portalcubed/util/EntityReference.java @@ -8,48 +8,48 @@ import java.util.UUID; public class EntityReference { - public final ServerLevel level; - public final UUID uuid; - private final Class entityClass; - - private WeakReference entity; - - public EntityReference(ServerLevel level, T entity) { - this.level = level; - this.uuid = entity.getUUID(); - //noinspection unchecked - this.entityClass = (Class) entity.getClass(); - this.entity = new WeakReference<>(entity); - } - - public EntityReference(ServerLevel level, UUID uuid, Class entityClass) { - this.level = level; - this.uuid = uuid; - this.entityClass = entityClass; - this.entity = new WeakReference<>(null); - } - - @Nullable - public T get() { - tryResolve(); - return entity.get(); - } - - public boolean isLoaded() { - tryResolve(); - return get() != null; - } - - public boolean isUnloaded() { - return !isLoaded(); - } - - private void tryResolve() { - if (entity.get() == null) { - Entity entity = level.getEntity(uuid); - if (entityClass.isInstance(entity)) - //noinspection unchecked - this.entity = new WeakReference<>((T) entity); - } - } + public final ServerLevel level; + public final UUID uuid; + private final Class entityClass; + + private WeakReference entity; + + public EntityReference(ServerLevel level, T entity) { + this.level = level; + this.uuid = entity.getUUID(); + //noinspection unchecked + this.entityClass = (Class) entity.getClass(); + this.entity = new WeakReference<>(entity); + } + + public EntityReference(ServerLevel level, UUID uuid, Class entityClass) { + this.level = level; + this.uuid = uuid; + this.entityClass = entityClass; + this.entity = new WeakReference<>(null); + } + + @Nullable + public T get() { + tryResolve(); + return entity.get(); + } + + public boolean isLoaded() { + tryResolve(); + return get() != null; + } + + public boolean isUnloaded() { + return !isLoaded(); + } + + private void tryResolve() { + if (entity.get() == null) { + Entity entity = level.getEntity(uuid); + if (entityClass.isInstance(entity)) + //noinspection unchecked + this.entity = new WeakReference<>((T) entity); + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/GeneralUtil.java b/src/main/java/com/fusionflux/portalcubed/util/GeneralUtil.java index 24f12164..8a7cd95a 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/GeneralUtil.java +++ b/src/main/java/com/fusionflux/portalcubed/util/GeneralUtil.java @@ -17,116 +17,116 @@ import static java.lang.Math.*; public class GeneralUtil { - public static final Vec3 NEGATIVE_INFINITY = new Vec3( - Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY - ); - public static final Vec3 POSITIVE_INFINITY = new Vec3( - Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY - ); - - /** - * @author maximum - */ - public static VoxelShape rotate(VoxelShape shape, Direction dir) { - List shapes = new ArrayList<>(); - - shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> shapes.add(switch (dir) { - case WEST -> Shapes.box(z1, y1, x1, z2, y2, x2); - case SOUTH -> Shapes.box(1 - x2, y1, 1 - z2, 1 - x1, y2, 1 - z1); - case EAST -> Shapes.box(1 - z2, y1, 1 - x2, 1 - z1, y2, 1 - x1); - default -> Shapes.box(x1, y1, z1, x2, y2, z2); - })); - - return Shapes.or(Shapes.empty(), shapes.toArray(new VoxelShape[0])); - } - - public static double calculateVelocity(double x, double y, double a, double g) { - a = Math.toRadians(a); - return sqrt(x * x * g / (2 * cos(-a) * (x * sin(-a) + y * cos(-a)))); - } - - // Code based off of code from ChatGPT - public static Vec3 calculatePerpendicularVector(Vec3 lineStart, Vec3 lineEnd, Vec3 point) { - // Calculate direction vector of line - final Vec3 d = lineEnd.subtract(lineStart); - - // Calculate vector from point to line - final Vec3 p = point.subtract(lineStart); - - // Calculate projection of point vector onto line vector - final double t = p.dot(d) / d.dot(d); - - // Calculate perpendicular vector - return p.subtract(d.scale(t)); - } - - public static boolean targetsEqual(HitResult a, HitResult b) { - return a.getType() == b.getType() && switch (a.getType()) { - case MISS -> true; - case BLOCK -> ((BlockHitResult)a).getBlockPos().equals(((BlockHitResult)b).getBlockPos()); - case ENTITY -> ((EntityHitResult)a).getEntity() == ((EntityHitResult)b).getEntity(); - }; - } - - // Based on https://forum.unity.com/threads/how-do-i-find-the-closest-point-on-a-line.340058/ - public static Vec3 nearestPointOnLine(Vec3 linePnt, Vec3 lineDir, Vec3 pnt) { - lineDir = lineDir.normalize(); - final Vec3 v = pnt.subtract(linePnt); - final double d = v.dot(lineDir); - return linePnt.add(lineDir.scale(d)); - } - - public static AABB rotate(AABB box, float angle, Direction.Axis axis) { - angle = Mth.wrapDegrees(angle); - if ((angle > -45 && angle <= 45) || angle > 135 || angle <= -135) { - return box; - } else { - return switch (axis) { - case X -> new AABB(box.minX, box.minZ, box.minY, box.maxX, box.maxZ, box.maxY); - case Y -> new AABB(box.minZ, box.minY, box.minX, box.maxZ, box.maxY, box.maxX); - case Z -> new AABB(box.minY, box.minX, box.minZ, box.maxY, box.maxX, box.maxZ); - }; - } - } - - public static Vec2 normalToRotation(Vec3 normal) { - return new Vec2( - (float)toDegrees(-Mth.atan2(normal.y, sqrt(normal.x * normal.x + normal.z * normal.z))), - (float)toDegrees(Mth.atan2(normal.z, normal.x)) - 90 - ); - } - - public static AABB capAABBAt(Vec3 min, Vec3 max, Direction direction, Vec3 origin) { - if (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE) { - min = min.with(direction.getAxis(), origin.get(direction.getAxis())); - } else { - max = max.with(direction.getAxis(), origin.get(direction.getAxis())); - } - return new AABB(min, max); - } - - public static AABB createInfiniteForwardsAABB(Direction direction, Vec3 origin) { - return capAABBAt(NEGATIVE_INFINITY, POSITIVE_INFINITY, direction, origin); - } - - public static void setupPortalShapes(Entity entity) { - final AABB portalCheckBox = entity.getBoundingBox().expandTowards(entity.getDeltaMovement()); - List list = entity.level().getEntitiesOfClass(Portal.class, portalCheckBox); - - VoxelShape cutoutShape = Shapes.empty(); - VoxelShape crossPortalCollisionShape = Shapes.empty(); - - for (Portal portal : list) { - if (portal.getActive() && portal.calculateCutoutBox() != NULL_BOX && portal.calculateBoundsCheckBox() != NULL_BOX) { - cutoutShape = Shapes.or(cutoutShape, Shapes.create(portal.getCutoutBoundingBox())); - crossPortalCollisionShape = Shapes.or(crossPortalCollisionShape, portal.getCrossPortalCollisionShapeOther(entity)); - } - } - - CalledValues.setPortalCutout(entity, cutoutShape); - CalledValues.setCrossPortalCollision(entity, crossPortalCollisionShape); - } - - public static void appendTooltip(String descriptionId, List tooltipComponents) { - } + public static final Vec3 NEGATIVE_INFINITY = new Vec3( + Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY + ); + public static final Vec3 POSITIVE_INFINITY = new Vec3( + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY + ); + + /** + * @author maximum + */ + public static VoxelShape rotate(VoxelShape shape, Direction dir) { + List shapes = new ArrayList<>(); + + shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> shapes.add(switch (dir) { + case WEST -> Shapes.box(z1, y1, x1, z2, y2, x2); + case SOUTH -> Shapes.box(1 - x2, y1, 1 - z2, 1 - x1, y2, 1 - z1); + case EAST -> Shapes.box(1 - z2, y1, 1 - x2, 1 - z1, y2, 1 - x1); + default -> Shapes.box(x1, y1, z1, x2, y2, z2); + })); + + return Shapes.or(Shapes.empty(), shapes.toArray(new VoxelShape[0])); + } + + public static double calculateVelocity(double x, double y, double a, double g) { + a = Math.toRadians(a); + return sqrt(x * x * g / (2 * cos(-a) * (x * sin(-a) + y * cos(-a)))); + } + + // Code based off of code from ChatGPT + public static Vec3 calculatePerpendicularVector(Vec3 lineStart, Vec3 lineEnd, Vec3 point) { + // Calculate direction vector of line + final Vec3 d = lineEnd.subtract(lineStart); + + // Calculate vector from point to line + final Vec3 p = point.subtract(lineStart); + + // Calculate projection of point vector onto line vector + final double t = p.dot(d) / d.dot(d); + + // Calculate perpendicular vector + return p.subtract(d.scale(t)); + } + + public static boolean targetsEqual(HitResult a, HitResult b) { + return a.getType() == b.getType() && switch (a.getType()) { + case MISS -> true; + case BLOCK -> ((BlockHitResult)a).getBlockPos().equals(((BlockHitResult)b).getBlockPos()); + case ENTITY -> ((EntityHitResult)a).getEntity() == ((EntityHitResult)b).getEntity(); + }; + } + + // Based on https://forum.unity.com/threads/how-do-i-find-the-closest-point-on-a-line.340058/ + public static Vec3 nearestPointOnLine(Vec3 linePnt, Vec3 lineDir, Vec3 pnt) { + lineDir = lineDir.normalize(); + final Vec3 v = pnt.subtract(linePnt); + final double d = v.dot(lineDir); + return linePnt.add(lineDir.scale(d)); + } + + public static AABB rotate(AABB box, float angle, Direction.Axis axis) { + angle = Mth.wrapDegrees(angle); + if ((angle > -45 && angle <= 45) || angle > 135 || angle <= -135) { + return box; + } else { + return switch (axis) { + case X -> new AABB(box.minX, box.minZ, box.minY, box.maxX, box.maxZ, box.maxY); + case Y -> new AABB(box.minZ, box.minY, box.minX, box.maxZ, box.maxY, box.maxX); + case Z -> new AABB(box.minY, box.minX, box.minZ, box.maxY, box.maxX, box.maxZ); + }; + } + } + + public static Vec2 normalToRotation(Vec3 normal) { + return new Vec2( + (float)toDegrees(-Mth.atan2(normal.y, sqrt(normal.x * normal.x + normal.z * normal.z))), + (float)toDegrees(Mth.atan2(normal.z, normal.x)) - 90 + ); + } + + public static AABB capAABBAt(Vec3 min, Vec3 max, Direction direction, Vec3 origin) { + if (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE) { + min = min.with(direction.getAxis(), origin.get(direction.getAxis())); + } else { + max = max.with(direction.getAxis(), origin.get(direction.getAxis())); + } + return new AABB(min, max); + } + + public static AABB createInfiniteForwardsAABB(Direction direction, Vec3 origin) { + return capAABBAt(NEGATIVE_INFINITY, POSITIVE_INFINITY, direction, origin); + } + + public static void setupPortalShapes(Entity entity) { + final AABB portalCheckBox = entity.getBoundingBox().expandTowards(entity.getDeltaMovement()); + List list = entity.level().getEntitiesOfClass(Portal.class, portalCheckBox); + + VoxelShape cutoutShape = Shapes.empty(); + VoxelShape crossPortalCollisionShape = Shapes.empty(); + + for (Portal portal : list) { + if (portal.getActive() && portal.calculateCutoutBox() != NULL_BOX && portal.calculateBoundsCheckBox() != NULL_BOX) { + cutoutShape = Shapes.or(cutoutShape, Shapes.create(portal.getCutoutBoundingBox())); + crossPortalCollisionShape = Shapes.or(crossPortalCollisionShape, portal.getCrossPortalCollisionShapeOther(entity)); + } + } + + CalledValues.setPortalCutout(entity, cutoutShape); + CalledValues.setCrossPortalCollision(entity, crossPortalCollisionShape); + } + + public static void appendTooltip(String descriptionId, List tooltipComponents) { + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/HolderComponent.java b/src/main/java/com/fusionflux/portalcubed/util/HolderComponent.java index 4a6acec5..704f69f8 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/HolderComponent.java +++ b/src/main/java/com/fusionflux/portalcubed/util/HolderComponent.java @@ -29,148 +29,148 @@ public final class HolderComponent implements AutoSyncedComponent { - private CorePhysicsEntity heldEntity = null; - private Optional heldEntityUUID = Optional.empty(); - - private final Player owner; - - @ClientOnly - private int heldTicks; - @ClientOnly - private boolean grabbedWithGun; - - HolderComponent(Player owner) { - this.owner = owner; - } - - public boolean hold(CorePhysicsEntity entityToHold) { - Objects.requireNonNull(entityToHold, "The entity to hold can not be null!"); - if (entityBeingHeld() == null && !entityToHold.fizzling() && !entityToHold.isLocked()) { - entityToHold.setHolderUUID(Optional.of(owner.getUUID())); - this.heldEntity = entityToHold; - RayonIntegration.INSTANCE.setNoGravity(heldEntity, true); - this.heldEntityUUID = Optional.of(entityToHold.getUUID()); - PortalCubedComponents.HOLDER_COMPONENT.sync(owner); - if (owner.level().isClientSide) { - grabbedWithGun = owner.isHolding(i -> i.getItem() instanceof PortalGun); - playClientSound(false); - } - return true; - } - return false; - } - - @ClientOnly - private void playClientSound(boolean stop) { - heldTicks = 0; - if (!grabbedWithGun) return; - Minecraft.getInstance().getSoundManager().play(new HoldSoundInstance( - stop ? PortalCubedSounds.HOLD_STOP_EVENT : PortalCubedSounds.HOLD_START_EVENT, - false, !stop - )); - } - - public @Nullable CorePhysicsEntity entityBeingHeld() { - if (heldEntity == null && heldEntityUUID.isPresent()) this.heldEntity = (CorePhysicsEntity) ((LevelExt) this.owner.level()).getEntityByUuid(heldEntityUUID.get()); - return this.heldEntity; - } - - public boolean stopHolding() { - if (this.heldEntity != null) { - heldEntity.setHolderUUID(Optional.empty()); - if (!heldEntity.fizzling()) { - RayonIntegration.INSTANCE.setNoGravity(heldEntity, false); - } - if (owner.level().isClientSide && !heldEntity.isRemoved()) { - var buf = PacketByteBufs.create(); - buf.writeDouble(heldEntity.position().x); - buf.writeDouble(heldEntity.position().y); - buf.writeDouble(heldEntity.position().z); - buf.writeDouble(heldEntity.lastPos.x); - buf.writeDouble(heldEntity.lastPos.y); - buf.writeDouble(heldEntity.lastPos.z); - buf.writeFloat(heldEntity.yBodyRot); - buf.writeUUID(heldEntity.getUUID()); - NetworkingSafetyWrapper.sendFromClient("cube_pos_update", buf); - } - - this.heldEntityUUID = Optional.empty(); - this.heldEntity = null; - PortalCubedComponents.HOLDER_COMPONENT.sync(owner); - if (owner.level().isClientSide) { - playClientSound(true); - } - return true; - } - return false; - } - - - @Override - public void readFromNbt(CompoundTag tag) { - if (tag.contains("heldEntityUUID")) this.heldEntityUUID = Optional.of(tag.getUUID("heldEntityUUID")); - } - - @Override - public void writeToNbt(@NotNull CompoundTag tag) { - this.heldEntityUUID.ifPresent(value -> tag.putUUID("heldEntityUUID", value)); - } - - @Override - public boolean shouldSyncWith(ServerPlayer player) { - return player == this.owner; - } - - @Override - public void applySyncPacket(FriendlyByteBuf buf) { - final var syncedHeldEntityUUID = EntityDataSerializers.OPTIONAL_UUID.read(buf); - if (heldEntity == null && syncedHeldEntityUUID.isPresent()) { - hold((CorePhysicsEntity) ((LevelExt) this.owner.level()).getEntityByUuid(syncedHeldEntityUUID.get())); - } else if (syncedHeldEntityUUID.isEmpty() && heldEntity != null) { - stopHolding(); - } - handHideRefresh(); - } - - @Override - public void writeSyncPacket(FriendlyByteBuf buf, ServerPlayer recipient) { - EntityDataSerializers.OPTIONAL_UUID.write(buf, this.heldEntityUUID); - } - - private void handHideRefresh() { - if (owner.getMainHandItem().is(PortalCubedItems.HOLDS_OBJECT)) return; - owner.resetAttackStrengthTicker(); - ((ItemInHandRendererExt)Minecraft.getInstance().gameRenderer.itemInHandRenderer).startHandFaker(); - } - - @ClientOnly - public void tick() { - if (entityBeingHeld() == null || !grabbedWithGun) return; - if (++heldTicks == 87) { - Minecraft.getInstance().getSoundManager().play(new HoldSoundInstance(PortalCubedSounds.HOLD_LOOP_EVENT, true, true)); - } - } - - private class HoldSoundInstance extends EntityBoundSoundInstance { - private final boolean fadeout; - - HoldSoundInstance(SoundEvent event, boolean looping, boolean fadeout) { - super(event, SoundSource.PLAYERS, 0.8f, 1f, owner, owner.getRandom().nextLong()); - this.looping = looping; - this.fadeout = fadeout; - } - - @Override - public void tick() { - super.tick(); - if (fadeout && entityBeingHeld() == null) { - if (volume > 1 / 14f) { - volume -= 1 / 14f; - } else { - stop(); - } - } - } - } + private CorePhysicsEntity heldEntity = null; + private Optional heldEntityUUID = Optional.empty(); + + private final Player owner; + + @ClientOnly + private int heldTicks; + @ClientOnly + private boolean grabbedWithGun; + + HolderComponent(Player owner) { + this.owner = owner; + } + + public boolean hold(CorePhysicsEntity entityToHold) { + Objects.requireNonNull(entityToHold, "The entity to hold can not be null!"); + if (entityBeingHeld() == null && !entityToHold.fizzling() && !entityToHold.isLocked()) { + entityToHold.setHolderUUID(Optional.of(owner.getUUID())); + this.heldEntity = entityToHold; + RayonIntegration.INSTANCE.setNoGravity(heldEntity, true); + this.heldEntityUUID = Optional.of(entityToHold.getUUID()); + PortalCubedComponents.HOLDER_COMPONENT.sync(owner); + if (owner.level().isClientSide) { + grabbedWithGun = owner.isHolding(i -> i.getItem() instanceof PortalGun); + playClientSound(false); + } + return true; + } + return false; + } + + @ClientOnly + private void playClientSound(boolean stop) { + heldTicks = 0; + if (!grabbedWithGun) return; + Minecraft.getInstance().getSoundManager().play(new HoldSoundInstance( + stop ? PortalCubedSounds.HOLD_STOP_EVENT : PortalCubedSounds.HOLD_START_EVENT, + false, !stop + )); + } + + public @Nullable CorePhysicsEntity entityBeingHeld() { + if (heldEntity == null && heldEntityUUID.isPresent()) this.heldEntity = (CorePhysicsEntity) ((LevelExt) this.owner.level()).getEntityByUuid(heldEntityUUID.get()); + return this.heldEntity; + } + + public boolean stopHolding() { + if (this.heldEntity != null) { + heldEntity.setHolderUUID(Optional.empty()); + if (!heldEntity.fizzling()) { + RayonIntegration.INSTANCE.setNoGravity(heldEntity, false); + } + if (owner.level().isClientSide && !heldEntity.isRemoved()) { + var buf = PacketByteBufs.create(); + buf.writeDouble(heldEntity.position().x); + buf.writeDouble(heldEntity.position().y); + buf.writeDouble(heldEntity.position().z); + buf.writeDouble(heldEntity.lastPos.x); + buf.writeDouble(heldEntity.lastPos.y); + buf.writeDouble(heldEntity.lastPos.z); + buf.writeFloat(heldEntity.yBodyRot); + buf.writeUUID(heldEntity.getUUID()); + NetworkingSafetyWrapper.sendFromClient("cube_pos_update", buf); + } + + this.heldEntityUUID = Optional.empty(); + this.heldEntity = null; + PortalCubedComponents.HOLDER_COMPONENT.sync(owner); + if (owner.level().isClientSide) { + playClientSound(true); + } + return true; + } + return false; + } + + + @Override + public void readFromNbt(CompoundTag tag) { + if (tag.contains("heldEntityUUID")) this.heldEntityUUID = Optional.of(tag.getUUID("heldEntityUUID")); + } + + @Override + public void writeToNbt(@NotNull CompoundTag tag) { + this.heldEntityUUID.ifPresent(value -> tag.putUUID("heldEntityUUID", value)); + } + + @Override + public boolean shouldSyncWith(ServerPlayer player) { + return player == this.owner; + } + + @Override + public void applySyncPacket(FriendlyByteBuf buf) { + final var syncedHeldEntityUUID = EntityDataSerializers.OPTIONAL_UUID.read(buf); + if (heldEntity == null && syncedHeldEntityUUID.isPresent()) { + hold((CorePhysicsEntity) ((LevelExt) this.owner.level()).getEntityByUuid(syncedHeldEntityUUID.get())); + } else if (syncedHeldEntityUUID.isEmpty() && heldEntity != null) { + stopHolding(); + } + handHideRefresh(); + } + + @Override + public void writeSyncPacket(FriendlyByteBuf buf, ServerPlayer recipient) { + EntityDataSerializers.OPTIONAL_UUID.write(buf, this.heldEntityUUID); + } + + private void handHideRefresh() { + if (owner.getMainHandItem().is(PortalCubedItems.HOLDS_OBJECT)) return; + owner.resetAttackStrengthTicker(); + ((ItemInHandRendererExt)Minecraft.getInstance().gameRenderer.itemInHandRenderer).startHandFaker(); + } + + @ClientOnly + public void tick() { + if (entityBeingHeld() == null || !grabbedWithGun) return; + if (++heldTicks == 87) { + Minecraft.getInstance().getSoundManager().play(new HoldSoundInstance(PortalCubedSounds.HOLD_LOOP_EVENT, true, true)); + } + } + + private class HoldSoundInstance extends EntityBoundSoundInstance { + private final boolean fadeout; + + HoldSoundInstance(SoundEvent event, boolean looping, boolean fadeout) { + super(event, SoundSource.PLAYERS, 0.8f, 1f, owner, owner.getRandom().nextLong()); + this.looping = looping; + this.fadeout = fadeout; + } + + @Override + public void tick() { + super.tick(); + if (fadeout && entityBeingHeld() == null) { + if (volume > 1 / 14f) { + volume -= 1 / 14f; + } else { + stop(); + } + } + } + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/IPQuaternion.java b/src/main/java/com/fusionflux/portalcubed/util/IPQuaternion.java index cb947c00..d4b80b90 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/IPQuaternion.java +++ b/src/main/java/com/fusionflux/portalcubed/util/IPQuaternion.java @@ -12,349 +12,349 @@ //This is from https://github.com/qouteall/ImmersivePortalsMod/blob/1.18/q_misc_util/src/main/java/qouteall/q_misc_util/my_util/DQuaternion.java, public class IPQuaternion { - public static final IPQuaternion IDENTITY = new IPQuaternion(0, 0, 0, 1); - - public final double x; - public final double y; - public final double z; - public final double w; - - public IPQuaternion(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - public double getX() { - return x; - } - - public double getY() { - return y; - } - - public double getZ() { - return z; - } - - public double getW() { - return w; - } - - public static IPQuaternion rotationByRadians( - Vec3 axis, - double rotationAngle - ) { - double s = Math.sin(rotationAngle / 2.0F); - return new IPQuaternion( - axis.x * s, - axis.y * s, - axis.z * s, - Math.cos(rotationAngle / 2.0F) - ); - } - - /** - * @return the axis that the rotation is being performed along - */ - public Vec3 getRotatingAxis() { - return new Vec3(x, y, z).normalize(); - } - - public double getRotatingAngleRadians() { - return Math.acos(w) * 2; - } - - public double getRotatingAngleDegrees() { - return Math.toDegrees(getRotatingAngleRadians()); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - IPQuaternion that = (IPQuaternion)o; - return Double.compare(that.x, x) == 0 && - Double.compare(that.y, y) == 0 && - Double.compare(that.z, z) == 0 && - Double.compare(that.w, w) == 0; - } - - @Override - public String toString() { - Vec3 rotatingAxis = getRotatingAxis(); - return String.format("Rotates %.3f degrees along (%.3f %.3f %.3f) Quaternion:(%.3f %.3f %.3f %.3f)", - getRotatingAngleDegrees(), rotatingAxis.x, rotatingAxis.y, rotatingAxis.z, x, y, z, w - ); - } - - public IPQuaternion multiply(double val) { - return new IPQuaternion( - x * val, y * val, z * val, w * val - ); - } - - /** - * vector add - */ - public IPQuaternion add(IPQuaternion q) { - return new IPQuaternion( - x + q.x, y + q.y, z + q.z, w + q.w - ); - } - - public Vec3 rotate(Vec3 vec, boolean correct) { - IPQuaternion result = this.hamiltonProduct(new IPQuaternion(vec.x, vec.y, vec.z, 0)) - .hamiltonProduct(getConjugated()); - - if (correct) { - result = result.fixFloatingPointErrorAccumulation(); - } - - return new Vec3(result.x, result.y, result.z); - } - - public IPQuaternion fixFloatingPointErrorAccumulation() { - IPQuaternion quaternion = new IPQuaternion( - fixCoordinateFloatingPointError(getX()), - fixCoordinateFloatingPointError(getY()), - fixCoordinateFloatingPointError(getZ()), - fixCoordinateFloatingPointError(getW()) - ); - - return quaternion.getNormalized(); - } - - public IPQuaternion getNormalized() { - double lenSq = dotProduct(this); - if (lenSq != 0) { - // no fastInverseSqrt. precision is the most important - double len = Math.sqrt(lenSq); - return this.multiply(1.0 / len); - } else { - PortalCubed.LOGGER.error("Normalizing zero-length quaternion", new Throwable()); - return IDENTITY; - } - } - - private static double fixCoordinateFloatingPointError(double num) { - final double threshold = 0.0000001; - if (Math.abs(num) < threshold) { - return 0; - } - - if (Math.abs(num - 1) < threshold) { - return 1; - } - - if (Math.abs(num - (-1)) < threshold) { - return -1; - } - - return num; - } - - public IPQuaternion getConjugated() { - return new IPQuaternion( - -x, -y, -z, w - ); - } - - public IPQuaternion hamiltonProduct(IPQuaternion other) { - double x1 = this.getX(); - double y1 = this.getY(); - double z1 = this.getZ(); - double w1 = this.getW(); - double x2 = other.getX(); - double y2 = other.getY(); - double z2 = other.getZ(); - double w2 = other.getW(); - return new IPQuaternion( - w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, - w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, - w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, - w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 - ); - } - - public static Tuple getPitchYawFromRotation(IPQuaternion quaternion) { - double x = quaternion.getX(); - double y = quaternion.getY(); - double z = quaternion.getZ(); - double w = quaternion.getW(); - - double cosYaw = 2 * (y * y + z * z) - 1; - double sinYaw = -(x * z + y * w) * 2; - - double cosPitch = 1 - 2 * (x * x + z * z); - double sinPitch = (x * w + y * z) * 2; - - return new Tuple<>( - Math.toDegrees(Math.atan2(sinPitch, cosPitch)), - Math.toDegrees(Math.atan2(sinYaw, cosYaw)) - ); - } - - public Vector3f getEulerAngles() { - final Vector3f eulerAngles = new Vector3f(); - eulerAngles.x = (float)Math.toDegrees(Math.atan2(x * w - y * z, 0.5f - x * x - y * y)); - eulerAngles.y = (float)Math.toDegrees(Math.safeAsin(2.0f * (x * z + y * w))); - eulerAngles.z = (float)Math.toDegrees(Math.atan2(z * w - x * y, 0.5f - y * y - z * z)); - return eulerAngles; - } - - - // x, y, z are the 3 rows of the matrix - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ - // only works if the matrix is rotation only - public static IPQuaternion matrixToQuaternion( - Vec3 x, Vec3 y, Vec3 z - ) { - double m00 = x.x(); - double m11 = y.y(); - double m22 = z.z(); - - double m12 = z.y(); - double m21 = y.z(); - - double m20 = x.z(); - double m02 = z.x(); - - double m01 = y.x(); - double m10 = x.y(); - - double tr = m00 + m11 + m22; - - double qx, qy, qz, qw; - - if (tr > 0) { - double s = Math.sqrt(tr + 1.0) * 2; // S=4*qw - qw = 0.25 * s; - qx = (m21 - m12) / s; - qy = (m02 - m20) / s; - qz = (m10 - m01) / s; - } else if ((m00 > m11) && (m00 > m22)) { - double s = Math.sqrt(1.0 + m00 - m11 - m22) * 2; // S=4*qx - qw = (m21 - m12) / s; - qx = 0.25 * s; - qy = (m01 + m10) / s; - qz = (m02 + m20) / s; - } else if (m11 > m22) { - double s = Math.sqrt(1.0 + m11 - m00 - m22) * 2; // S=4*qy - qw = (m02 - m20) / s; - qx = (m01 + m10) / s; - qy = 0.25 * s; - qz = (m12 + m21) / s; - } else { - double s = Math.sqrt(1.0 + m22 - m00 - m11) * 2; // S=4*qz - qw = (m10 - m01) / s; - qx = (m02 + m20) / s; - qy = (m12 + m21) / s; - qz = 0.25 * s; - } - - return new IPQuaternion(qx, qy, qz, qw); - } - - public static IPQuaternion getRotationBetween(Vec3 from, Vec3 to, Vec3 backup) { - from = from.normalize(); - to = to.normalize(); - Vec3 axis = from.cross(to).normalize(); - double cos = from.dot(to); - double angle = Math.acos(cos); - - if (Math.toDegrees(angle) == 180) { - axis = backup; - } - return IPQuaternion.rotationByRadians(axis, angle); - } - - public Quaternionf toQuaternionf() { - return new Quaternionf(x, y, z, w); - } - - public Quaterniond toQuaterniond() { - return new Quaterniond(x, y, z, w); - } - - public static IPQuaternion fromEuler(float angleX, float angleY, float angleZ) { - angleX = Math.toRadians(angleX); - angleY = Math.toRadians(angleY); - angleZ = Math.toRadians(angleZ); - float sx = Math.sin(angleX * 0.5f); - float cx = Math.cosFromSin(sx, angleX * 0.5f); - float sy = Math.sin(angleY * 0.5f); - float cy = Math.cosFromSin(sy, angleY * 0.5f); - float sz = Math.sin(angleZ * 0.5f); - float cz = Math.cosFromSin(sz, angleZ * 0.5f); - float yx = cy * sx; - float yy = sy * cx; - float yz = sy * sx; - float yw = cy * cx; - return new IPQuaternion( - yx * cz + yy * sz, - yy * cz - yx * sz, - yw * sz - yz * cz, - yw * cz + yz * sz - ); - } - - public static IPQuaternion fromQuaternionf(Quaternionf joml) { - return new IPQuaternion(joml.x, joml.y, joml.z, joml.w); - } - - public double dotProduct(IPQuaternion q) { - return getX() * q.getX() + - getY() * q.getY() + - getZ() * q.getZ() + - getW() * q.getW(); - } - - public static IPQuaternion getCameraRotation(double pitch, double yaw) { - IPQuaternion r1 = rotationByDegrees(new Vec3(1, 0, 0), Mth.clamp(pitch, -89.9999, 89.9999)); - IPQuaternion r2 = rotationByDegrees(new Vec3(0, 1, 0), yaw + 180); - return r1.hamiltonProduct(r2); - } - - public static IPQuaternion rotationByDegrees( - Vec3 rotatingAxis, - double degrees - ) { - return rotationByRadians( - rotatingAxis, Math.toRadians(degrees) - ); - } - - public static IPQuaternion interpolate( - IPQuaternion a, - IPQuaternion b, - double t - ) { - - double dot = a.dotProduct(b); - - if (dot < 0.0f) { - a = a.multiply(-1); - dot = -dot; - } - - final double DOT_THRESHOLD = 0.9995; - if (dot > DOT_THRESHOLD) { - // If the inputs are too close for comfort, linearly interpolate - // and normalize the result. - - return a.multiply(1 - t).add(b.multiply(t)).getNormalized(); - } - - double theta0 = Math.acos(dot); - double theta = theta0 * t; - double sinTheta = Math.sin(theta); - double sinTheta0 = Math.sin(theta0); - - double s0 = Math.cos(theta) - dot * sinTheta / sinTheta0; - double s1 = sinTheta / sinTheta0; - - return a.multiply(s0).add(b.multiply(s1)); - } + public static final IPQuaternion IDENTITY = new IPQuaternion(0, 0, 0, 1); + + public final double x; + public final double y; + public final double z; + public final double w; + + public IPQuaternion(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public double getW() { + return w; + } + + public static IPQuaternion rotationByRadians( + Vec3 axis, + double rotationAngle + ) { + double s = Math.sin(rotationAngle / 2.0F); + return new IPQuaternion( + axis.x * s, + axis.y * s, + axis.z * s, + Math.cos(rotationAngle / 2.0F) + ); + } + + /** + * @return the axis that the rotation is being performed along + */ + public Vec3 getRotatingAxis() { + return new Vec3(x, y, z).normalize(); + } + + public double getRotatingAngleRadians() { + return Math.acos(w) * 2; + } + + public double getRotatingAngleDegrees() { + return Math.toDegrees(getRotatingAngleRadians()); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + IPQuaternion that = (IPQuaternion)o; + return Double.compare(that.x, x) == 0 && + Double.compare(that.y, y) == 0 && + Double.compare(that.z, z) == 0 && + Double.compare(that.w, w) == 0; + } + + @Override + public String toString() { + Vec3 rotatingAxis = getRotatingAxis(); + return String.format("Rotates %.3f degrees along (%.3f %.3f %.3f) Quaternion:(%.3f %.3f %.3f %.3f)", + getRotatingAngleDegrees(), rotatingAxis.x, rotatingAxis.y, rotatingAxis.z, x, y, z, w + ); + } + + public IPQuaternion multiply(double val) { + return new IPQuaternion( + x * val, y * val, z * val, w * val + ); + } + + /** + * vector add + */ + public IPQuaternion add(IPQuaternion q) { + return new IPQuaternion( + x + q.x, y + q.y, z + q.z, w + q.w + ); + } + + public Vec3 rotate(Vec3 vec, boolean correct) { + IPQuaternion result = this.hamiltonProduct(new IPQuaternion(vec.x, vec.y, vec.z, 0)) + .hamiltonProduct(getConjugated()); + + if (correct) { + result = result.fixFloatingPointErrorAccumulation(); + } + + return new Vec3(result.x, result.y, result.z); + } + + public IPQuaternion fixFloatingPointErrorAccumulation() { + IPQuaternion quaternion = new IPQuaternion( + fixCoordinateFloatingPointError(getX()), + fixCoordinateFloatingPointError(getY()), + fixCoordinateFloatingPointError(getZ()), + fixCoordinateFloatingPointError(getW()) + ); + + return quaternion.getNormalized(); + } + + public IPQuaternion getNormalized() { + double lenSq = dotProduct(this); + if (lenSq != 0) { + // no fastInverseSqrt. precision is the most important + double len = Math.sqrt(lenSq); + return this.multiply(1.0 / len); + } else { + PortalCubed.LOGGER.error("Normalizing zero-length quaternion", new Throwable()); + return IDENTITY; + } + } + + private static double fixCoordinateFloatingPointError(double num) { + final double threshold = 0.0000001; + if (Math.abs(num) < threshold) { + return 0; + } + + if (Math.abs(num - 1) < threshold) { + return 1; + } + + if (Math.abs(num - (-1)) < threshold) { + return -1; + } + + return num; + } + + public IPQuaternion getConjugated() { + return new IPQuaternion( + -x, -y, -z, w + ); + } + + public IPQuaternion hamiltonProduct(IPQuaternion other) { + double x1 = this.getX(); + double y1 = this.getY(); + double z1 = this.getZ(); + double w1 = this.getW(); + double x2 = other.getX(); + double y2 = other.getY(); + double z2 = other.getZ(); + double w2 = other.getW(); + return new IPQuaternion( + w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, + w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, + w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 + ); + } + + public static Tuple getPitchYawFromRotation(IPQuaternion quaternion) { + double x = quaternion.getX(); + double y = quaternion.getY(); + double z = quaternion.getZ(); + double w = quaternion.getW(); + + double cosYaw = 2 * (y * y + z * z) - 1; + double sinYaw = -(x * z + y * w) * 2; + + double cosPitch = 1 - 2 * (x * x + z * z); + double sinPitch = (x * w + y * z) * 2; + + return new Tuple<>( + Math.toDegrees(Math.atan2(sinPitch, cosPitch)), + Math.toDegrees(Math.atan2(sinYaw, cosYaw)) + ); + } + + public Vector3f getEulerAngles() { + final Vector3f eulerAngles = new Vector3f(); + eulerAngles.x = (float)Math.toDegrees(Math.atan2(x * w - y * z, 0.5f - x * x - y * y)); + eulerAngles.y = (float)Math.toDegrees(Math.safeAsin(2.0f * (x * z + y * w))); + eulerAngles.z = (float)Math.toDegrees(Math.atan2(z * w - x * y, 0.5f - y * y - z * z)); + return eulerAngles; + } + + + // x, y, z are the 3 rows of the matrix + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ + // only works if the matrix is rotation only + public static IPQuaternion matrixToQuaternion( + Vec3 x, Vec3 y, Vec3 z + ) { + double m00 = x.x(); + double m11 = y.y(); + double m22 = z.z(); + + double m12 = z.y(); + double m21 = y.z(); + + double m20 = x.z(); + double m02 = z.x(); + + double m01 = y.x(); + double m10 = x.y(); + + double tr = m00 + m11 + m22; + + double qx, qy, qz, qw; + + if (tr > 0) { + double s = Math.sqrt(tr + 1.0) * 2; // S=4*qw + qw = 0.25 * s; + qx = (m21 - m12) / s; + qy = (m02 - m20) / s; + qz = (m10 - m01) / s; + } else if ((m00 > m11) && (m00 > m22)) { + double s = Math.sqrt(1.0 + m00 - m11 - m22) * 2; // S=4*qx + qw = (m21 - m12) / s; + qx = 0.25 * s; + qy = (m01 + m10) / s; + qz = (m02 + m20) / s; + } else if (m11 > m22) { + double s = Math.sqrt(1.0 + m11 - m00 - m22) * 2; // S=4*qy + qw = (m02 - m20) / s; + qx = (m01 + m10) / s; + qy = 0.25 * s; + qz = (m12 + m21) / s; + } else { + double s = Math.sqrt(1.0 + m22 - m00 - m11) * 2; // S=4*qz + qw = (m10 - m01) / s; + qx = (m02 + m20) / s; + qy = (m12 + m21) / s; + qz = 0.25 * s; + } + + return new IPQuaternion(qx, qy, qz, qw); + } + + public static IPQuaternion getRotationBetween(Vec3 from, Vec3 to, Vec3 backup) { + from = from.normalize(); + to = to.normalize(); + Vec3 axis = from.cross(to).normalize(); + double cos = from.dot(to); + double angle = Math.acos(cos); + + if (Math.toDegrees(angle) == 180) { + axis = backup; + } + return IPQuaternion.rotationByRadians(axis, angle); + } + + public Quaternionf toQuaternionf() { + return new Quaternionf(x, y, z, w); + } + + public Quaterniond toQuaterniond() { + return new Quaterniond(x, y, z, w); + } + + public static IPQuaternion fromEuler(float angleX, float angleY, float angleZ) { + angleX = Math.toRadians(angleX); + angleY = Math.toRadians(angleY); + angleZ = Math.toRadians(angleZ); + float sx = Math.sin(angleX * 0.5f); + float cx = Math.cosFromSin(sx, angleX * 0.5f); + float sy = Math.sin(angleY * 0.5f); + float cy = Math.cosFromSin(sy, angleY * 0.5f); + float sz = Math.sin(angleZ * 0.5f); + float cz = Math.cosFromSin(sz, angleZ * 0.5f); + float yx = cy * sx; + float yy = sy * cx; + float yz = sy * sx; + float yw = cy * cx; + return new IPQuaternion( + yx * cz + yy * sz, + yy * cz - yx * sz, + yw * sz - yz * cz, + yw * cz + yz * sz + ); + } + + public static IPQuaternion fromQuaternionf(Quaternionf joml) { + return new IPQuaternion(joml.x, joml.y, joml.z, joml.w); + } + + public double dotProduct(IPQuaternion q) { + return getX() * q.getX() + + getY() * q.getY() + + getZ() * q.getZ() + + getW() * q.getW(); + } + + public static IPQuaternion getCameraRotation(double pitch, double yaw) { + IPQuaternion r1 = rotationByDegrees(new Vec3(1, 0, 0), Mth.clamp(pitch, -89.9999, 89.9999)); + IPQuaternion r2 = rotationByDegrees(new Vec3(0, 1, 0), yaw + 180); + return r1.hamiltonProduct(r2); + } + + public static IPQuaternion rotationByDegrees( + Vec3 rotatingAxis, + double degrees + ) { + return rotationByRadians( + rotatingAxis, Math.toRadians(degrees) + ); + } + + public static IPQuaternion interpolate( + IPQuaternion a, + IPQuaternion b, + double t + ) { + + double dot = a.dotProduct(b); + + if (dot < 0.0f) { + a = a.multiply(-1); + dot = -dot; + } + + final double DOT_THRESHOLD = 0.9995; + if (dot > DOT_THRESHOLD) { + // If the inputs are too close for comfort, linearly interpolate + // and normalize the result. + + return a.multiply(1 - t).add(b.multiply(t)).getNormalized(); + } + + double theta0 = Math.acos(dot); + double theta = theta0 * t; + double sinTheta = Math.sin(theta); + double sinTheta0 = Math.sin(theta0); + + double s0 = Math.cos(theta) - dot * sinTheta / sinTheta0; + double s1 = sinTheta / sinTheta0; + + return a.multiply(s0).add(b.multiply(s1)); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/LerpedQuaternion.java b/src/main/java/com/fusionflux/portalcubed/util/LerpedQuaternion.java index ed648c00..412a405a 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/LerpedQuaternion.java +++ b/src/main/java/com/fusionflux/portalcubed/util/LerpedQuaternion.java @@ -9,132 +9,132 @@ import net.minecraft.network.FriendlyByteBuf; public class LerpedQuaternion { - private Quaternionf start; - private Quaternionf end; - private float duration; - private Consumer updateCallback; - - private int ticks; - - public LerpedQuaternion(Quaternionf start) { - this.start = start; - } - - public void tick() { - if (isActive()) { - ticks++; - if (ticks > duration) { - finish(); - } - } - } - - public LerpedQuaternion withUpdateCallback(Consumer callback) { - this.updateCallback = callback; - return this; - } - - public LerpedQuaternion lerpTo(Quaternionf end) { - return lerpTo(end, 20); - } - - public LerpedQuaternion lerpTo(Quaternionf end, float duration) { - this.end = end; - this.duration = duration; - onUpdate(); - return this; - } - - public void set(Quaternionf start) { - this.end = start; // finish will set start to end - finish(); - } - - public boolean isActive() { - return end != null; - } - - public Quaternionf get() { - float progress = Math.min(1, ticks / duration); - return getInternal(progress); - } - - public Quaternionf get(float partialTicks) { - float progress = Math.min(1, (ticks + partialTicks) / duration); - return getInternal(progress); - } - - private Quaternionf getInternal(float progress) { - if (!isActive()) - return start; - return start.slerp(end, progress, new Quaternionf()); - } - - private void onUpdate() { - if (updateCallback != null) - updateCallback.accept(this); - } - - private void finish() { - this.start = this.end; - this.end = null; - this.ticks = 0; - this.duration = 0; - onUpdate(); - } - - public LerpedQuaternion copy() { - LerpedQuaternion copy = new LerpedQuaternion(start).withUpdateCallback(this.updateCallback); - if (isActive()) { - copy.end = this.end; - copy.ticks = this.ticks; - copy.duration = this.duration; - } - return copy; - } - - public void toNetwork(FriendlyByteBuf buf) { - buf.writeQuaternion(start); - if (isActive()) { - buf.writeBoolean(true); - buf.writeQuaternion(end); - buf.writeVarInt(ticks); - buf.writeFloat(duration); - } else { - buf.writeBoolean(false); - } - } - - public static LerpedQuaternion fromNetwork(FriendlyByteBuf buf) { - Quaternionf start = buf.readQuaternion(); - LerpedQuaternion quaternion = new LerpedQuaternion(start); - if (!buf.readBoolean()) - return quaternion; - quaternion.end = buf.readQuaternion(); - quaternion.ticks = buf.readVarInt(); - quaternion.duration = buf.readFloat(); - return quaternion; - } - - public CompoundTag toNbt() { - CompoundTag nbt = new CompoundTag(); - NbtHelper.putQuaternion(nbt, "start", start); - if (isActive()) { - NbtHelper.putQuaternion(nbt, "end", end); - nbt.putInt("ticks", ticks); - nbt.putFloat("duration", duration); - } - return nbt; - } - - public static LerpedQuaternion fromNbt(CompoundTag tag) { - Quaternionf start = NbtHelper.getQuaternion(tag, "start"); - LerpedQuaternion quaternion = new LerpedQuaternion(start); - if (tag.contains("end", Tag.TAG_COMPOUND) && tag.contains("ticks", Tag.TAG_INT) && tag.contains("duration", Tag.TAG_FLOAT)) { - quaternion.end = NbtHelper.getQuaternion(tag, "end"); - quaternion.ticks = tag.getInt("ticks"); - quaternion.duration = tag.getFloat("duration"); - } - return quaternion; - } + private Quaternionf start; + private Quaternionf end; + private float duration; + private Consumer updateCallback; + + private int ticks; + + public LerpedQuaternion(Quaternionf start) { + this.start = start; + } + + public void tick() { + if (isActive()) { + ticks++; + if (ticks > duration) { + finish(); + } + } + } + + public LerpedQuaternion withUpdateCallback(Consumer callback) { + this.updateCallback = callback; + return this; + } + + public LerpedQuaternion lerpTo(Quaternionf end) { + return lerpTo(end, 20); + } + + public LerpedQuaternion lerpTo(Quaternionf end, float duration) { + this.end = end; + this.duration = duration; + onUpdate(); + return this; + } + + public void set(Quaternionf start) { + this.end = start; // finish will set start to end + finish(); + } + + public boolean isActive() { + return end != null; + } + + public Quaternionf get() { + float progress = Math.min(1, ticks / duration); + return getInternal(progress); + } + + public Quaternionf get(float partialTicks) { + float progress = Math.min(1, (ticks + partialTicks) / duration); + return getInternal(progress); + } + + private Quaternionf getInternal(float progress) { + if (!isActive()) + return start; + return start.slerp(end, progress, new Quaternionf()); + } + + private void onUpdate() { + if (updateCallback != null) + updateCallback.accept(this); + } + + private void finish() { + this.start = this.end; + this.end = null; + this.ticks = 0; + this.duration = 0; + onUpdate(); + } + + public LerpedQuaternion copy() { + LerpedQuaternion copy = new LerpedQuaternion(start).withUpdateCallback(this.updateCallback); + if (isActive()) { + copy.end = this.end; + copy.ticks = this.ticks; + copy.duration = this.duration; + } + return copy; + } + + public void toNetwork(FriendlyByteBuf buf) { + buf.writeQuaternion(start); + if (isActive()) { + buf.writeBoolean(true); + buf.writeQuaternion(end); + buf.writeVarInt(ticks); + buf.writeFloat(duration); + } else { + buf.writeBoolean(false); + } + } + + public static LerpedQuaternion fromNetwork(FriendlyByteBuf buf) { + Quaternionf start = buf.readQuaternion(); + LerpedQuaternion quaternion = new LerpedQuaternion(start); + if (!buf.readBoolean()) + return quaternion; + quaternion.end = buf.readQuaternion(); + quaternion.ticks = buf.readVarInt(); + quaternion.duration = buf.readFloat(); + return quaternion; + } + + public CompoundTag toNbt() { + CompoundTag nbt = new CompoundTag(); + NbtHelper.putQuaternion(nbt, "start", start); + if (isActive()) { + NbtHelper.putQuaternion(nbt, "end", end); + nbt.putInt("ticks", ticks); + nbt.putFloat("duration", duration); + } + return nbt; + } + + public static LerpedQuaternion fromNbt(CompoundTag tag) { + Quaternionf start = NbtHelper.getQuaternion(tag, "start"); + LerpedQuaternion quaternion = new LerpedQuaternion(start); + if (tag.contains("end", Tag.TAG_COMPOUND) && tag.contains("ticks", Tag.TAG_INT) && tag.contains("duration", Tag.TAG_FLOAT)) { + quaternion.end = NbtHelper.getQuaternion(tag, "end"); + quaternion.ticks = tag.getInt("ticks"); + quaternion.duration = tag.getFloat("duration"); + } + return quaternion; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/MutableVec3.java b/src/main/java/com/fusionflux/portalcubed/util/MutableVec3.java index e6c9336a..1259bc54 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/MutableVec3.java +++ b/src/main/java/com/fusionflux/portalcubed/util/MutableVec3.java @@ -4,31 +4,31 @@ import net.minecraft.world.phys.Vec3; public class MutableVec3 { - public double x, y, z; + public double x, y, z; - public MutableVec3() { - this(0, 0, 0); - } + public MutableVec3() { + this(0, 0, 0); + } - public MutableVec3(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public MutableVec3(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public MutableVec3(Vec3 vec) { - this(vec.x, vec.y, vec.z); - } + public MutableVec3(Vec3 vec) { + this(vec.x, vec.y, vec.z); + } - public void set(Axis axis, double value) { - switch (axis) { - case X -> this.x = value; - case Y -> this.y = value; - case Z -> this.z = value; - } - } + public void set(Axis axis, double value) { + switch (axis) { + case X -> this.x = value; + case Y -> this.y = value; + case Z -> this.z = value; + } + } - public double get(Axis axis) { - return axis.choose(x, y, z); - } + public double get(Axis axis) { + return axis.choose(x, y, z); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/NbtHelper.java b/src/main/java/com/fusionflux/portalcubed/util/NbtHelper.java index 81d88b30..c93f3a84 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/NbtHelper.java +++ b/src/main/java/com/fusionflux/portalcubed/util/NbtHelper.java @@ -8,65 +8,65 @@ import org.joml.Quaternionf; public class NbtHelper { - public static void putVec3d(CompoundTag compoundTag, String name, Vec3 vec3d) { - final ListTag list = new ListTag(); - list.add(DoubleTag.valueOf(vec3d.x)); - list.add(DoubleTag.valueOf(vec3d.y)); - list.add(DoubleTag.valueOf(vec3d.z)); - compoundTag.put(name, list); - } + public static void putVec3d(CompoundTag compoundTag, String name, Vec3 vec3d) { + final ListTag list = new ListTag(); + list.add(DoubleTag.valueOf(vec3d.x)); + list.add(DoubleTag.valueOf(vec3d.y)); + list.add(DoubleTag.valueOf(vec3d.z)); + compoundTag.put(name, list); + } - public static Vec3 getVec3d(CompoundTag compoundTag, String name) { - final ListTag list = compoundTag.getList(name, Tag.TAG_DOUBLE); - return new Vec3( - list.getDouble(0), - list.getDouble(1), - list.getDouble(2) - ); - } + public static Vec3 getVec3d(CompoundTag compoundTag, String name) { + final ListTag list = compoundTag.getList(name, Tag.TAG_DOUBLE); + return new Vec3( + list.getDouble(0), + list.getDouble(1), + list.getDouble(2) + ); + } - public static void putQuaternion(CompoundTag compoundTag, String name, Quaternionf quat) { - final ListTag list = new ListTag(); - list.add(FloatTag.valueOf(quat.x)); - list.add(FloatTag.valueOf(quat.y)); - list.add(FloatTag.valueOf(quat.z)); - list.add(FloatTag.valueOf(quat.w)); - compoundTag.put(name, list); - } + public static void putQuaternion(CompoundTag compoundTag, String name, Quaternionf quat) { + final ListTag list = new ListTag(); + list.add(FloatTag.valueOf(quat.x)); + list.add(FloatTag.valueOf(quat.y)); + list.add(FloatTag.valueOf(quat.z)); + list.add(FloatTag.valueOf(quat.w)); + compoundTag.put(name, list); + } - public static Quaternionf getQuaternion(CompoundTag compoundTag, String name) { - final ListTag list = compoundTag.getList(name, Tag.TAG_FLOAT); - final Quaternionf result = new Quaternionf( - list.getFloat(0), - list.getFloat(1), - list.getFloat(2), - list.getFloat(3) - ); - if (result.lengthSquared() < 1e-7f) { - result.identity(); // Just in case the quat ends up as (0, 0, 0, 0) - } - return result; - } + public static Quaternionf getQuaternion(CompoundTag compoundTag, String name) { + final ListTag list = compoundTag.getList(name, Tag.TAG_FLOAT); + final Quaternionf result = new Quaternionf( + list.getFloat(0), + list.getFloat(1), + list.getFloat(2), + list.getFloat(3) + ); + if (result.lengthSquared() < 1e-7f) { + result.identity(); // Just in case the quat ends up as (0, 0, 0, 0) + } + return result; + } - @Nullable - public static BlockPos readNullableBlockPos(CompoundTag tag, String key) { - if (!tag.contains(key, Tag.TAG_COMPOUND)) - return null; - CompoundTag pos = tag.getCompound(key); - if (pos.contains("X", Tag.TAG_INT) && pos.contains("Y", Tag.TAG_INT) && pos.contains("Z", Tag.TAG_INT)) - return new BlockPos(pos.getInt("X"), pos.getInt("Y"), pos.getInt("Z")); - return null; - } + @Nullable + public static BlockPos readNullableBlockPos(CompoundTag tag, String key) { + if (!tag.contains(key, Tag.TAG_COMPOUND)) + return null; + CompoundTag pos = tag.getCompound(key); + if (pos.contains("X", Tag.TAG_INT) && pos.contains("Y", Tag.TAG_INT) && pos.contains("Z", Tag.TAG_INT)) + return new BlockPos(pos.getInt("X"), pos.getInt("Y"), pos.getInt("Z")); + return null; + } - public static & StringRepresentable> T readEnum(CompoundTag tag, String key, T fallback) { - if (!tag.contains(key, Tag.TAG_STRING)) - return fallback; - String name = tag.getString(key); - @SuppressWarnings("unchecked") Class clazz = (Class) fallback.getClass(); - for (T entry : clazz.getEnumConstants()) { - if (entry.getSerializedName().equals(name)) - return entry; - } - return fallback; - } + public static & StringRepresentable> T readEnum(CompoundTag tag, String key, T fallback) { + if (!tag.contains(key, Tag.TAG_STRING)) + return fallback; + String name = tag.getString(key); + @SuppressWarnings("unchecked") Class clazz = (Class) fallback.getClass(); + for (T entry : clazz.getEnumConstants()) { + if (entry.getSerializedName().equals(name)) + return entry; + } + return fallback; + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponent.java b/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponent.java index 7aa976a2..8258286b 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponent.java +++ b/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponent.java @@ -11,43 +11,43 @@ public interface PortalCubedComponent extends Component { - Set getPortals(); + Set getPortals(); - void addPortals(UUID portalUUID); + void addPortals(UUID portalUUID); - void removePortals(UUID portalUUID); + void removePortals(UUID portalUUID); - VoxelShape getPortalCutout(); + VoxelShape getPortalCutout(); - void setPortalCutout(VoxelShape cutout); + void setPortalCutout(VoxelShape cutout); - VoxelShape getCrossPortalCollision(); + VoxelShape getCrossPortalCollision(); - void setCrossPortalCollision(VoxelShape collision); + void setCrossPortalCollision(VoxelShape collision); - boolean getHasTeleportationHappened(); + boolean getHasTeleportationHappened(); - void setHasTeleportationHappened(boolean hasHappened); + void setHasTeleportationHappened(boolean hasHappened); - boolean getWasInfiniteFalling(); + boolean getWasInfiniteFalling(); - void setWasInfiniteFalling(boolean infFall); + void setWasInfiniteFalling(boolean infFall); - Vec3 getVelocityUpdateAfterTeleport(); + Vec3 getVelocityUpdateAfterTeleport(); - void setVelocityUpdateAfterTeleport(Vec3 velocity); + void setVelocityUpdateAfterTeleport(Vec3 velocity); - boolean getCanFireGel(); + boolean getCanFireGel(); - void setCanFireGel(boolean canGel); + void setCanFireGel(boolean canGel); - Vec3 getServerVelForGel(); + Vec3 getServerVelForGel(); - void setServerVelForGel(Vec3 velocity); + void setServerVelForGel(Vec3 velocity); - @Nullable - BlockPos getLauncher(); + @Nullable + BlockPos getLauncher(); - void setLauncher(@Nullable BlockPos launcher); + void setLauncher(@Nullable BlockPos launcher); } diff --git a/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponents.java b/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponents.java index 1d27a9c1..a1caad50 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponents.java +++ b/src/main/java/com/fusionflux/portalcubed/util/PortalCubedComponents.java @@ -10,12 +10,12 @@ import static com.fusionflux.portalcubed.PortalCubed.id; public class PortalCubedComponents implements EntityComponentInitializer { - public static final ComponentKey ENTITY_COMPONENT = ComponentRegistry.getOrCreate(id("entity_component"), PortalCubedComponent.class); - public static final ComponentKey HOLDER_COMPONENT = ComponentRegistry.getOrCreate(id("holder_component"), HolderComponent.class); + public static final ComponentKey ENTITY_COMPONENT = ComponentRegistry.getOrCreate(id("entity_component"), PortalCubedComponent.class); + public static final ComponentKey HOLDER_COMPONENT = ComponentRegistry.getOrCreate(id("holder_component"), HolderComponent.class); - @Override - public void registerEntityComponentFactories(EntityComponentFactoryRegistry registry) { - registry.registerFor(Entity.class, ENTITY_COMPONENT, EntityComponent::new); - registry.registerFor(Player.class, HOLDER_COMPONENT, HolderComponent::new); - } + @Override + public void registerEntityComponentFactories(EntityComponentFactoryRegistry registry) { + registry.registerFor(Entity.class, ENTITY_COMPONENT, EntityComponent::new); + registry.registerFor(Player.class, HOLDER_COMPONENT, HolderComponent::new); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/PortalDirectionUtils.java b/src/main/java/com/fusionflux/portalcubed/util/PortalDirectionUtils.java index 78128e89..6051ebc3 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/PortalDirectionUtils.java +++ b/src/main/java/com/fusionflux/portalcubed/util/PortalDirectionUtils.java @@ -18,65 +18,65 @@ import java.util.function.Predicate; public class PortalDirectionUtils { - public static Vec3 rotateVector(Portal portal, Vec3 vector) { - return portal.getTransformQuat().rotate(vector, false); - } + public static Vec3 rotateVector(Portal portal, Vec3 vector) { + return portal.getTransformQuat().rotate(vector, false); + } - public static final AdvancedEntityRaycast.TransformInfo PORTAL_RAYCAST_TRANSFORM = new AdvancedEntityRaycast.TransformInfo( - e -> e instanceof Portal, - (context, blockHit, entityHit) -> { - final Portal portal = (Portal)entityHit.getEntity(); - if (!portal.getActive()) return null; - final double distance = context.getFrom().distanceTo(context.getTo()); - final Vec3 offset = blockHit.getLocation().subtract(context.getFrom()); + public static final AdvancedEntityRaycast.TransformInfo PORTAL_RAYCAST_TRANSFORM = new AdvancedEntityRaycast.TransformInfo( + e -> e instanceof Portal, + (context, blockHit, entityHit) -> { + final Portal portal = (Portal)entityHit.getEntity(); + if (!portal.getActive()) return null; + final double distance = context.getFrom().distanceTo(context.getTo()); + final Vec3 offset = blockHit.getLocation().subtract(context.getFrom()); - final Direction facing = portal.getFacingDirection(); - final Vec3 newOffset = rotateVector(portal, offset) - .normalize() - .scale(distance - offset.length()); - final Vec3 hitRelative = entityHit.getLocation().subtract(portal.getOriginPos()) - .with(facing.getAxis(), 0); - final Vec3 newRel = rotateVector(portal, hitRelative); - final Vec3 newStart = portal.getDestination().orElseThrow().add(newRel); - return new AdvancedEntityRaycast.TransformResult( - blockHit.getLocation(), - AdvancedEntityRaycast.withStartEnd(context, newStart, newStart.add(newOffset)), - portal.getLinkedPortalUUID() - .flatMap(id -> Optional.ofNullable(((LevelExt)portal.level()).getEntityByUuid(id))) - .map(Set::of) - .orElse(Set.of()) - ); - } - ); + final Direction facing = portal.getFacingDirection(); + final Vec3 newOffset = rotateVector(portal, offset) + .normalize() + .scale(distance - offset.length()); + final Vec3 hitRelative = entityHit.getLocation().subtract(portal.getOriginPos()) + .with(facing.getAxis(), 0); + final Vec3 newRel = rotateVector(portal, hitRelative); + final Vec3 newStart = portal.getDestination().orElseThrow().add(newRel); + return new AdvancedEntityRaycast.TransformResult( + blockHit.getLocation(), + AdvancedEntityRaycast.withStartEnd(context, newStart, newStart.add(newOffset)), + portal.getLinkedPortalUUID() + .flatMap(id -> Optional.ofNullable(((LevelExt)portal.level()).getEntityByUuid(id))) + .map(Set::of) + .orElse(Set.of()) + ); + } + ); - public static AdvancedEntityRaycast.Result raycast(Level level, ClipContext context) { - return AdvancedEntityRaycast.raycast(level, context, Level::clip, PORTAL_RAYCAST_TRANSFORM); - } + public static AdvancedEntityRaycast.Result raycast(Level level, ClipContext context) { + return AdvancedEntityRaycast.raycast(level, context, Level::clip, PORTAL_RAYCAST_TRANSFORM); + } - /** - * @param originEntity The entity responsible for the raycast - * @return New vector after transformation. If null, there was no portal between {@code startPos} and {@code endPos}. - * Usually this is interpreted as a return value of {@code endPos}, but that's not a requirement. - */ - @Nullable - public static Pair simpleTransformPassingVector(Entity originEntity, Vec3 startPos, Vec3 endPos, Predicate portalPredicate) { - final EntityHitResult hit = ProjectileUtil.getEntityHitResult( - originEntity, startPos, endPos, - new AABB(startPos, endPos).inflate(1), - e -> e instanceof Portal portal && portal.getActive() && portalPredicate.test(portal), - startPos.distanceToSqr(endPos) - ); - if (hit == null) return null; - final Portal portal = (Portal)hit.getEntity(); - final Direction facing = portal.getFacingDirection(); - final double yOffset = endPos.distanceTo(startPos) - hit.getLocation().distanceTo(startPos); - final Vec3 hitRelative = PortalDirectionUtils.rotateVector( - portal, - hit.getLocation() - .subtract(portal.getOriginPos()) - .with(facing.getAxis(), facing.getAxisDirection().getStep() * -1 * yOffset) - ); - return Pair.of(portal.getDestination().orElseThrow().add(hitRelative), portal); - } + /** + * @param originEntity The entity responsible for the raycast + * @return New vector after transformation. If null, there was no portal between {@code startPos} and {@code endPos}. + * Usually this is interpreted as a return value of {@code endPos}, but that's not a requirement. + */ + @Nullable + public static Pair simpleTransformPassingVector(Entity originEntity, Vec3 startPos, Vec3 endPos, Predicate portalPredicate) { + final EntityHitResult hit = ProjectileUtil.getEntityHitResult( + originEntity, startPos, endPos, + new AABB(startPos, endPos).inflate(1), + e -> e instanceof Portal portal && portal.getActive() && portalPredicate.test(portal), + startPos.distanceToSqr(endPos) + ); + if (hit == null) return null; + final Portal portal = (Portal)hit.getEntity(); + final Direction facing = portal.getFacingDirection(); + final double yOffset = endPos.distanceTo(startPos) - hit.getLocation().distanceTo(startPos); + final Vec3 hitRelative = PortalDirectionUtils.rotateVector( + portal, + hit.getLocation() + .subtract(portal.getOriginPos()) + .with(facing.getAxis(), facing.getAxisDirection().getStep() * -1 * yOffset) + ); + return Pair.of(portal.getDestination().orElseThrow().add(hitRelative), portal); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/TwoByTwo.java b/src/main/java/com/fusionflux/portalcubed/util/TwoByTwo.java index 8ac2a164..da70be0e 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/TwoByTwo.java +++ b/src/main/java/com/fusionflux/portalcubed/util/TwoByTwo.java @@ -14,81 +14,81 @@ import java.util.List; public record TwoByTwo(BlockPos topRight, BlockPos topLeft, BlockPos bottomLeft, BlockPos bottomRight) implements Iterable { - public static TwoByTwo fromBottomRightCorner(BlockPos bottomRight, Direction left, Direction up) { - return new TwoByTwo( - bottomRight.relative(up), bottomRight.relative(up).relative(left), bottomRight.relative(left), bottomRight - ); - } + public static TwoByTwo fromBottomRightCorner(BlockPos bottomRight, Direction left, Direction up) { + return new TwoByTwo( + bottomRight.relative(up), bottomRight.relative(up).relative(left), bottomRight.relative(left), bottomRight + ); + } - public static TwoByTwo fromTopLeftCorner(BlockPos topLeft, Direction right, Direction down) { - return new TwoByTwo( - topLeft.relative(right), topLeft, topLeft.relative(down), topLeft.relative(right).relative(down) - ); - } + public static TwoByTwo fromTopLeftCorner(BlockPos topLeft, Direction right, Direction down) { + return new TwoByTwo( + topLeft.relative(right), topLeft, topLeft.relative(down), topLeft.relative(right).relative(down) + ); + } - @Nullable - public static TwoByTwo fromNbt(CompoundTag tag) { - BlockPos topRight = NbtHelper.readNullableBlockPos(tag, "topRight"); - BlockPos topLeft = NbtHelper.readNullableBlockPos(tag, "topLeft"); - BlockPos bottomLeft = NbtHelper.readNullableBlockPos(tag, "bottomLeft"); - BlockPos bottomRight = NbtHelper.readNullableBlockPos(tag, "bottomRight"); - TwoByTwo twoByTwo = new TwoByTwo(topRight, topLeft, bottomLeft, bottomRight); - for (BlockPos pos : twoByTwo) { - if (pos == null) - return null; - } - return twoByTwo; - } + @Nullable + public static TwoByTwo fromNbt(CompoundTag tag) { + BlockPos topRight = NbtHelper.readNullableBlockPos(tag, "topRight"); + BlockPos topLeft = NbtHelper.readNullableBlockPos(tag, "topLeft"); + BlockPos bottomLeft = NbtHelper.readNullableBlockPos(tag, "bottomLeft"); + BlockPos bottomRight = NbtHelper.readNullableBlockPos(tag, "bottomRight"); + TwoByTwo twoByTwo = new TwoByTwo(topRight, topLeft, bottomLeft, bottomRight); + for (BlockPos pos : twoByTwo) { + if (pos == null) + return null; + } + return twoByTwo; + } - public BlockPos byQuadrantIndex(int index) { - return byQuadrant(index + 1); - } + public BlockPos byQuadrantIndex(int index) { + return byQuadrant(index + 1); + } - public BlockPos byQuadrant(int quadrant) { - return switch (quadrant) { - case 1 -> topRight; - case 2 -> topLeft; - case 3 -> bottomLeft; - case 4 -> bottomRight; - default -> throw new IllegalArgumentException("Invalid quadrant: " + quadrant); - }; - } + public BlockPos byQuadrant(int quadrant) { + return switch (quadrant) { + case 1 -> topRight; + case 2 -> topLeft; + case 3 -> bottomLeft; + case 4 -> bottomRight; + default -> throw new IllegalArgumentException("Invalid quadrant: " + quadrant); + }; + } - public Iterable quadrants(int first, int second, int third, int fourth) { - return List.of(byQuadrant(first), byQuadrant(second), byQuadrant(third), byQuadrant(fourth)); - } + public Iterable quadrants(int first, int second, int third, int fourth) { + return List.of(byQuadrant(first), byQuadrant(second), byQuadrant(third), byQuadrant(fourth)); + } - public Vec3 getCenter() { - // average centers of each pos - double totalX = 0, totalY = 0, totalZ = 0; - for (BlockPos pos : this) { - totalX += pos.getX() + 0.5; - totalY += pos.getY() + 0.5; - totalZ += pos.getZ() + 0.5; - } - return new Vec3(totalX / 4f, totalY / 4f, totalZ / 4f); - } + public Vec3 getCenter() { + // average centers of each pos + double totalX = 0, totalY = 0, totalZ = 0; + for (BlockPos pos : this) { + totalX += pos.getX() + 0.5; + totalY += pos.getY() + 0.5; + totalZ += pos.getZ() + 0.5; + } + return new Vec3(totalX / 4f, totalY / 4f, totalZ / 4f); + } - public AABB toBox(double inflate) { - return new AABB(bottomLeft, topRight).inflate(inflate); - } + public AABB toBox(double inflate) { + return new AABB(bottomLeft, topRight).inflate(inflate); + } - public CompoundTag toNbt() { - CompoundTag tag = new CompoundTag(); - tag.put("topRight", NbtUtils.writeBlockPos(topRight)); - tag.put("topLeft", NbtUtils.writeBlockPos(topLeft)); - tag.put("bottomLeft", NbtUtils.writeBlockPos(bottomLeft)); - tag.put("bottomRight", NbtUtils.writeBlockPos(bottomRight)); - return tag; - } + public CompoundTag toNbt() { + CompoundTag tag = new CompoundTag(); + tag.put("topRight", NbtUtils.writeBlockPos(topRight)); + tag.put("topLeft", NbtUtils.writeBlockPos(topLeft)); + tag.put("bottomLeft", NbtUtils.writeBlockPos(bottomLeft)); + tag.put("bottomRight", NbtUtils.writeBlockPos(bottomRight)); + return tag; + } - @NotNull - @Override - public Iterator iterator() { - return Iterators.forArray(topRight, topLeft, bottomLeft, bottomRight); - } + @NotNull + @Override + public Iterator iterator() { + return Iterators.forArray(topRight, topLeft, bottomLeft, bottomRight); + } - public boolean contains(BlockPos pos) { - return pos.equals(topRight) || pos.equals(topLeft) || pos.equals(bottomLeft) || pos.equals(bottomRight); - } + public boolean contains(BlockPos pos) { + return pos.equals(topRight) || pos.equals(topLeft) || pos.equals(bottomLeft) || pos.equals(bottomRight); + } } diff --git a/src/main/java/com/fusionflux/portalcubed/util/VoxelShaper.java b/src/main/java/com/fusionflux/portalcubed/util/VoxelShaper.java index 2d2469dd..c4741253 100644 --- a/src/main/java/com/fusionflux/portalcubed/util/VoxelShaper.java +++ b/src/main/java/com/fusionflux/portalcubed/util/VoxelShaper.java @@ -17,155 +17,155 @@ // Taken from Create, licensed under MIT: https://github.com/Creators-of-Create/Create/blob/mc1.18/dev/src/main/java/com/simibubi/create/foundation/utility/VoxelShaper.java public class VoxelShaper { - private static final Vec3 BLOCK_CENTER = new Vec3(8, 8, 8); - - private final Map shapes = new HashMap<>(); - - public VoxelShape get(Direction direction) { - return shapes.get(direction); - } - - public VoxelShape get(Axis axis) { - return shapes.get(axisAsFace(axis)); - } - - public static VoxelShaper forHorizontal(VoxelShape shape, Direction facing) { - return forDirectionsWithRotation(shape, facing, Direction.Plane.HORIZONTAL, new HorizontalRotationValues()); - } - - public static VoxelShaper forHorizontalAxis(VoxelShape shape, Axis along) { - return forDirectionsWithRotation(shape, axisAsFace(along), Arrays.asList(Direction.SOUTH, Direction.EAST), - new HorizontalRotationValues()); - } - - public static VoxelShaper forDirectional(VoxelShape shape, Direction facing) { - return forDirectionsWithRotation(shape, facing, Arrays.asList(Direction.values()), new DefaultRotationValues()); - } - - public static VoxelShaper forAxis(VoxelShape shape, Axis along) { - return forDirectionsWithRotation(shape, axisAsFace(along), - Arrays.asList(Direction.SOUTH, Direction.EAST, Direction.UP), new DefaultRotationValues()); - } - - public VoxelShaper withVerticalShapes(VoxelShape upShape) { - shapes.put(Direction.UP, upShape); - shapes.put(Direction.DOWN, rotatedCopy(upShape, new Vec3(180, 0, 0), BLOCK_CENTER)); - return this; - } - - public VoxelShaper withShape(VoxelShape shape, Direction facing) { - shapes.put(facing, shape); - return this; - } - - public static Direction axisAsFace(Axis axis) { - return Direction.get(AxisDirection.POSITIVE, axis); - } - - protected static float horizontalAngleFromDirection(Direction direction) { - return (float) ((Math.max(direction.get2DDataValue(), 0) & 3) * 90); - } - - protected static VoxelShaper forDirectionsWithRotation(VoxelShape shape, Direction facing, - Iterable directions, Function rotationValues) { - VoxelShaper voxelShaper = new VoxelShaper(); - for (Direction dir : directions) { - voxelShaper.shapes.put(dir, rotate(shape, facing, dir, rotationValues)); - } - return voxelShaper; - } - - public static VoxelShape rotate(VoxelShape shape, Direction from, Direction to, - Function usingValues) { - if (from == to) - return shape; - - return rotatedCopy( - shape, - usingValues.apply(from) - .reverse() - .add(usingValues.apply(to)), - BLOCK_CENTER - ); - } - - public static VoxelShape rotatedCopy(VoxelShape shape, Vec3 rotation, Vec3 origin) { - if (rotation.equals(Vec3.ZERO)) - return shape; - - MutableObject result = new MutableObject<>(Shapes.empty()); - - shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> { - Vec3 v1 = new Vec3(x1, y1, z1).scale(16) - .subtract(origin); - Vec3 v2 = new Vec3(x2, y2, z2).scale(16) - .subtract(origin); - - v1 = rotate(v1, (float) rotation.x, Axis.X); - v1 = rotate(v1, (float) rotation.y, Axis.Y); - v1 = rotate(v1, (float) rotation.z, Axis.Z) - .add(origin); - - v2 = rotate(v2, (float) rotation.x, Axis.X); - v2 = rotate(v2, (float) rotation.y, Axis.Y); - v2 = rotate(v2, (float) rotation.z, Axis.Z) - .add(origin); - - VoxelShape rotated = blockBox(v1, v2); - result.setValue(Shapes.or(result.getValue(), rotated)); - }); - - return result.getValue(); - } - - protected static VoxelShape blockBox(Vec3 v1, Vec3 v2) { - return Block.box( - Math.min(v1.x, v2.x), - Math.min(v1.y, v2.y), - Math.min(v1.z, v2.z), - Math.max(v1.x, v2.x), - Math.max(v1.y, v2.y), - Math.max(v1.z, v2.z) - ); - } - - protected static class DefaultRotationValues implements Function { - // assume facing up as the default rotation - @Override - public Vec3 apply(Direction direction) { - return new Vec3(direction == Direction.UP ? 0 : (Direction.Plane.VERTICAL.test(direction) ? 180 : 90), - -horizontalAngleFromDirection(direction), 0); - } - } - - protected static class HorizontalRotationValues implements Function { - @Override - public Vec3 apply(Direction direction) { - return new Vec3(0, -horizontalAngleFromDirection(direction), 0); - } - } - - // this method is from VecHelper: https://github.com/Creators-of-Create/Create/blob/39ef3da5df0fad2054d8b95f15b51b4199479774/src/main/java/com/simibubi/create/foundation/utility/VecHelper.java#L46 - public static Vec3 rotate(Vec3 vec, double deg, Axis axis) { - if (deg == 0) - return vec; - if (vec == Vec3.ZERO) - return vec; - - float angle = (float) (deg / 180f * Math.PI); - double sin = Mth.sin(angle); - double cos = Mth.cos(angle); - double x = vec.x; - double y = vec.y; - double z = vec.z; - - if (axis == Axis.X) - return new Vec3(x, y * cos - z * sin, z * cos + y * sin); - if (axis == Axis.Y) - return new Vec3(x * cos + z * sin, y, z * cos - x * sin); - if (axis == Axis.Z) - return new Vec3(x * cos - y * sin, y * cos + x * sin, z); - return vec; - } + private static final Vec3 BLOCK_CENTER = new Vec3(8, 8, 8); + + private final Map shapes = new HashMap<>(); + + public VoxelShape get(Direction direction) { + return shapes.get(direction); + } + + public VoxelShape get(Axis axis) { + return shapes.get(axisAsFace(axis)); + } + + public static VoxelShaper forHorizontal(VoxelShape shape, Direction facing) { + return forDirectionsWithRotation(shape, facing, Direction.Plane.HORIZONTAL, new HorizontalRotationValues()); + } + + public static VoxelShaper forHorizontalAxis(VoxelShape shape, Axis along) { + return forDirectionsWithRotation(shape, axisAsFace(along), Arrays.asList(Direction.SOUTH, Direction.EAST), + new HorizontalRotationValues()); + } + + public static VoxelShaper forDirectional(VoxelShape shape, Direction facing) { + return forDirectionsWithRotation(shape, facing, Arrays.asList(Direction.values()), new DefaultRotationValues()); + } + + public static VoxelShaper forAxis(VoxelShape shape, Axis along) { + return forDirectionsWithRotation(shape, axisAsFace(along), + Arrays.asList(Direction.SOUTH, Direction.EAST, Direction.UP), new DefaultRotationValues()); + } + + public VoxelShaper withVerticalShapes(VoxelShape upShape) { + shapes.put(Direction.UP, upShape); + shapes.put(Direction.DOWN, rotatedCopy(upShape, new Vec3(180, 0, 0), BLOCK_CENTER)); + return this; + } + + public VoxelShaper withShape(VoxelShape shape, Direction facing) { + shapes.put(facing, shape); + return this; + } + + public static Direction axisAsFace(Axis axis) { + return Direction.get(AxisDirection.POSITIVE, axis); + } + + protected static float horizontalAngleFromDirection(Direction direction) { + return (float) ((Math.max(direction.get2DDataValue(), 0) & 3) * 90); + } + + protected static VoxelShaper forDirectionsWithRotation(VoxelShape shape, Direction facing, + Iterable directions, Function rotationValues) { + VoxelShaper voxelShaper = new VoxelShaper(); + for (Direction dir : directions) { + voxelShaper.shapes.put(dir, rotate(shape, facing, dir, rotationValues)); + } + return voxelShaper; + } + + public static VoxelShape rotate(VoxelShape shape, Direction from, Direction to, + Function usingValues) { + if (from == to) + return shape; + + return rotatedCopy( + shape, + usingValues.apply(from) + .reverse() + .add(usingValues.apply(to)), + BLOCK_CENTER + ); + } + + public static VoxelShape rotatedCopy(VoxelShape shape, Vec3 rotation, Vec3 origin) { + if (rotation.equals(Vec3.ZERO)) + return shape; + + MutableObject result = new MutableObject<>(Shapes.empty()); + + shape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> { + Vec3 v1 = new Vec3(x1, y1, z1).scale(16) + .subtract(origin); + Vec3 v2 = new Vec3(x2, y2, z2).scale(16) + .subtract(origin); + + v1 = rotate(v1, (float) rotation.x, Axis.X); + v1 = rotate(v1, (float) rotation.y, Axis.Y); + v1 = rotate(v1, (float) rotation.z, Axis.Z) + .add(origin); + + v2 = rotate(v2, (float) rotation.x, Axis.X); + v2 = rotate(v2, (float) rotation.y, Axis.Y); + v2 = rotate(v2, (float) rotation.z, Axis.Z) + .add(origin); + + VoxelShape rotated = blockBox(v1, v2); + result.setValue(Shapes.or(result.getValue(), rotated)); + }); + + return result.getValue(); + } + + protected static VoxelShape blockBox(Vec3 v1, Vec3 v2) { + return Block.box( + Math.min(v1.x, v2.x), + Math.min(v1.y, v2.y), + Math.min(v1.z, v2.z), + Math.max(v1.x, v2.x), + Math.max(v1.y, v2.y), + Math.max(v1.z, v2.z) + ); + } + + protected static class DefaultRotationValues implements Function { + // assume facing up as the default rotation + @Override + public Vec3 apply(Direction direction) { + return new Vec3(direction == Direction.UP ? 0 : (Direction.Plane.VERTICAL.test(direction) ? 180 : 90), + -horizontalAngleFromDirection(direction), 0); + } + } + + protected static class HorizontalRotationValues implements Function { + @Override + public Vec3 apply(Direction direction) { + return new Vec3(0, -horizontalAngleFromDirection(direction), 0); + } + } + + // this method is from VecHelper: https://github.com/Creators-of-Create/Create/blob/39ef3da5df0fad2054d8b95f15b51b4199479774/src/main/java/com/simibubi/create/foundation/utility/VecHelper.java#L46 + public static Vec3 rotate(Vec3 vec, double deg, Axis axis) { + if (deg == 0) + return vec; + if (vec == Vec3.ZERO) + return vec; + + float angle = (float) (deg / 180f * Math.PI); + double sin = Mth.sin(angle); + double cos = Mth.cos(angle); + double x = vec.x; + double y = vec.y; + double z = vec.z; + + if (axis == Axis.X) + return new Vec3(x, y * cos - z * sin, z * cos + y * sin); + if (axis == Axis.Y) + return new Vec3(x * cos + z * sin, y, z * cos - x * sin); + if (axis == Axis.Z) + return new Vec3(x * cos - y * sin, y * cos + x * sin, z); + return vec; + } }