From 06af9ce8b1eeaebbb5913c8e2f3a15bf1be9a10d Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 24 Jan 2022 20:33:16 +0100 Subject: [PATCH] Migrate the Carpet codebase to Mojang Mappings --- build.gradle | 4 +- gradle.properties | 3 +- src/main/java/carpet/CarpetExtension.java | 15 +- src/main/java/carpet/CarpetServer.java | 24 +- src/main/java/carpet/CarpetSettings.java | 92 +-- .../java/carpet/commands/CounterCommand.java | 44 +- .../java/carpet/commands/DistanceCommand.java | 28 +- .../java/carpet/commands/DrawCommand.java | 175 +++-- .../java/carpet/commands/InfoCommand.java | 31 +- src/main/java/carpet/commands/LogCommand.java | 65 +- .../java/carpet/commands/MobAICommand.java | 26 +- .../carpet/commands/PerimeterInfoCommand.java | 54 +- .../java/carpet/commands/PlayerCommand.java | 171 +++-- .../java/carpet/commands/ProfileCommand.java | 10 +- .../java/carpet/commands/ScriptCommand.java | 258 +++---- .../java/carpet/commands/SpawnCommand.java | 119 ++- .../java/carpet/commands/TestCommand.java | 10 +- .../java/carpet/commands/TickCommand.java | 50 +- .../carpet/fakes/BiomeArrayInterface.java | 8 +- .../carpet/fakes/BlockEntityInterface.java | 2 +- .../carpet/fakes/BlockPredicateInterface.java | 11 +- .../fakes/BlockStateArgumentInterface.java | 4 +- .../carpet/fakes/ChunkGeneratorInterface.java | 2 +- .../carpet/fakes/ChunkHolderInterface.java | 13 +- .../fakes/ChunkLightProviderInterface.java | 4 +- .../fakes/ChunkTicketManagerInterface.java | 10 +- .../carpet/fakes/CoralFeatureInterface.java | 9 +- .../carpet/fakes/IngredientInterface.java | 3 +- .../fakes/InventoryBearerInterface.java | 4 +- .../carpet/fakes/LightStorageInterface.java | 4 +- .../fakes/MinecraftServerInterface.java | 17 +- .../java/carpet/fakes/MobEntityInterface.java | 5 +- .../fakes/PistonBlockEntityInterface.java | 2 +- .../carpet/fakes/PistonBlockInterface.java | 8 +- .../carpet/fakes/PlacedFeatureInterface.java | 4 +- .../carpet/fakes/RecipeManagerInterface.java | 10 +- .../fakes/RedstoneWireBlockInterface.java | 8 +- .../carpet/fakes/ScreenHandlerInterface.java | 14 +- .../fakes/ServerChunkManagerInterface.java | 4 +- .../ServerLightingProviderInterface.java | 11 +- ...rverPlayerInteractionManagerInterface.java | 2 +- .../carpet/fakes/ServerWorldInterface.java | 10 +- .../fakes/SimpleEntityLookupInterface.java | 7 +- .../fakes/SpawnHelperInnerInterface.java | 4 +- .../fakes/StructureFeatureInterface.java | 18 +- .../ThreadedAnvilChunkStorageInterface.java | 5 +- .../carpet/fakes/WorldChunkInterface.java | 6 +- .../java/carpet/fakes/WorldInterface.java | 14 +- .../java/carpet/helpers/BlockRotator.java | 278 +++---- .../carpet/helpers/BlockSaplingHelper.java | 10 +- .../java/carpet/helpers/CustomSpawnLists.java | 18 +- .../helpers/EntityPlayerActionPack.java | 227 +++--- .../java/carpet/helpers/FeatureGenerator.java | 259 +++---- .../java/carpet/helpers/HopperCounter.java | 85 ++- .../java/carpet/helpers/InventoryHelper.java | 14 +- .../carpet/helpers/OptimizedExplosion.java | 238 +++--- .../java/carpet/helpers/ParticleDisplay.java | 41 +- .../carpet/helpers/RedstoneWireTurbo.java | 53 +- .../carpet/helpers/ThrowableSuppression.java | 2 +- src/main/java/carpet/helpers/TickSpeed.java | 21 +- src/main/java/carpet/helpers/Tracer.java | 53 +- .../java/carpet/logging/HUDController.java | 85 ++- src/main/java/carpet/logging/HUDLogger.java | 11 +- src/main/java/carpet/logging/Logger.java | 41 +- .../java/carpet/logging/LoggerRegistry.java | 9 +- .../logHelpers/ExplosionLogHelper.java | 35 +- .../logHelpers/PathfindingVisualizer.java | 14 +- .../logging/logHelpers/TNTLogHelper.java | 12 +- .../logHelpers/TrajectoryLogHelper.java | 25 +- ...actCauldronBlock_stackableSBoxesMixin.java | 32 +- ...tractRecipeScreenHandler_scarpetMixin.java | 12 +- .../ArmorStandEntity_scarpetMarkerMixin.java | 20 +- ...rierBlock_updateSuppressionBlockMixin.java | 42 +- .../mixins/BastionRemnantFeatureMixin.java | 11 +- .../mixins/BiomeArray_getBiomeArrayMixin.java | 6 - ...eEntityShootFireballGoal_extremeMixin.java | 2 +- .../mixins/BlazeEntity_extremeMixin.java | 6 +- .../mixins/BlockEntity_movableBEMixin.java | 8 +- .../mixins/BlockItem_creativeNoClipMixin.java | 28 +- .../mixins/BlockItem_scarpetEventMixin.java | 19 +- ...ightStorage_scarpetChunkCreationMixin.java | 48 +- .../BlockStateArgument_fillUpdatesMixin.java | 20 +- .../BlockStateArgument_scarpetMixin.java | 12 +- ...ingAmethystBlock_movableAmethystMixin.java | 42 +- .../java/carpet/mixins/CarpetBlockMixin.java | 22 +- .../CauldronBlock_stackableSBoxesMixin.java | 11 +- .../mixins/CaveScalerMixin_scarpetMixin.java | 6 +- .../mixins/ChunkGenerator_scarpetMixin.java | 12 +- ...ChunkHolder_scarpetChunkCreationMixin.java | 32 +- ...ghtProvider_scarpetChunkCreationMixin.java | 18 +- src/main/java/carpet/mixins/ChunkMixin.java | 8 +- .../mixins/ChunkRegion_scarpetPlopMixin.java | 8 +- ...cketManager_scarpetChunkCreationMixin.java | 13 +- .../ChunkTicketManager_scarpetMixin.java | 14 +- .../ChunkTicketManager_spawnChunksMixin.java | 30 +- .../mixins/ChunkTicketManager_tickMixin.java | 10 +- .../carpet/mixins/ClientConnectionMixin.java | 8 +- .../mixins/ClientPlayNetworkHandlerMixin.java | 32 +- ...ClientPlayerEntity_clientCommandMixin.java | 12 +- .../java/carpet/mixins/CloneCommandMixin.java | 20 +- .../CommandFunctionManager_tickMixin.java | 4 +- .../carpet/mixins/CommandManagerMixin.java | 20 +- .../java/carpet/mixins/ContainerMixin.java | 44 +- .../java/carpet/mixins/CoralBlockMixin.java | 70 +- .../carpet/mixins/CoralFanBlockMixin.java | 58 +- .../java/carpet/mixins/CoralFeatureMixin.java | 16 +- .../CrashReport_addScarpetAppsMixin.java | 9 +- .../DebugRenderer_scarpetRenderMixin.java | 4 +- .../mixins/DesertPyramidFeatureMixin.java | 7 +- .../java/carpet/mixins/DirectionMixin.java | 12 +- .../mixins/DispenserBlock_cactusMixin.java | 14 +- .../carpet/mixins/DispenserBlock_qcMixin.java | 14 +- .../carpet/mixins/EndCityFeatureMixin.java | 7 +- ...atewayBlockEntity_creativeNoClipMixin.java | 8 +- src/main/java/carpet/mixins/EntityMixin.java | 20 +- .../EntityNavigation_pathfindingMixin.java | 40 +- .../EntityTrackerEntry_leashFixMixin.java | 18 +- .../mixins/Entity_scarpetEventsMixin.java | 32 +- .../mixins/ExperienceOrbEntityMixin.java | 36 +- .../java/carpet/mixins/ExplosionAccessor.java | 16 +- .../java/carpet/mixins/ExplosionMixin.java | 56 +- .../mixins/Explosion_scarpetEventMixin.java | 54 +- .../mixins/FallingBlockEntityMixin.java | 20 +- ...FallingBlockEntity_scarpetEventsMixin.java | 10 +- .../java/carpet/mixins/FillCommandMixin.java | 18 +- .../mixins/FireworkEntity_extremeMixin.java | 4 +- .../FishingBobberEntity_extremeMixin.java | 6 +- .../mixins/FlatChunkGeneratorMixin.java | 72 +- ...owableFluid_liquidDamageDisabledMixin.java | 20 +- .../FluidBlock_renewableBlackstoneMixin.java | 38 +- .../FluidBlock_renewableDeepslateMixin.java | 26 +- .../ForceLoadCommand_forceLoadLimitMixin.java | 6 +- .../carpet/mixins/GuardianEntityMixin.java | 42 +- .../carpet/mixins/HopperBlockEntityMixin.java | 40 +- .../mixins/HopperBlock_cactusMixin.java | 16 +- .../mixins/HorseBaseEntity_scarpetMixin.java | 14 +- .../java/carpet/mixins/HuskEntityMixin.java | 20 +- .../java/carpet/mixins/InGameHudMixin.java | 18 +- .../carpet/mixins/InfestedBlockMixin.java | 22 +- .../mixins/Ingredient_scarpetMixin.java | 8 +- ...enserBehaviour_extremeBehavioursMixin.java | 4 +- .../java/carpet/mixins/ItemEntityMixin.java | 60 +- .../mixins/ItemScatterer_extremeMixin.java | 6 +- .../mixins/ItemUsageContext_cactusMixin.java | 16 +- .../LavaFluid_renewableDeepslateMixin.java | 28 +- .../LevelPropagator_resetChunkInterface.java | 9 +- ...ightStorage_scarpetChunkCreationMixin.java | 45 +- ...ingProvider_scarpetChunkCreationMixin.java | 26 +- .../java/carpet/mixins/LivingEntityMixin.java | 16 +- .../mixins/LivingEntity_creativeFlyMixin.java | 26 +- .../LivingEntity_maxCollisionsMixin.java | 38 +- .../LivingEntity_scarpetEventsMixin.java | 28 +- .../carpet/mixins/MinecraftClientMixin.java | 14 +- .../MinecraftClient_pausedShakeMixin.java | 8 +- .../mixins/MinecraftServer_coreMixin.java | 18 +- ...MinecraftServer_pingPlayerSampleLimit.java | 2 +- .../mixins/MinecraftServer_scarpetMixin.java | 52 +- .../MinecraftServer_tickspeedMixin.java | 122 +-- ...Server_updateSuppressionCrashFixMixin.java | 18 +- .../java/carpet/mixins/MobEntityMixin.java | 12 +- .../carpet/mixins/MobEntity_extremeMixin.java | 6 +- .../NoiseChunkGenerator_husksSpawnMixin.java | 39 +- .../NoiseColumnSamplerMixin_scarpetMixin.java | 190 ++--- .../mixins/PerfCommand_permissionMixin.java | 10 +- .../mixins/PickaxeItem_missingToolsMixin.java | 26 +- ...onBlockEntityRenderer_movableBEMixin.java} | 36 +- ... => PistonBlockEntity_movableBEMixin.java} | 86 +-- ...PistonBlockEntity_playerHandlingMixin.java | 56 +- ...n.java => PistonBlock_movableBEMixin.java} | 72 +- .../carpet/mixins/PistonBlock_qcMixin.java | 16 +- .../mixins/PistonBlock_rotatorBlockMixin.java | 16 +- .../PistonHandler_customStickyMixin.java | 122 +-- .../mixins/PistonHandler_pushLimitMixin.java | 6 +- .../mixins/PlacedFeature_scarpetMixin.java | 4 +- .../mixins/PlayerActionC2SPacketMixin.java | 10 +- .../PlayerEntityMixin_portalDelayMixin.java | 10 +- .../PlayerEntity_antiCheatDisabled.java | 22 +- .../PlayerEntity_creativeNoClipMixin.java | 28 +- .../mixins/PlayerEntity_fakePlayersMixin.java | 10 +- .../mixins/PlayerEntity_parrotMixin.java | 66 +- .../PlayerEntity_scarpetEventsMixin.java | 46 +- .../PlayerEntity_xpNoCooldownMixin.java | 12 +- .../PlayerInventory_scarpetEventMixin.java | 31 +- .../PlayerListHeaderS2CPacketMixin.java | 10 +- .../carpet/mixins/PlayerListHudMixin.java | 10 +- .../mixins/PlayerManager_coreMixin.java | 12 +- .../PlayerManager_fakePlayersMixin.java | 22 +- .../PlayerManager_scarpetEventsMixin.java | 19 +- .../mixins/PointOfInterest_scarpetMixin.java | 6 +- .../PoweredRailBlock_powerLimitMixin.java | 4 +- .../carpet/mixins/ProjectileEntityMixin.java | 30 +- .../mixins/ProjectileEntity_extremeMixin.java | 6 +- .../mixins/Projectile_extremeMixin.java | 6 +- .../mixins/RecipeManager_scarpetMixin.java | 18 +- .../carpet/mixins/RedstoneWireBlockMixin.java | 67 +- .../mixins/ReloadCommand_reloadAppsMixin.java | 8 +- .../RenderTickCounter_tickSpeedMixin.java | 10 +- .../java/carpet/mixins/SaplingBlockMixin.java | 22 +- .../ScoreboardObjective_scarpetMixin.java | 10 +- .../mixins/Scoreboard_scarpetMixin.java | 10 +- .../ScreenHandlerSubclasses_scarpetMixin.java | 24 +- .../mixins/ScreenHandler_scarpetMixin.java | 54 +- .../ScreenHandler_stackableSBoxesMixin.java | 18 +- .../mixins/ServerChunkManagerMixin.java | 44 +- .../mixins/ServerChunkManager_tickMixin.java | 32 +- .../ServerEntityManager_scarpetMixin.java | 18 +- ...ingProvider_scarpetChunkCreationMixin.java | 59 +- .../ServerLightingProvider_scarpetMixin.java | 38 +- .../mixins/ServerMetadata_motdMixin.java | 12 +- .../mixins/ServerPlayNetworkHandlerMixin.java | 22 +- ...NetworkHandler_antiCheatDisabledMixin.java | 32 +- .../ServerPlayNetworkHandler_coreMixin.java | 16 +- ...etworkHandler_interactionUpdatesMixin.java | 46 +- ...PlayNetworkHandler_scarpetEventsMixin.java | 172 ++--- .../ServerPlayNetworkHandler_tickMixin.java | 36 +- .../mixins/ServerPlayerEntityMixin.java | 10 +- .../ServerPlayerEntity_scarpetEventMixin.java | 96 +-- ...Entity_updateSuppressionCrashFixMixin.java | 28 +- ...ayerInteractionManager_antiCheatMixin.java | 44 +- ...rPlayerInteractionManager_cactusMixin.java | 26 +- ...InteractionManager_scarpetEventsMixin.java | 58 +- .../mixins/ServerWorld_scarpetMixin.java | 57 +- .../mixins/ServerWorld_spawnChunksMixin.java | 6 +- .../carpet/mixins/ServerWorld_tickMixin.java | 61 +- .../carpet/mixins/SetBlockCommandMixin.java | 16 +- ...kerBoxBlockEntity_creativeNoClipMixin.java | 20 +- .../SimpleEntityLookup_scarpetMixin.java | 18 +- ...etonHorseTrapTriggerGoal_extremeMixin.java | 4 +- ...ightStorage_scarpetChunkCreationMixin.java | 82 +- .../mixins/Slot_stackableSBoxesMixin.java | 14 +- .../mixins/SoundEngineInt_cleanLogsMixin.java | 2 +- .../mixins/SoundSystem_cleanLogsMixin.java | 4 +- .../carpet/mixins/SpawnGroup_spawnMixin.java | 12 +- .../carpet/mixins/SpawnHelperInnerMixin.java | 17 +- .../java/carpet/mixins/SpawnHelperMixin.java | 166 ++--- .../mixins/StatePredicate_scarpetMixin.java | 16 +- ...ructureBlockBlockEntityRenderer_mixin.java | 12 +- ...tureBlockBlockEntity_fillUpdatesMixin.java | 22 +- ...StructureBlockBlockEntity_limitsMixin.java | 12 +- .../carpet/mixins/StructureFeatureMixin.java | 110 ++- .../StructureGeneratorFactory_plopMixin.java | 6 +- .../StructurePiece_scarpetPlopMixin.java | 14 +- .../mixins/Structure_fillUpdatesMixin.java | 28 +- .../carpet/mixins/SummonCommandMixin.java | 44 +- .../mixins/TagPredicate_scarpetMixin.java | 18 +- .../java/carpet/mixins/Team_scarpetMixin.java | 8 +- ...hunkStorage_scarpetChunkCreationMixin.java | 192 ++--- .../ThreadedAnvilChunkStorage_tickMixin.java | 10 +- .../java/carpet/mixins/ThrownEntityMixin.java | 22 +- .../java/carpet/mixins/TntBlockMixin.java | 14 +- .../java/carpet/mixins/TntEntityMixin.java | 64 +- .../TradeOutputSlot_scarpetEventMixin.java | 27 +- .../UpdateStructureBlockC2SPacketMixin.java | 22 +- .../carpet/mixins/VillagerEntity_aiMixin.java | 136 ++-- ...StandingBlockItem_creativeNoClipMixin.java | 30 +- .../mixins/WitherEntity_extremeMixin.java | 6 +- .../mixins/WorldChunkBEList_tickMixin.java | 18 +- .../mixins/WorldChunk_fillUpdatesMixin.java | 24 +- .../mixins/WorldChunk_movableBEMixin.java | 162 ++++ .../mixins/WorldChunk_movableTEMixin.java | 164 ---- .../WorldRenderer_creativeNoClipMixin.java | 10 +- .../mixins/WorldRenderer_fogOffMixin.java | 14 +- .../WorldRenderer_pausedShakeMixin.java | 18 +- .../WorldRenderer_scarpetRenderMixin.java | 26 +- .../carpet/mixins/World_fillUpdatesMixin.java | 18 +- .../mixins/World_getOtherEntitiesLimited.java | 30 +- .../carpet/mixins/World_movableBEMixin.java | 120 +++ .../carpet/mixins/World_movableTEMixin.java | 121 --- .../carpet/mixins/World_scarpetPlopMixin.java | 24 +- .../java/carpet/mixins/World_tickMixin.java | 22 +- .../World_updateSuppressionCrashFixMixin.java | 14 +- .../java/carpet/network/CarpetClient.java | 28 +- .../carpet/network/ClientNetworkHandler.java | 61 +- .../carpet/network/ServerNetworkHandler.java | 126 ++-- .../carpet/patches/CopyProfilerResult.java | 21 +- .../carpet/patches/EntityPlayerMPFake.java | 130 ++-- .../carpet/patches/FakeClientConnection.java | 10 +- .../patches/NetHandlerPlayServerFake.java | 20 +- .../java/carpet/script/CarpetContext.java | 8 +- .../java/carpet/script/CarpetEventServer.java | 409 +++++----- .../java/carpet/script/CarpetExpression.java | 14 +- .../java/carpet/script/CarpetScriptHost.java | 132 ++-- .../carpet/script/CarpetScriptServer.java | 36 +- .../java/carpet/script/EntityEventsGroup.java | 21 +- .../script/annotation/FunctionsTestClass.java | 5 - .../carpet/script/annotation/Locator.java | 11 +- .../script/annotation/OutputConverter.java | 25 +- .../java/carpet/script/annotation/Param.java | 16 +- .../annotation/SimpleTypeConverter.java | 15 +- .../java/carpet/script/api/Auxiliary.java | 438 ++++++----- .../carpet/script/api/BlockIterators.java | 39 +- src/main/java/carpet/script/api/Entities.java | 95 ++- .../java/carpet/script/api/Inventories.java | 173 +++-- .../java/carpet/script/api/Monitoring.java | 23 +- .../java/carpet/script/api/Scoreboards.java | 208 +++--- .../java/carpet/script/api/Threading.java | 6 +- .../java/carpet/script/api/WorldAccess.java | 568 +++++++------- .../carpet/script/argument/BlockArgument.java | 11 +- .../carpet/script/argument/FileArgument.java | 34 +- .../script/argument/Vector3Argument.java | 19 +- .../java/carpet/script/bundled/Module.java | 11 +- .../script/command/CommandArgument.java | 358 +++++---- .../carpet/script/command/CommandToken.java | 7 +- .../exception/CarpetExpressionException.java | 5 +- .../carpet/script/utils/AppStoreManager.java | 25 +- .../java/carpet/script/utils/BiomeInfo.java | 32 +- .../script/utils/EquipmentInventory.java | 43 +- .../carpet/script/utils/InputValidator.java | 10 +- .../carpet/script/utils/ShapeDispatcher.java | 375 +++++----- .../carpet/script/utils/ShapesRenderer.java | 603 ++++++++------- .../script/utils/SnoopyCommandSource.java | 124 +-- .../java/carpet/script/utils/SystemInfo.java | 89 ++- .../java/carpet/script/utils/WorldTools.java | 127 ++-- .../java/carpet/script/value/BlockValue.java | 131 ++-- .../carpet/script/value/BooleanValue.java | 8 +- .../java/carpet/script/value/EntityValue.java | 705 +++++++++--------- .../script/value/FormattedTextValue.java | 38 +- .../carpet/script/value/FrameworkValue.java | 4 +- .../script/value/FunctionAnnotationValue.java | 4 +- .../carpet/script/value/FunctionValue.java | 9 +- .../carpet/script/value/LazyListValue.java | 9 +- .../java/carpet/script/value/ListValue.java | 43 +- .../java/carpet/script/value/MapValue.java | 9 +- .../script/value/NBTSerializableValue.java | 283 ++++--- .../java/carpet/script/value/NullValue.java | 9 +- .../carpet/script/value/NumericValue.java | 20 +- .../java/carpet/script/value/ScreenValue.java | 343 +++++---- .../java/carpet/script/value/StringValue.java | 8 +- .../java/carpet/script/value/ThreadValue.java | 5 +- src/main/java/carpet/script/value/Value.java | 5 +- .../carpet/script/value/ValueConversions.java | 211 +++--- src/main/java/carpet/settings/ParsedRule.java | 10 +- .../java/carpet/settings/SettingsManager.java | 106 +-- src/main/java/carpet/settings/Validator.java | 25 +- src/main/java/carpet/utils/BlockInfo.java | 418 ++++++----- .../java/carpet/utils/CarpetProfiler.java | 76 +- .../java/carpet/utils/DistanceCalculator.java | 39 +- src/main/java/carpet/utils/Messenger.java | 154 ++-- src/main/java/carpet/utils/MobAI.java | 42 +- .../carpet/utils/PerimeterDiagnostics.java | 98 ++- src/main/java/carpet/utils/SpawnChunks.java | 10 +- src/main/java/carpet/utils/SpawnReporter.java | 249 +++---- src/main/java/carpet/utils/Translations.java | 4 +- src/main/java/carpet/utils/WoolTool.java | 83 +-- src/main/resources/carpet.accesswidener | 10 +- src/main/resources/carpet.mixins.json | 10 +- 346 files changed, 8353 insertions(+), 8492 deletions(-) rename src/main/java/carpet/mixins/{PistonBlockEntityRenderer_movableTEMixin.java => PistonBlockEntityRenderer_movableBEMixin.java} (54%) rename src/main/java/carpet/mixins/{PistonBlockEntity_movableTEMixin.java => PistonBlockEntity_movableBEMixin.java} (56%) rename src/main/java/carpet/mixins/{PistonBlock_movableTEMixin.java => PistonBlock_movableBEMixin.java} (58%) create mode 100644 src/main/java/carpet/mixins/WorldChunk_movableBEMixin.java delete mode 100644 src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java create mode 100644 src/main/java/carpet/mixins/World_movableBEMixin.java delete mode 100644 src/main/java/carpet/mixins/World_movableTEMixin.java diff --git a/build.gradle b/build.gradle index 7bbbad4b..82649c87 100644 --- a/build.gradle +++ b/build.gradle @@ -17,11 +17,11 @@ loom { dependencies { // To change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + mappings loom.officialMojangMappings() modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" // Fabric API. This is technically optional, but you probably want it anyway. - // modCompile "net.fabricmc:fabric:${project.fabric_version}" + //modImplementation "net.fabricmc:fabric:${project.fabric_version}" modCompileOnly fabricApi.module("fabric-rendering-v1", project.fabric_version) // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. diff --git a/gradle.properties b/gradle.properties index 4f545e19..b9b05589 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,9 +5,8 @@ org.gradle.jvmargs=-Xmx1G # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html minecraft_version=22w03a - yarn_mappings=22w03a+build.1 loader_version=0.12.12 - fabric_version=0.46.1+1.18 + fabric_version=0.46.2+1.18 # Mod Properties mod_version = 1.4.58 diff --git a/src/main/java/carpet/CarpetExtension.java b/src/main/java/carpet/CarpetExtension.java index c7d30457..f09dd7a8 100644 --- a/src/main/java/carpet/CarpetExtension.java +++ b/src/main/java/carpet/CarpetExtension.java @@ -3,10 +3,9 @@ package carpet; import carpet.script.CarpetExpression; import carpet.settings.SettingsManager; import com.mojang.brigadier.CommandDispatcher; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; - +import net.minecraft.server.level.ServerPlayer; import java.util.Map; public interface CarpetExtension @@ -50,7 +49,7 @@ public interface CarpetExtension * where you should register your commands * */ - default void registerCommands(CommandDispatcher dispatcher) {} + default void registerCommands(CommandDispatcher dispatcher) {} /** * Provide your own custom settings manager managed in the same way as base /carpet @@ -64,18 +63,18 @@ public interface CarpetExtension /** * Event that gets called when a player logs in * - * @param player The {@link ServerPlayerEntity} that logged in + * @param player The {@link ServerPlayer} that logged in * */ - default void onPlayerLoggedIn(ServerPlayerEntity player) {} + default void onPlayerLoggedIn(ServerPlayer player) {} /** * Event that gets called when a player logs out * - * @param player The {@link ServerPlayerEntity} that logged out + * @param player The {@link ServerPlayer} that logged out * */ - default void onPlayerLoggedOut(ServerPlayerEntity player) {} + default void onPlayerLoggedOut(ServerPlayer player) {} /** * Event that gets called when the server closes. diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 88fb81de..8e8ef6af 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -1,5 +1,6 @@ package carpet; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -27,16 +28,19 @@ import carpet.logging.HUDController; import carpet.utils.FabricAPIHooks; import carpet.utils.MobAI; import carpet.utils.SpawnReporter; + +import com.google.common.reflect.ClassPath; +import com.google.common.reflect.ClassPath.ClassInfo; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.DedicatedServerModInitializer; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.server.command.CommandManager; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.command.PerfCommand; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.commands.PerfCommand; +import net.minecraft.server.level.ServerPlayer; public class CarpetServer // static for now - easier to handle all around the code, its one anyways { @@ -45,7 +49,7 @@ public class CarpetServer // static for now - easier to handle all around the co public static final Random rand = new Random(); public static MinecraftServer minecraft_server; - private static CommandDispatcher currentCommandDispatcher; + private static CommandDispatcher currentCommandDispatcher; public static CarpetScriptServer scriptServer; public static SettingsManager settingsManager; public static final List extensions = new ArrayList<>(); @@ -116,10 +120,10 @@ public class CarpetServer // static for now - easier to handle all around the co } @Deprecated - public static void registerCarpetCommands(CommandDispatcher dispatcher) { + public static void registerCarpetCommands(CommandDispatcher dispatcher) { } - public static void registerCarpetCommands(CommandDispatcher dispatcher, CommandManager.RegistrationEnvironment environment) + public static void registerCarpetCommands(CommandDispatcher dispatcher, Commands.CommandSelection environment) { settingsManager.registerCommand(dispatcher); extensions.forEach(e -> { @@ -144,7 +148,7 @@ public class CarpetServer // static for now - easier to handle all around the co extensions.forEach(e -> e.registerCommands(dispatcher)); currentCommandDispatcher = dispatcher; - if (environment != CommandManager.RegistrationEnvironment.DEDICATED) + if (environment != Commands.CommandSelection.DEDICATED) PerfCommand.register(dispatcher); if (FabricLoader.getInstance().isDevelopmentEnvironment()) @@ -152,7 +156,7 @@ public class CarpetServer // static for now - easier to handle all around the co // todo 1.16 - re-registerer apps if that's a reload operation. } - public static void onPlayerLoggedIn(ServerPlayerEntity player) + public static void onPlayerLoggedIn(ServerPlayer player) { ServerNetworkHandler.onPlayerJoin(player); LoggerRegistry.playerConnected(player); @@ -161,7 +165,7 @@ public class CarpetServer // static for now - easier to handle all around the co } - public static void onPlayerLoggedOut(ServerPlayerEntity player) + public static void onPlayerLoggedOut(ServerPlayer player) { ServerNetworkHandler.onPlayerLoggedOut(player); LoggerRegistry.playerDisconnected(player); diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 5fbbc327..47d86a5e 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -8,19 +8,19 @@ import carpet.settings.Validator; import carpet.utils.Translations; import carpet.utils.Messenger; import carpet.utils.SpawnChunks; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.dedicated.DedicatedServer; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; +import net.minecraft.server.ServerInterface; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -55,7 +55,7 @@ public class CarpetSettings public static int updateSuppressionBlockSetting = -1; private static class LanguageValidator extends Validator { - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { if (currentRule.get().equals(newValue) || source == null) { return newValue; @@ -128,8 +128,8 @@ public class CarpetSettings */ private static class CarpetPermissionLevel extends Validator { - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { - if (source == null || source.hasPermissionLevel(4)) + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { + if (source == null || source.hasPermission(4)) return newValue; return null; } @@ -173,7 +173,7 @@ public class CarpetSettings private static class OneHourMaxDelayLimit extends Validator { - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { return (newValue > 0 && newValue <= 72000) ? newValue : null; } @Override @@ -208,7 +208,7 @@ public class CarpetSettings public static class StackableShulkerBoxValidator extends Validator { @Override - public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) + public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { if (newValue.matches("^[0-9]+$")) { int value = Integer.parseInt(newValue); @@ -258,7 +258,7 @@ public class CarpetSettings private static class CheckOptimizedTntEnabledValidator extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { return optimizedTNT || currentRule.defaultValue.equals(newValue) ? newValue : null; } @@ -274,7 +274,7 @@ public class CarpetSettings private static class TNTRandomRangeValidator extends Validator { @Override - public Double validate(ServerCommandSource source, ParsedRule currentRule, Double newValue, String string) { + public Double validate(CommandSourceStack source, ParsedRule currentRule, Double newValue, String string) { return newValue == -1 || newValue >= 0 ? newValue : null; } @@ -290,7 +290,7 @@ public class CarpetSettings private static class TNTAngleValidator extends Validator { @Override - public Double validate(ServerCommandSource source, ParsedRule currentRule, Double newValue, String string) { + public Double validate(CommandSourceStack source, ParsedRule currentRule, Double newValue, String string) { return (newValue >= 0 && newValue < Math.PI * 2) || newValue == -1 ? newValue : null; } @@ -384,7 +384,7 @@ public class CarpetSettings private static class ChainStoneSetting extends Validator { - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { CarpetSettings.doChainStone = !newValue.toLowerCase(Locale.ROOT).equals("false"); CarpetSettings.chainStoneStickToAll = newValue.toLowerCase(Locale.ROOT).equals("stick_to_all"); @@ -481,9 +481,9 @@ public class CarpetSettings public static String commandScript = "true"; private static class ModulePermissionLevel extends Validator { - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { int permissionLevel = SettingsManager.getCommandLevel(newValue); - if (source != null && !source.hasPermissionLevel(permissionLevel)) + if (source != null && !source.hasPermission(permissionLevel)) return null; CarpetSettings.runPermissionLevel = permissionLevel; CarpetServer.settingsManager.notifyPlayersCommandsChanged(); @@ -581,7 +581,7 @@ public class CarpetSettings //public static boolean miningGhostBlockFix = false; private static class PushLimitLimits extends Validator { - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>0 && newValue <= 1024) ? newValue : null; } @Override @@ -606,7 +606,7 @@ public class CarpetSettings public static int railPowerLimit = 9; private static class FillLimitLimits extends Validator { - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>0 && newValue <= 20000000) ? newValue : null; } @Override @@ -676,7 +676,7 @@ public class CarpetSettings private static class ViewDistanceValidator extends Validator { - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { if (currentRule.get().equals(newValue) || source == null) { @@ -689,11 +689,11 @@ public class CarpetSettings } MinecraftServer server = source.getServer(); - if (server.isDedicated()) + if (server.isDedicatedServer()) { - int vd = (newValue >= 2)?newValue:((DedicatedServer) server).getProperties().viewDistance; - if (vd != server.getPlayerManager().getViewDistance()) - server.getPlayerManager().setViewDistance(vd); + int vd = (newValue >= 2)?newValue:((ServerInterface) server).getProperties().viewDistance; + if (vd != server.getPlayerList().getViewDistance()) + server.getPlayerList().setViewDistance(vd); return newValue; } else @@ -718,17 +718,17 @@ public class CarpetSettings public static class ChangeSpawnChunksValidator extends Validator { public static void changeSpawnSize(int size) { - ServerWorld overworld = CarpetServer.minecraft_server.getWorld(World.OVERWORLD); // OW + ServerLevel overworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW if (overworld != null) { ChunkPos centerChunk = new ChunkPos(new BlockPos( - overworld.getLevelProperties().getSpawnX(), - overworld.getLevelProperties().getSpawnY(), - overworld.getLevelProperties().getSpawnZ() + overworld.getLevelData().getXSpawn(), + overworld.getLevelData().getYSpawn(), + overworld.getLevelData().getZSpawn() )); - SpawnChunks.changeSpawnChunks(overworld.getChunkManager(), centerChunk, size); + SpawnChunks.changeSpawnChunks(overworld.getChunkSource(), centerChunk, size); } } - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { if (source == null) return newValue; if (newValue < 0 || newValue > 32) { @@ -741,7 +741,7 @@ public class CarpetSettings return newValue; } if (CarpetServer.minecraft_server == null) return newValue; - ServerWorld currentOverworld = CarpetServer.minecraft_server.getWorld(World.OVERWORLD); // OW + ServerLevel currentOverworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW if (currentOverworld != null) { changeSpawnSize(newValue); @@ -762,15 +762,15 @@ public class CarpetSettings public static class LightBatchValidator extends Validator { public static void applyLightBatchSizes() { - Iterator iterator = CarpetServer.minecraft_server.getWorlds().iterator(); + Iterator iterator = CarpetServer.minecraft_server.getAllLevels().iterator(); while (iterator.hasNext()) { - ServerWorld serverWorld = iterator.next(); - serverWorld.getChunkManager().getLightingProvider().setTaskBatchSize(lightEngineMaxBatchSize); + ServerLevel serverWorld = iterator.next(); + serverWorld.getChunkSource().getLightEngine().setTaskPerBatch(lightEngineMaxBatchSize); } } - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { if (source == null) return newValue; if (newValue < 0) { @@ -893,7 +893,7 @@ public class CarpetSettings public static boolean isCreativeFlying(Entity entity) { // #todo replace after merger to 1.17 - return CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying; + return CarpetSettings.creativeNoClip && entity instanceof Player && (((Player) entity).isCreative()) && ((Player) entity).getAbilities().flying; } @@ -938,7 +938,7 @@ public class CarpetSettings public static class StructureBlockLimitValidator extends Validator { - @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(CommandSourceStack source, ParsedRule currentRule, Integer newValue, String string) { return (newValue >= vanillaStructureBlockLimit) ? newValue : null; } @@ -965,8 +965,8 @@ public class CarpetSettings public static class StructureBlockIgnoredValidator extends Validator { @Override - public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { - Optional ignoredBlock = Registry.BLOCK.getOrEmpty(Identifier.tryParse(newValue)); + public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { + Optional ignoredBlock = Registry.BLOCK.getOptional(ResourceLocation.tryParse(newValue)); if (!ignoredBlock.isPresent()) { Messenger.m(source, "r Unknown block '" + newValue + "'."); return null; @@ -1027,7 +1027,7 @@ public class CarpetSettings private static class updateSuppressionBlockModes extends Validator { @Override - public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { if (!currentRule.get().equals(newValue)) { if (newValue.equalsIgnoreCase("false")) { updateSuppressionBlockSetting = -1; diff --git a/src/main/java/carpet/commands/CounterCommand.java b/src/main/java/carpet/commands/CounterCommand.java index 484a7b4d..59e0cd3d 100644 --- a/src/main/java/carpet/commands/CounterCommand.java +++ b/src/main/java/carpet/commands/CounterCommand.java @@ -5,11 +5,11 @@ import carpet.helpers.HopperCounter; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.command.CommandException; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.command.CommandManager; -import net.minecraft.util.DyeColor; -import net.minecraft.text.BaseText; +import net.minecraft.commands.CommandRuntimeException; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.world.item.DyeColor; /** * Class for the /counter command which allows to use hoppers pointing into wool @@ -20,25 +20,25 @@ public class CounterCommand /** * The method used to register the command and make it available for the players to use. */ - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder literalargumentbuilder = CommandManager.literal("counter").executes((context) + LiteralArgumentBuilder literalargumentbuilder = Commands.literal("counter").executes((context) -> listAllCounters(context.getSource(), false)).requires((player) -> CarpetSettings.hopperCounters); literalargumentbuilder. - then((CommandManager.literal("reset").executes( (p_198489_1_)-> + then((Commands.literal("reset").executes( (p_198489_1_)-> resetCounter(p_198489_1_.getSource(), null)))); for (DyeColor enumDyeColor: DyeColor.values()) { String color = enumDyeColor.toString(); literalargumentbuilder. - then((CommandManager.literal(color).executes( (p_198489_1_)-> displayCounter(p_198489_1_.getSource(), color, false)))); - literalargumentbuilder.then(CommandManager.literal(color). - then(CommandManager.literal("reset").executes((context) -> + then((Commands.literal(color).executes( (p_198489_1_)-> displayCounter(p_198489_1_.getSource(), color, false)))); + literalargumentbuilder.then(Commands.literal(color). + then(Commands.literal("reset").executes((context) -> resetCounter(context.getSource(), color)))); - literalargumentbuilder.then(CommandManager.literal(color). - then(CommandManager.literal("realtime").executes((context) -> + literalargumentbuilder.then(Commands.literal(color). + then(Commands.literal("realtime").executes((context) -> displayCounter(context.getSource(), color, true)))); } dispatcher.register(literalargumentbuilder); @@ -51,14 +51,14 @@ public class CounterCommand * would make it slower than IRL */ - private static int displayCounter(ServerCommandSource source, String color, boolean realtime) + private static int displayCounter(CommandSourceStack source, String color, boolean realtime) { HopperCounter counter = HopperCounter.getCounter(color); - if (counter == null) throw new CommandException(Messenger.s("Unknown wool color: "+color)); + if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color: "+color)); - for (BaseText message: counter.format(source.getServer(), realtime, false)) + for (BaseComponent message: counter.format(source.getServer(), realtime, false)) { - source.sendFeedback(message, false); + source.sendSuccess(message, false); } return 1; } @@ -68,7 +68,7 @@ public class CounterCommand * it will reset all counters. * @param color The counter whose contents we want to reset */ - private static int resetCounter(ServerCommandSource source, String color) + private static int resetCounter(CommandSourceStack source, String color) { if (color == null) { @@ -78,7 +78,7 @@ public class CounterCommand else { HopperCounter counter = HopperCounter.getCounter(color); - if (counter == null) throw new CommandException(Messenger.s("Unknown wool color")); + if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color")); counter.reset(source.getServer()); Messenger.m(source, "w Restarted "+color+" counter"); } @@ -90,11 +90,11 @@ public class CounterCommand * @param realtime Whether or not to display it as in-game time or IRL time, which accounts for less than 20TPS which * would make it slower than IRL */ - private static int listAllCounters(ServerCommandSource source, boolean realtime) + private static int listAllCounters(CommandSourceStack source, boolean realtime) { - for (BaseText message: HopperCounter.formatAll(source.getServer(), realtime)) + for (BaseComponent message: HopperCounter.formatAll(source.getServer(), realtime)) { - source.sendFeedback(message, false); + source.sendSuccess(message, false); } return 1; } diff --git a/src/main/java/carpet/commands/DistanceCommand.java b/src/main/java/carpet/commands/DistanceCommand.java index 77f947e6..0a5b2d23 100644 --- a/src/main/java/carpet/commands/DistanceCommand.java +++ b/src/main/java/carpet/commands/DistanceCommand.java @@ -5,39 +5,39 @@ import carpet.settings.SettingsManager; import carpet.utils.DistanceCalculator; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.command.argument.Vec3ArgumentType; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.coordinates.Vec3Argument; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class DistanceCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder command = literal("distance"). + LiteralArgumentBuilder command = literal("distance"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandDistance)). then(literal("from"). executes( (c) -> DistanceCalculator.setStart(c.getSource(), c.getSource().getPosition())). - then(argument("from", Vec3ArgumentType.vec3()). + then(argument("from", Vec3Argument.vec3()). executes( (c) -> DistanceCalculator.setStart( c.getSource(), - Vec3ArgumentType.getVec3(c, "from"))). + Vec3Argument.getVec3(c, "from"))). then(literal("to"). executes((c) -> DistanceCalculator.distance( c.getSource(), - Vec3ArgumentType.getVec3(c, "from"), + Vec3Argument.getVec3(c, "from"), c.getSource().getPosition())). - then(argument("to", Vec3ArgumentType.vec3()). + then(argument("to", Vec3Argument.vec3()). executes( (c) -> DistanceCalculator.distance( c.getSource(), - Vec3ArgumentType.getVec3(c, "from"), - Vec3ArgumentType.getVec3(c, "to") + Vec3Argument.getVec3(c, "from"), + Vec3Argument.getVec3(c, "to") )))))). then(literal("to"). executes( (c) -> DistanceCalculator.setEnd(c.getSource(), c.getSource().getPosition()) ). - then(argument("to", Vec3ArgumentType.vec3()). - executes( (c) -> DistanceCalculator.setEnd(c.getSource(), Vec3ArgumentType.getVec3(c, "to"))))); + then(argument("to", Vec3Argument.vec3()). + executes( (c) -> DistanceCalculator.setEnd(c.getSource(), Vec3Argument.getVec3(c, "to"))))); dispatcher.register(command); } } diff --git a/src/main/java/carpet/commands/DrawCommand.java b/src/main/java/carpet/commands/DrawCommand.java index db4ac981..b3f01db0 100644 --- a/src/main/java/carpet/commands/DrawCommand.java +++ b/src/main/java/carpet/commands/DrawCommand.java @@ -12,70 +12,69 @@ import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.block.Block; -import net.minecraft.block.pattern.CachedBlockPosition; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.command.argument.BlockPredicateArgumentType; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.command.argument.BlockStateArgumentType; -import net.minecraft.inventory.Inventory; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.MathHelper; - import java.util.List; import java.util.function.Predicate; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.commands.arguments.blocks.BlockPredicateArgument; +import net.minecraft.commands.arguments.blocks.BlockStateArgument; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.Mth; +import net.minecraft.world.Container; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; import java.lang.Math; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class DrawCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder command = literal("draw"). + LiteralArgumentBuilder command = literal("draw"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandDraw)). then(literal("sphere"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(drawShape(c -> DrawCommand.drawSphere(c, false)))))). then(literal("ball"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(drawShape(c -> DrawCommand.drawSphere(c, true)))))). then(literal("diamond"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(drawShape(c -> DrawCommand.drawDiamond(c, true)))))). then(literal("pyramid"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(argument("height",IntegerArgumentType.integer(1)). - then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"up","down"},b)). - then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b)). + then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"up","down"},b)). + then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b)). then(drawShape(c -> DrawCommand.drawPyramid(c, "square", true))))))))). then(literal("cone"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(argument("height",IntegerArgumentType.integer(1)). - then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"up","down"},b)). - then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b)) + then(argument("pointing",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"up","down"},b)). + then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b)) .then(drawShape(c -> DrawCommand.drawPyramid(c, "circle", true))))))))). then(literal("cylinder"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(argument("height",IntegerArgumentType.integer(1)). - then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b)) + then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b)) .then(drawShape(c -> DrawCommand.drawPrism(c, "circle")))))))). then(literal("cuboid"). - then(argument("center", BlockPosArgumentType.blockPos()). + then(argument("center", BlockPosArgument.blockPos()). then(argument("radius", IntegerArgumentType.integer(1)). then(argument("height",IntegerArgumentType.integer(1)). - then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggestMatching(new String[]{"y","x","z"},b)) + then(argument("orientation",StringArgumentType.word()).suggests( (c, b) -> suggest(new String[]{"y","x","z"},b)) .then(drawShape(c -> DrawCommand.drawPrism(c, "square")))))))); dispatcher.register(command); } @@ -83,33 +82,33 @@ public class DrawCommand @FunctionalInterface private interface OptionalBlockSelector { - Integer apply(final CommandContext ctx) throws CommandSyntaxException; + Integer apply(final CommandContext ctx) throws CommandSyntaxException; } @FunctionalInterface private interface ArgumentExtractor { - T apply(final CommandContext ctx, final String argName) throws CommandSyntaxException; + T apply(final CommandContext ctx, final String argName) throws CommandSyntaxException; } - private static RequiredArgumentBuilder + private static RequiredArgumentBuilder drawShape(OptionalBlockSelector drawer) { - return argument("block", BlockStateArgumentType.blockState()). + return argument("block", BlockStateArgument.block()). executes(drawer::apply) .then(literal("replace") - .then(argument("filter", BlockPredicateArgumentType.blockPredicate()) + .then(argument("filter", BlockPredicateArgument.blockPredicate()) .executes(drawer::apply))); } private static class ErrorHandled extends RuntimeException {} - private static T getArg(CommandContext ctx, ArgumentExtractor extract, String hwat) throws CommandSyntaxException + private static T getArg(CommandContext ctx, ArgumentExtractor extract, String hwat) throws CommandSyntaxException { return getArg(ctx, extract, hwat, false); } - private static T getArg(CommandContext ctx, ArgumentExtractor extract, String hwat, boolean optional) throws CommandSyntaxException + private static T getArg(CommandContext ctx, ArgumentExtractor extract, String hwat, boolean optional) throws CommandSyntaxException { T arg = null; try @@ -131,23 +130,23 @@ public class DrawCommand } private static int setBlock( - ServerWorld world, BlockPos.Mutable mbpos, int x, int y, int z, - BlockStateArgument block, Predicate replacement, + ServerLevel world, BlockPos.MutableBlockPos mbpos, int x, int y, int z, + BlockInput block, Predicate replacement, List list ) { mbpos.set(x, y, z); int success=0; - if (replacement == null || replacement.test(new CachedBlockPosition(world, mbpos, true))) + if (replacement == null || replacement.test(new BlockInWorld(world, mbpos, true))) { BlockEntity tileentity = world.getBlockEntity(mbpos); - if (tileentity instanceof Inventory) + if (tileentity instanceof Container) { - ((Inventory) tileentity).clear(); + ((Container) tileentity).clearContent(); } - if (block.setBlockState(world, mbpos, 2)) + if (block.place(world, mbpos, 2)) { - list.add(mbpos.toImmutable()); + list.add(mbpos.immutable()); ++success; } } @@ -155,23 +154,23 @@ public class DrawCommand return success; } - private static int drawSphere(CommandContext ctx, boolean solid) throws CommandSyntaxException + private static int drawSphere(CommandContext ctx, boolean solid) throws CommandSyntaxException { BlockPos pos; int radius; - BlockStateArgument block; - Predicate replacement; + BlockInput block; + Predicate replacement; try { - pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center"); + pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center"); radius = getArg(ctx, IntegerArgumentType::getInteger, "radius"); - block = getArg(ctx, BlockStateArgumentType::getBlockState, "block"); - replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true); + block = getArg(ctx, BlockStateArgument::getBlock, "block"); + replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true); } catch (ErrorHandled ignored) { return 0; } int affected = 0; - ServerWorld world = ctx.getSource().getWorld(); + ServerLevel world = ctx.getSource().getLevel(); double radiusX = radius+0.5; double radiusY = radius+0.5; @@ -185,7 +184,7 @@ public class DrawCommand final int ceilRadiusY = (int) Math.ceil(radiusY); final int ceilRadiusZ = (int) Math.ceil(radiusZ); - BlockPos.Mutable mbpos = pos.mutableCopy(); + BlockPos.MutableBlockPos mbpos = pos.mutable(); List list = Lists.newArrayList(); double nextXn = 0; @@ -244,35 +243,35 @@ public class DrawCommand } if (CarpetSettings.fillUpdates) { - list.forEach(blockpos1 -> world.updateNeighbors(blockpos1, world.getBlockState(blockpos1).getBlock())); + list.forEach(blockpos1 -> world.blockUpdated(blockpos1, world.getBlockState(blockpos1).getBlock())); } Messenger.m(ctx.getSource(), "gi Filled " + affected + " blocks"); return affected; } - private static int drawDiamond(CommandContext ctx, boolean solid) throws CommandSyntaxException + private static int drawDiamond(CommandContext ctx, boolean solid) throws CommandSyntaxException { BlockPos pos; int radius; - BlockStateArgument block; - Predicate replacement; + BlockInput block; + Predicate replacement; try { - pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center"); + pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center"); radius = getArg(ctx, IntegerArgumentType::getInteger, "radius"); - block = getArg(ctx, BlockStateArgumentType::getBlockState, "block"); - replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true); + block = getArg(ctx, BlockStateArgument::getBlock, "block"); + replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true); } catch (ErrorHandled ignored) { return 0; } - ServerCommandSource source = ctx.getSource(); + CommandSourceStack source = ctx.getSource(); int affected=0; - BlockPos.Mutable mbpos = pos.mutableCopy(); + BlockPos.MutableBlockPos mbpos = pos.mutable(); List list = Lists.newArrayList(); - ServerWorld world = source.getWorld(); + ServerLevel world = source.getLevel(); CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); @@ -294,7 +293,7 @@ public class DrawCommand if (CarpetSettings.fillUpdates) { - list.forEach(p -> world.updateNeighbors(p, world.getBlockState(p).getBlock())); + list.forEach(p -> world.blockUpdated(p, world.getBlockState(p).getBlock())); } Messenger.m(source, "gi Filled " + affected + " blocks"); @@ -303,13 +302,13 @@ public class DrawCommand } private static int fillFlat( - ServerWorld world, BlockPos pos, int offset, double dr, boolean rectangle, String orientation, - BlockStateArgument block, Predicate replacement, - List list, BlockPos.Mutable mbpos + ServerLevel world, BlockPos pos, int offset, double dr, boolean rectangle, String orientation, + BlockInput block, Predicate replacement, + List list, BlockPos.MutableBlockPos mbpos ) { int successes=0; - int r = MathHelper.floor(dr); + int r = Mth.floor(dr); double drsq = dr*dr; if (orientation.equalsIgnoreCase("x")) { @@ -347,35 +346,35 @@ public class DrawCommand return 0; } - private static int drawPyramid(CommandContext ctx, String base, boolean solid) throws CommandSyntaxException + private static int drawPyramid(CommandContext ctx, String base, boolean solid) throws CommandSyntaxException { BlockPos pos; double radius; int height; boolean pointup; String orientation; - BlockStateArgument block; - Predicate replacement; + BlockInput block; + Predicate replacement; try { - pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center"); + pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center"); radius = getArg(ctx, IntegerArgumentType::getInteger, "radius")+0.5D; height = getArg(ctx, IntegerArgumentType::getInteger, "height"); pointup = getArg(ctx, StringArgumentType::getString, "pointing").equalsIgnoreCase("up"); orientation = getArg(ctx, StringArgumentType::getString,"orientation"); - block = getArg(ctx, BlockStateArgumentType::getBlockState, "block"); - replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true); + block = getArg(ctx, BlockStateArgument::getBlock, "block"); + replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true); } catch (ErrorHandled ignored) { return 0; } - ServerCommandSource source = ctx.getSource(); + CommandSourceStack source = ctx.getSource(); int affected = 0; - BlockPos.Mutable mbpos = pos.mutableCopy(); + BlockPos.MutableBlockPos mbpos = pos.mutable(); List list = Lists.newArrayList(); - ServerWorld world = source.getWorld(); + ServerLevel world = source.getLevel(); CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); @@ -393,7 +392,7 @@ public class DrawCommand for (BlockPos blockpos1 : list) { Block blokc = world.getBlockState(blockpos1).getBlock(); - world.updateNeighbors(blockpos1, blokc); + world.blockUpdated(blockpos1, blokc); } } @@ -402,32 +401,32 @@ public class DrawCommand return affected; } - private static int drawPrism(CommandContext ctx, String base){ + private static int drawPrism(CommandContext ctx, String base){ BlockPos pos; double radius; int height; String orientation; - BlockStateArgument block; - Predicate replacement; + BlockInput block; + Predicate replacement; try { - pos = getArg(ctx, BlockPosArgumentType::getBlockPos, "center"); + pos = getArg(ctx, BlockPosArgument::getSpawnablePos, "center"); radius = getArg(ctx, IntegerArgumentType::getInteger, "radius")+0.5D; height = getArg(ctx, IntegerArgumentType::getInteger, "height"); orientation = getArg(ctx, StringArgumentType::getString,"orientation"); - block = getArg(ctx, BlockStateArgumentType::getBlockState, "block"); - replacement = getArg(ctx, BlockPredicateArgumentType::getBlockPredicate, "filter", true); + block = getArg(ctx, BlockStateArgument::getBlock, "block"); + replacement = getArg(ctx, BlockPredicateArgument::getBlockPredicate, "filter", true); } catch (ErrorHandled | CommandSyntaxException ignored) { return 0; } - ServerCommandSource source = ctx.getSource(); + CommandSourceStack source = ctx.getSource(); int affected = 0; - BlockPos.Mutable mbpos = pos.mutableCopy(); + BlockPos.MutableBlockPos mbpos = pos.mutable(); List list = Lists.newArrayList(); - ServerWorld world = source.getWorld(); + ServerLevel world = source.getLevel(); CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); @@ -444,7 +443,7 @@ public class DrawCommand for (BlockPos blockpos1 : list) { Block blokc = world.getBlockState(blockpos1).getBlock(); - world.updateNeighbors(blockpos1, blokc); + world.blockUpdated(blockpos1, blokc); } } diff --git a/src/main/java/carpet/commands/InfoCommand.java b/src/main/java/carpet/commands/InfoCommand.java index 706a04e6..924e88e4 100644 --- a/src/main/java/carpet/commands/InfoCommand.java +++ b/src/main/java/carpet/commands/InfoCommand.java @@ -6,42 +6,41 @@ import carpet.utils.BlockInfo; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.text.BaseText; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.util.math.BlockPos; - import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; import static com.mojang.brigadier.arguments.StringArgumentType.getString; import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class InfoCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder command = literal("info"). + LiteralArgumentBuilder command = literal("info"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandInfo)). then(literal("block"). - then(argument("block position", BlockPosArgumentType.blockPos()). + then(argument("block position", BlockPosArgument.blockPos()). executes( (c) -> infoBlock( c.getSource(), - BlockPosArgumentType.getBlockPos(c, "block position"), null)). + BlockPosArgument.getSpawnablePos(c, "block position"), null)). then(literal("grep"). then(argument("regexp",greedyString()). executes( (c) -> infoBlock( c.getSource(), - BlockPosArgumentType.getBlockPos(c, "block position"), + BlockPosArgument.getSpawnablePos(c, "block position"), getString(c, "regexp"))))))); dispatcher.register(command); } - public static void printBlock(List messages, ServerCommandSource source, String grep) + public static void printBlock(List messages, CommandSourceStack source, String grep) { Messenger.m(source, ""); if (grep != null) @@ -50,7 +49,7 @@ public class InfoCommand Messenger.m(source, messages.get(0)); for (int i = 1; i dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder literalargumentbuilder = CommandManager.literal("log"). + LiteralArgumentBuilder literalargumentbuilder = Commands.literal("log"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandLog)). executes((context) -> listLogs(context.getSource())). - then(CommandManager.literal("clear"). - executes( (c) -> unsubFromAll(c.getSource(), c.getSource().getName())). - then(CommandManager.argument("player", StringArgumentType.word()). - suggests( (c, b)-> suggestMatching(c.getSource().getPlayerNames(),b)). + then(Commands.literal("clear"). + executes( (c) -> unsubFromAll(c.getSource(), c.getSource().getTextName())). + then(Commands.argument("player", StringArgumentType.word()). + suggests( (c, b)-> suggest(c.getSource().getOnlinePlayerNames(),b)). executes( (c) -> unsubFromAll(c.getSource(), getString(c, "player"))))); - literalargumentbuilder.then(CommandManager.argument("log name",StringArgumentType.word()). - suggests( (c, b)-> suggestMatching(LoggerRegistry.getLoggerNames(),b)). - executes( (c)-> toggleSubscription(c.getSource(), c.getSource().getName(), getString(c, "log name"))). - then(CommandManager.literal("clear"). + literalargumentbuilder.then(Commands.argument("log name",StringArgumentType.word()). + suggests( (c, b)-> suggest(LoggerRegistry.getLoggerNames(),b)). + executes( (c)-> toggleSubscription(c.getSource(), c.getSource().getTextName(), getString(c, "log name"))). + then(Commands.literal("clear"). executes( (c) -> unsubFromLogger( c.getSource(), - c.getSource().getName(), + c.getSource().getTextName(), getString(c, "log name")))). - then(CommandManager.argument("option", StringArgumentType.string()). - suggests( (c, b) -> suggestMatching( + then(Commands.argument("option", StringArgumentType.string()). + suggests( (c, b) -> suggest( (LoggerRegistry.getLogger(getString(c, "log name"))==null ?new String[]{} :LoggerRegistry.getLogger(getString(c, "log name")).getOptions()), b)). executes( (c) -> subscribePlayer( c.getSource(), - c.getSource().getName(), + c.getSource().getTextName(), getString(c, "log name"), getString(c, "option"))). - then(CommandManager.argument("player", StringArgumentType.word()). - suggests( (c, b) -> suggestMatching(c.getSource().getPlayerNames(),b)). + then(Commands.argument("player", StringArgumentType.word()). + suggests( (c, b) -> suggest(c.getSource().getOnlinePlayerNames(),b)). executes( (c) -> subscribePlayer( c.getSource(), getString(c, "player"), @@ -65,19 +64,19 @@ public class LogCommand dispatcher.register(literalargumentbuilder); } - private static int listLogs(ServerCommandSource source) + private static int listLogs(CommandSourceStack source) { - PlayerEntity player; + Player player; try { - player = source.getPlayer(); + player = source.getPlayerOrException(); } catch (CommandSyntaxException e) { Messenger.m(source, "For players only"); return 0; } - Map subs = LoggerRegistry.getPlayerSubscriptions(source.getName()); + Map subs = LoggerRegistry.getPlayerSubscriptions(source.getTextName()); if (subs == null) { subs = new HashMap<>(); @@ -132,9 +131,9 @@ public class LogCommand } return 1; } - private static int unsubFromAll(ServerCommandSource source, String player_name) + private static int unsubFromAll(CommandSourceStack source, String player_name) { - PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); + Player player = source.getServer().getPlayerList().getPlayerByName(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -147,9 +146,9 @@ public class LogCommand Messenger.m(source, "gi Unsubscribed from all logs"); return 1; } - private static int unsubFromLogger(ServerCommandSource source, String player_name, String logname) + private static int unsubFromLogger(CommandSourceStack source, String player_name, String logname) { - PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); + Player player = source.getServer().getPlayerList().getPlayerByName(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -165,9 +164,9 @@ public class LogCommand return 1; } - private static int toggleSubscription(ServerCommandSource source, String player_name, String logName) + private static int toggleSubscription(CommandSourceStack source, String player_name, String logName) { - PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); + Player player = source.getServer().getPlayerList().getPlayerByName(player_name); if (player == null) { Messenger.m(source, "r No player specified"); @@ -189,9 +188,9 @@ public class LogCommand } return 1; } - private static int subscribePlayer(ServerCommandSource source, String player_name, String logname, String option) + private static int subscribePlayer(CommandSourceStack source, String player_name, String logname, String option) { - PlayerEntity player = source.getServer().getPlayerManager().getPlayer(player_name); + Player player = source.getServer().getPlayerList().getPlayerByName(player_name); if (player == null) { Messenger.m(source, "r No player specified"); diff --git a/src/main/java/carpet/commands/MobAICommand.java b/src/main/java/carpet/commands/MobAICommand.java index 865c62b3..92fb224b 100644 --- a/src/main/java/carpet/commands/MobAICommand.java +++ b/src/main/java/carpet/commands/MobAICommand.java @@ -6,34 +6,34 @@ import carpet.utils.MobAI; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.command.argument.EntitySummonArgumentType; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.registry.Registry; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.EntitySummonArgument; +import net.minecraft.core.Registry; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class MobAICommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder command = literal("track"). + LiteralArgumentBuilder command = literal("track"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandTrackAI)). - then(argument("entity type", EntitySummonArgumentType.entitySummon()). + then(argument("entity type", EntitySummonArgument.id()). - suggests( (c, b) -> suggestMatching(MobAI.availbleTypes(), b)). + suggests( (c, b) -> suggest(MobAI.availbleTypes(), b)). then(literal("clear").executes( (c) -> { - MobAI.clearTracking(Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type"))); + MobAI.clearTracking(Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type"))); return 1; } )). then(argument("aspect", StringArgumentType.word()). - suggests( (c, b) -> suggestMatching(MobAI.availableFor(Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type"))),b)). + suggests( (c, b) -> suggest(MobAI.availableFor(Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type"))),b)). executes( (c) -> { MobAI.startTracking( - Registry.ENTITY_TYPE.get(EntitySummonArgumentType.getEntitySummon(c, "entity type")), + Registry.ENTITY_TYPE.get(EntitySummonArgument.getSummonableEntity(c, "entity type")), MobAI.TrackingType.byName(StringArgumentType.getString(c, "aspect")) ); return 1; diff --git a/src/main/java/carpet/commands/PerimeterInfoCommand.java b/src/main/java/carpet/commands/PerimeterInfoCommand.java index 619fdf8d..715d7a2f 100644 --- a/src/main/java/carpet/commands/PerimeterInfoCommand.java +++ b/src/main/java/carpet/commands/PerimeterInfoCommand.java @@ -6,64 +6,64 @@ import carpet.utils.Messenger; import carpet.utils.PerimeterDiagnostics; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.command.suggestion.SuggestionProviders; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.command.argument.EntitySummonArgumentType; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.EntitySummonArgument; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.commands.synchronization.SuggestionProviders; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class PerimeterInfoCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder command = literal("perimeterinfo"). + LiteralArgumentBuilder command = literal("perimeterinfo"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandPerimeterInfo)). executes( (c) -> perimeterDiagnose( c.getSource(), new BlockPos(c.getSource().getPosition()), null)). - then(argument("center position", BlockPosArgumentType.blockPos()). + then(argument("center position", BlockPosArgument.blockPos()). executes( (c) -> perimeterDiagnose( c.getSource(), - BlockPosArgumentType.getBlockPos(c, "center position"), + BlockPosArgument.getSpawnablePos(c, "center position"), null)). - then(argument("mob",EntitySummonArgumentType.entitySummon()). + then(argument("mob",EntitySummonArgument.id()). suggests(SuggestionProviders.SUMMONABLE_ENTITIES). executes( (c) -> perimeterDiagnose( c.getSource(), - BlockPosArgumentType.getBlockPos(c, "center position"), - EntitySummonArgumentType.getEntitySummon(c, "mob").toString() + BlockPosArgument.getSpawnablePos(c, "center position"), + EntitySummonArgument.getSummonableEntity(c, "mob").toString() )))); dispatcher.register(command); } - private static int perimeterDiagnose(ServerCommandSource source, BlockPos pos, String mobId) + private static int perimeterDiagnose(CommandSourceStack source, BlockPos pos, String mobId) { - NbtCompound nbttagcompound = new NbtCompound(); - MobEntity entityliving = null; + CompoundTag nbttagcompound = new CompoundTag(); + Mob entityliving = null; if (mobId != null) { nbttagcompound.putString("id", mobId); - Entity baseEntity = EntityType.loadEntityWithPassengers(nbttagcompound, source.getWorld(), (entity_1x) -> { - entity_1x.refreshPositionAndAngles(new BlockPos(pos.getX(), source.getWorld().getBottomY()-10, pos.getZ()), entity_1x.getYaw(), entity_1x. getPitch()); - return !source.getWorld().tryLoadEntity(entity_1x) ? null : entity_1x; + Entity baseEntity = EntityType.loadEntityRecursive(nbttagcompound, source.getLevel(), (entity_1x) -> { + entity_1x.moveTo(new BlockPos(pos.getX(), source.getLevel().getMinBuildHeight()-10, pos.getZ()), entity_1x.getYRot(), entity_1x. getXRot()); + return !source.getLevel().addWithUUID(entity_1x) ? null : entity_1x; }); - if (!(baseEntity instanceof MobEntity)) + if (!(baseEntity instanceof Mob)) { Messenger.m(source, "r /perimeterinfo requires a mob entity to test agains."); if (baseEntity != null) baseEntity.discard(); return 0; } - entityliving = (MobEntity) baseEntity; + entityliving = (Mob) baseEntity; } - PerimeterDiagnostics.Result res = PerimeterDiagnostics.countSpots(source.getWorld(), pos, entityliving); + PerimeterDiagnostics.Result res = PerimeterDiagnostics.countSpots(source.getLevel(), pos, entityliving); Messenger.m(source, "w Spawning spaces around ",Messenger.tp("c",pos), "w :"); Messenger.m(source, "w potential in-liquid: ","wb "+res.liquid); diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index b4255503..14bdcc49 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -15,46 +15,45 @@ import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.DimensionArgumentType; -import net.minecraft.command.argument.RotationArgumentType; -import net.minecraft.command.argument.Vec3ArgumentType; -import net.minecraft.server.PlayerManager; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.DimensionArgument; +import net.minecraft.commands.arguments.coordinates.RotationArgument; +import net.minecraft.commands.arguments.coordinates.Vec3Argument; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.GameMode; -import net.minecraft.world.World; - +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class PlayerCommand { // TODO: allow any order like execute - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - final String[] gamemodeStrings = Arrays.stream(GameMode.values()) - .map(GameMode::getName) + final String[] gamemodeStrings = Arrays.stream(GameType.values()) + .map(GameType::getName) .collect(Collectors.toList()) .toArray(new String[]{}); - LiteralArgumentBuilder literalargumentbuilder = literal("player") + LiteralArgumentBuilder literalargumentbuilder = literal("player") .requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandPlayer)) .then(argument("player", StringArgumentType.word()) - .suggests( (c, b) -> suggestMatching(getPlayers(c.getSource()), b)) + .suggests( (c, b) -> suggest(getPlayers(c.getSource()), b)) .then(literal("stop").executes(PlayerCommand::stop)) .then(makeActionCommand("use", EntityPlayerActionPack.ActionType.USE)) .then(makeActionCommand("jump", EntityPlayerActionPack.ActionType.JUMP)) @@ -83,30 +82,30 @@ public class PlayerCommand .then(literal("west").executes(manipulation(ap -> ap.look(Direction.WEST)))) .then(literal("up").executes(manipulation(ap -> ap.look(Direction.UP)))) .then(literal("down").executes(manipulation(ap -> ap.look(Direction.DOWN)))) - .then(literal("at").then(argument("position", Vec3ArgumentType.vec3()).executes(PlayerCommand::lookAt))) - .then(argument("direction", RotationArgumentType.rotation()) - .executes(c -> manipulate(c, ap -> ap.look(RotationArgumentType.getRotation(c, "direction").toAbsoluteRotation(c.getSource()))))) + .then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::lookAt))) + .then(argument("direction", RotationArgument.rotation()) + .executes(c -> manipulate(c, ap -> ap.look(RotationArgument.getRotation(c, "direction").getRotation(c.getSource()))))) ).then(literal("turn") .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(-90, 0)))) .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(90, 0)))) .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(180, 0)))) - .then(argument("rotation", RotationArgumentType.rotation()) - .executes(c -> manipulate(c, ap -> ap.turn(RotationArgumentType.getRotation(c, "rotation").toAbsoluteRotation(c.getSource()))))) + .then(argument("rotation", RotationArgument.rotation()) + .executes(c -> manipulate(c, ap -> ap.turn(RotationArgument.getRotation(c, "rotation").getRotation(c.getSource()))))) ).then(literal("move").executes(c -> manipulate(c, EntityPlayerActionPack::stopMovement)) .then(literal("forward").executes(c -> manipulate(c, ap -> ap.setForward(1)))) .then(literal("backward").executes(c -> manipulate(c, ap -> ap.setForward(-1)))) .then(literal("left").executes(c -> manipulate(c, ap -> ap.setStrafing(1)))) .then(literal("right").executes(c -> manipulate(c, ap -> ap.setStrafing(-1)))) ).then(literal("spawn").executes(PlayerCommand::spawn) - .then(literal("in").requires((player) -> player.hasPermissionLevel(2)) + .then(literal("in").requires((player) -> player.hasPermission(2)) .then(argument("gamemode", StringArgumentType.word()) - .suggests( (c, b) -> suggestMatching(gamemodeStrings, b)) + .suggests( (c, b) -> suggest(gamemodeStrings, b)) .executes(PlayerCommand::spawn))) - .then(literal("at").then(argument("position", Vec3ArgumentType.vec3()).executes(PlayerCommand::spawn) - .then(literal("facing").then(argument("direction", RotationArgumentType.rotation()).executes(PlayerCommand::spawn) - .then(literal("in").then(argument("dimension", DimensionArgumentType.dimension()).executes(PlayerCommand::spawn) - .then(literal("in").requires((player) -> player.hasPermissionLevel(2)) - .then(argument("gamemode", StringArgumentType.word()).suggests( (c, b) -> suggestMatching(gamemodeStrings, b)) + .then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::spawn) + .then(literal("facing").then(argument("direction", RotationArgument.rotation()).executes(PlayerCommand::spawn) + .then(literal("in").then(argument("dimension", DimensionArgument.dimension()).executes(PlayerCommand::spawn) + .then(literal("in").requires((player) -> player.hasPermission(2)) + .then(argument("gamemode", StringArgumentType.word()).suggests( (c, b) -> suggest(gamemodeStrings, b)) .executes(PlayerCommand::spawn) ))) ))) @@ -116,7 +115,7 @@ public class PlayerCommand dispatcher.register(literalargumentbuilder); } - private static LiteralArgumentBuilder makeActionCommand(String actionName, EntityPlayerActionPack.ActionType type) + private static LiteralArgumentBuilder makeActionCommand(String actionName, EntityPlayerActionPack.ActionType type) { return literal(actionName) .executes(c -> action(c, type, EntityPlayerActionPack.Action.once())) @@ -126,7 +125,7 @@ public class PlayerCommand .executes(c -> action(c, type, EntityPlayerActionPack.Action.interval(IntegerArgumentType.getInteger(c, "ticks")))))); } - private static LiteralArgumentBuilder makeDropCommand(String actionName, boolean dropAll) + private static LiteralArgumentBuilder makeDropCommand(String actionName, boolean dropAll) { return literal(actionName) .then(literal("all").executes(c ->manipulate(c, ap -> ap.drop(-2,dropAll)))) @@ -139,39 +138,39 @@ public class PlayerCommand )))); } - private static Collection getPlayers(ServerCommandSource source) + private static Collection getPlayers(CommandSourceStack source) { Set players = Sets.newLinkedHashSet(Arrays.asList("Steve", "Alex")); - players.addAll(source.getPlayerNames()); + players.addAll(source.getOnlinePlayerNames()); return players; } - private static ServerPlayerEntity getPlayer(CommandContext context) + private static ServerPlayer getPlayer(CommandContext context) { String playerName = StringArgumentType.getString(context, "player"); MinecraftServer server = context.getSource().getServer(); - return server.getPlayerManager().getPlayer(playerName); + return server.getPlayerList().getPlayerByName(playerName); } - private static boolean cantManipulate(CommandContext context) + private static boolean cantManipulate(CommandContext context) { - PlayerEntity player = getPlayer(context); + Player player = getPlayer(context); if (player == null) { Messenger.m(context.getSource(), "r Can only manipulate existing players"); return true; } - PlayerEntity sendingPlayer; + Player sendingPlayer; try { - sendingPlayer = context.getSource().getPlayer(); + sendingPlayer = context.getSource().getPlayerOrException(); } catch (CommandSyntaxException e) { return false; } - if (!context.getSource().getServer().getPlayerManager().isOperator(sendingPlayer.getGameProfile())) + if (!context.getSource().getServer().getPlayerList().isOp(sendingPlayer.getGameProfile())) { if (sendingPlayer != player && !(player instanceof EntityPlayerMPFake)) { @@ -182,27 +181,27 @@ public class PlayerCommand return false; } - private static boolean cantReMove(CommandContext context) + private static boolean cantReMove(CommandContext context) { if (cantManipulate(context)) return true; - PlayerEntity player = getPlayer(context); + Player player = getPlayer(context); if (player instanceof EntityPlayerMPFake) return false; Messenger.m(context.getSource(), "r Only fake players can be moved or killed"); return true; } - private static boolean cantSpawn(CommandContext context) + private static boolean cantSpawn(CommandContext context) { String playerName = StringArgumentType.getString(context, "player"); MinecraftServer server = context.getSource().getServer(); - PlayerManager manager = server.getPlayerManager(); - PlayerEntity player = manager.getPlayer(playerName); + PlayerList manager = server.getPlayerList(); + Player player = manager.getPlayerByName(playerName); if (player != null) { Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is already logged on"); return true; } - GameProfile profile = server.getUserCache().findByName(playerName).orElse(null); + GameProfile profile = server.getProfileCache().get(playerName).orElse(null); if (profile == null) { if (!CarpetSettings.allowSpawningOfflinePlayers) @@ -211,15 +210,15 @@ public class PlayerCommand "Banned players can only be summoned in Singleplayer and in servers in off-line mode."); return true; } else { - profile = new GameProfile(PlayerEntity.getOfflinePlayerUuid(playerName), playerName); + profile = new GameProfile(Player.createPlayerUUID(playerName), playerName); } } - if (manager.getUserBanList().contains(profile)) + if (manager.getBans().isBanned(profile)) { Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is banned on this server"); return true; } - if (manager.isWhitelistEnabled() && manager.isWhitelisted(profile) && !context.getSource().hasPermissionLevel(2)) + if (manager.isUsingWhitelist() && manager.isWhiteListed(profile) && !context.getSource().hasPermission(2)) { Messenger.m(context.getSource(), "r Whitelisted players can only be spawned by operators"); return true; @@ -227,18 +226,18 @@ public class PlayerCommand return false; } - private static int kill(CommandContext context) + private static int kill(CommandContext context) { if (cantReMove(context)) return 0; getPlayer(context).kill(); return 1; } - private static int lookAt(CommandContext context) + private static int lookAt(CommandContext context) { return manipulate(context, ap -> { //try { - ap.lookAt(Vec3ArgumentType.getVec3(context, "position")); + ap.lookAt(Vec3Argument.getVec3(context, "position")); //} catch (CommandSyntaxException ignored) {} }); } @@ -261,45 +260,45 @@ public class PlayerCommand } } - private static int spawn(CommandContext context) throws CommandSyntaxException + private static int spawn(CommandContext context) throws CommandSyntaxException { if (cantSpawn(context)) return 0; - ServerCommandSource source = context.getSource(); - Vec3d pos = tryGetArg( - () -> Vec3ArgumentType.getVec3(context, "position"), + CommandSourceStack source = context.getSource(); + Vec3 pos = tryGetArg( + () -> Vec3Argument.getVec3(context, "position"), source::getPosition ); - Vec2f facing = tryGetArg( - () -> RotationArgumentType.getRotation(context, "direction").toAbsoluteRotation(context.getSource()), + Vec2 facing = tryGetArg( + () -> RotationArgument.getRotation(context, "direction").getRotation(context.getSource()), source::getRotation ); - RegistryKey dimType = tryGetArg( - () -> DimensionArgumentType.getDimensionArgument(context, "dimension").getRegistryKey(), - () -> source.getWorld().getRegistryKey() // dimension.getType() + ResourceKey dimType = tryGetArg( + () -> DimensionArgument.getDimension(context, "dimension").dimension(), + () -> source.getLevel().dimension() // dimension.getType() ); - GameMode mode = GameMode.CREATIVE; + GameType mode = GameType.CREATIVE; boolean flying = false; try { - ServerPlayerEntity player = context.getSource().getPlayer(); - mode = player.interactionManager.getGameMode(); + ServerPlayer player = context.getSource().getPlayerOrException(); + mode = player.gameMode.getGameModeForPlayer(); flying = player.getAbilities().flying; } catch (CommandSyntaxException ignored) {} try { String opGameMode = StringArgumentType.getString(context, "gamemode"); - mode = GameMode.byName(opGameMode, null); + mode = GameType.byName(opGameMode, null); if(mode == null) { Messenger.m(context.getSource(), "rb Invalid game mode: "+opGameMode+"."); return 0; } } catch (IllegalArgumentException ignored) {} - if(mode == GameMode.SPECTATOR) + if(mode == GameType.SPECTATOR) { // Force override flying to true for spectator players, or they will fell out of the world. flying = true; - } else if(mode.isSurvivalLike()){ + } else if(mode.isSurvival()){ // Force override flying to false for survival-like players, or they will fly too flying = false; } @@ -311,12 +310,12 @@ public class PlayerCommand } MinecraftServer server = source.getServer(); - if (!World.isValid(new BlockPos(pos.x, pos.y, pos.z))) + if (!Level.isInSpawnableBounds(new BlockPos(pos.x, pos.y, pos.z))) { Messenger.m(context.getSource(), "rb Player "+playerName+" cannot be placed outside of the world"); return 0; } - PlayerEntity player = EntityPlayerMPFake.createFake(playerName, server, pos.x, pos.y, pos.z, facing.y, facing.x, dimType, mode, flying); + Player player = EntityPlayerMPFake.createFake(playerName, server, pos.x, pos.y, pos.z, facing.y, facing.x, dimType, mode, flying); if (player == null) { Messenger.m(context.getSource(), "rb Player " + StringArgumentType.getString(context, "player") + " doesn't exist " + @@ -328,47 +327,47 @@ public class PlayerCommand private static int maxPlayerLength(MinecraftServer server) { - return server.getServerPort() >= 0 ? 16 : 40; + return server.getPort() >= 0 ? 16 : 40; } - private static int stop(CommandContext context) + private static int stop(CommandContext context) { if (cantManipulate(context)) return 0; - ServerPlayerEntity player = getPlayer(context); + ServerPlayer player = getPlayer(context); ((ServerPlayerEntityInterface) player).getActionPack().stopAll(); return 1; } - private static int manipulate(CommandContext context, Consumer action) + private static int manipulate(CommandContext context, Consumer action) { if (cantManipulate(context)) return 0; - ServerPlayerEntity player = getPlayer(context); + ServerPlayer player = getPlayer(context); action.accept(((ServerPlayerEntityInterface) player).getActionPack()); return 1; } - private static Command manipulation(Consumer action) + private static Command manipulation(Consumer action) { return c -> manipulate(c, action); } - private static int action(CommandContext context, EntityPlayerActionPack.ActionType type, EntityPlayerActionPack.Action action) + private static int action(CommandContext context, EntityPlayerActionPack.ActionType type, EntityPlayerActionPack.Action action) { return manipulate(context, ap -> ap.start(type, action)); } - private static int shadow(CommandContext context) + private static int shadow(CommandContext context) { - ServerPlayerEntity player = getPlayer(context); + ServerPlayer player = getPlayer(context); if (player instanceof EntityPlayerMPFake) { Messenger.m(context.getSource(), "r Cannot shadow fake players"); return 0; } - ServerPlayerEntity sendingPlayer = null; + ServerPlayer sendingPlayer = null; try { - sendingPlayer = context.getSource().getPlayer(); + sendingPlayer = context.getSource().getPlayerOrException(); } catch (CommandSyntaxException ignored) { } diff --git a/src/main/java/carpet/commands/ProfileCommand.java b/src/main/java/carpet/commands/ProfileCommand.java index 6a4dc2f4..2eb2ffa2 100644 --- a/src/main/java/carpet/commands/ProfileCommand.java +++ b/src/main/java/carpet/commands/ProfileCommand.java @@ -4,20 +4,20 @@ import carpet.CarpetSettings; import carpet.settings.SettingsManager; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; import static carpet.commands.TickCommand.healthEntities; import static carpet.commands.TickCommand.healthReport; import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class ProfileCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder literalargumentbuilder = literal("profile"). + LiteralArgumentBuilder literalargumentbuilder = literal("profile"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandProfile)). executes( (c) -> healthReport(c.getSource(), 100)). then(literal("health"). diff --git a/src/main/java/carpet/commands/ScriptCommand.java b/src/main/java/carpet/commands/ScriptCommand.java index 9fc31314..66a265ba 100644 --- a/src/main/java/carpet/commands/ScriptCommand.java +++ b/src/main/java/carpet/commands/ScriptCommand.java @@ -23,18 +23,6 @@ import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import net.minecraft.block.Block; -import net.minecraft.block.pattern.CachedBlockPosition; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.command.argument.BlockPredicateArgumentType; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.command.argument.BlockStateArgumentType; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.Clearable; -import net.minecraft.util.math.BlockPos; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockBox; import org.apache.commons.lang3.StringUtils; import java.io.IOException; @@ -49,10 +37,22 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.commands.arguments.blocks.BlockPredicateArgument; +import net.minecraft.commands.arguments.blocks.BlockStateArgument; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.Clearable; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; +import net.minecraft.world.level.levelgen.structure.BoundingBox; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class ScriptCommand { @@ -86,7 +86,7 @@ public class ScriptCommand } private static CompletableFuture suggestCode( - CommandContext context, + CommandContext context, SuggestionsBuilder suggestionsBuilder ) throws CommandSyntaxException { @@ -112,7 +112,7 @@ public class ScriptCommand * variable. */ private static CompletableFuture suggestDownloadableApps( - CommandContext context, + CommandContext context, SuggestionsBuilder suggestionsBuilder ) throws CommandSyntaxException { @@ -129,23 +129,23 @@ public class ScriptCommand }); } - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder b = literal("globals"). + LiteralArgumentBuilder b = literal("globals"). executes(context -> listGlobals(context, false)). then(literal("all").executes(context -> listGlobals(context, true))); - LiteralArgumentBuilder o = literal("stop"). + LiteralArgumentBuilder o = literal("stop"). executes( (cc) -> { CarpetServer.scriptServer.stopAll = true; return 1;}); - LiteralArgumentBuilder u = literal("resume"). + LiteralArgumentBuilder u = literal("resume"). executes( (cc) -> { CarpetServer.scriptServer.stopAll = false; return 1;}); - LiteralArgumentBuilder l = literal("run"). + LiteralArgumentBuilder l = literal("run"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)). then(argument("expr", StringArgumentType.greedyString()).suggests(ScriptCommand::suggestCode). executes((cc) -> compute( cc, StringArgumentType.getString(cc, "expr")))); - LiteralArgumentBuilder s = literal("invoke"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)). + LiteralArgumentBuilder s = literal("invoke"). + then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). executes( (cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), @@ -161,13 +161,13 @@ public class ScriptCommand null, StringArgumentType.getString(cc, "arguments") )))); - LiteralArgumentBuilder c = literal("invokepoint"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)). - then(argument("origin", BlockPosArgumentType.blockPos()). + LiteralArgumentBuilder c = literal("invokepoint"). + then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). + then(argument("origin", BlockPosArgument.blockPos()). executes( (cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), - BlockPosArgumentType.getBlockPos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "origin"), null, "" )). @@ -175,99 +175,99 @@ public class ScriptCommand executes( (cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), - BlockPosArgumentType.getBlockPos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "origin"), null, StringArgumentType.getString(cc, "arguments") ))))); - LiteralArgumentBuilder h = literal("invokearea"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggestMatching(suggestFunctionCalls(cc),bb)). - then(argument("from", BlockPosArgumentType.blockPos()). - then(argument("to", BlockPosArgumentType.blockPos()). + LiteralArgumentBuilder h = literal("invokearea"). + then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). + then(argument("from", BlockPosArgument.blockPos()). + then(argument("to", BlockPosArgument.blockPos()). executes( (cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), "" )). then(argument("arguments", StringArgumentType.greedyString()). executes( (cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "arguments") )))))); - LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermissionLevel(2)). - then(argument("origin", BlockPosArgumentType.blockPos()). - then(argument("from", BlockPosArgumentType.blockPos()). - then(argument("to", BlockPosArgumentType.blockPos()). + LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermission(2)). + then(argument("origin", BlockPosArgument.blockPos()). + then(argument("from", BlockPosArgument.blockPos()). + then(argument("to", BlockPosArgument.blockPos()). then(argument("expr", StringArgumentType.greedyString()). suggests(ScriptCommand::suggestCode). executes( (cc) -> scriptScan( cc, - BlockPosArgumentType.getBlockPos(cc, "origin"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr") )))))); - LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermissionLevel(2)). - then(argument("origin", BlockPosArgumentType.blockPos()). - then(argument("from", BlockPosArgumentType.blockPos()). - then(argument("to", BlockPosArgumentType.blockPos()). + LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermission(2)). + then(argument("origin", BlockPosArgument.blockPos()). + then(argument("from", BlockPosArgument.blockPos()). + then(argument("to", BlockPosArgument.blockPos()). then(argument("expr", StringArgumentType.string()). - then(argument("block", BlockStateArgumentType.blockState()). + then(argument("block", BlockStateArgument.block()). executes((cc) -> scriptFill( cc, - BlockPosArgumentType.getBlockPos(cc, "origin"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr"), - BlockStateArgumentType.getBlockState(cc, "block"), + BlockStateArgument.getBlock(cc, "block"), null, "solid" )). then(literal("replace"). - then(argument("filter", BlockPredicateArgumentType.blockPredicate()) + then(argument("filter", BlockPredicateArgument.blockPredicate()) .executes((cc) -> scriptFill( cc, - BlockPosArgumentType.getBlockPos(cc, "origin"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr"), - BlockStateArgumentType.getBlockState(cc, "block"), - BlockPredicateArgumentType.getBlockPredicate(cc, "filter"), + BlockStateArgument.getBlock(cc, "block"), + BlockPredicateArgument.getBlockPredicate(cc, "filter"), "solid" ))))))))); - LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermissionLevel(2)). - then(argument("origin", BlockPosArgumentType.blockPos()). - then(argument("from", BlockPosArgumentType.blockPos()). - then(argument("to", BlockPosArgumentType.blockPos()). + LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermission(2)). + then(argument("origin", BlockPosArgument.blockPos()). + then(argument("from", BlockPosArgument.blockPos()). + then(argument("to", BlockPosArgument.blockPos()). then(argument("expr", StringArgumentType.string()). - then(argument("block", BlockStateArgumentType.blockState()). + then(argument("block", BlockStateArgument.block()). executes((cc) -> scriptFill( cc, - BlockPosArgumentType.getBlockPos(cc, "origin"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr"), - BlockStateArgumentType.getBlockState(cc, "block"), + BlockStateArgument.getBlock(cc, "block"), null, "outline" )). then(literal("replace"). - then(argument("filter", BlockPredicateArgumentType.blockPredicate()) + then(argument("filter", BlockPredicateArgument.blockPredicate()) .executes((cc) -> scriptFill( cc, - BlockPosArgumentType.getBlockPos(cc, "origin"), - BlockPosArgumentType.getBlockPos(cc, "from"), - BlockPosArgumentType.getBlockPos(cc, "to"), + BlockPosArgument.getSpawnablePos(cc, "origin"), + BlockPosArgument.getSpawnablePos(cc, "from"), + BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr"), - BlockStateArgumentType.getBlockState(cc, "block"), - BlockPredicateArgumentType.getBlockPredicate(cc, "filter"), + BlockStateArgument.getBlock(cc, "block"), + BlockPredicateArgument.getBlockPredicate(cc, "filter"), "outline" ))))))))); - LiteralArgumentBuilder a = literal("load").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). + LiteralArgumentBuilder a = literal("load").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.listAvailableModules(true),bb)). + suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.listAvailableModules(true),bb)). executes((cc) -> { boolean success = CarpetServer.scriptServer.addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null); @@ -282,22 +282,22 @@ public class ScriptCommand ) ) ); - LiteralArgumentBuilder f = literal("unload").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). + LiteralArgumentBuilder f = literal("unload").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.unloadableModules,bb)). + suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)). executes((cc) -> { boolean success =CarpetServer.scriptServer.removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false); return success?1:0; })); - LiteralArgumentBuilder q = literal("event").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). + LiteralArgumentBuilder q = literal("event").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). executes( (cc) -> listEvents(cc.getSource())). then(literal("add_to"). then(argument("event", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().map(ev -> ev.name).collect(Collectors.toList()),bb)). + suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().map(ev -> ev.name).collect(Collectors.toList()),bb)). then(argument("call", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)). + suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), @@ -306,9 +306,9 @@ public class ScriptCommand )?1:0)). then(literal("from"). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.modules.keySet(), bb)). + suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)). then(argument("call", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)). + suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), @@ -317,22 +317,22 @@ public class ScriptCommand )?1:0)))))). then(literal("remove_from"). then(argument("event", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()) ,bb)). + suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()) ,bb)). then(argument("call", StringArgumentType.greedyString()). - suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), CarpetServer.scriptServer).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)). + suggests( (cc, bb) -> suggest(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), CarpetServer.scriptServer).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)). executes( (cc) -> CarpetServer.scriptServer.events.removeEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), StringArgumentType.getString(cc, "call") )?1:0)))); - LiteralArgumentBuilder d = literal("download").requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)). + LiteralArgumentBuilder d = literal("download").requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE)). then(argument("path", StringArgumentType.greedyString()). suggests(ScriptCommand::suggestDownloadableApps). executes(cc-> AppStoreManager.downloadScript(cc.getSource(), StringArgumentType.getString(cc,"path")))); - LiteralArgumentBuilder r = literal("remove").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). + LiteralArgumentBuilder r = literal("remove").requires( (player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScriptACE) ). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.unloadableModules,bb)). + suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)). executes((cc) -> { boolean success =CarpetServer.scriptServer.uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app")); @@ -346,10 +346,10 @@ public class ScriptCommand requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandScript)). then(literal("in"). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.modules.keySet(), bb)). + suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)). then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t)))); } - private static CarpetScriptHost getHost(CommandContext context) throws CommandSyntaxException + private static CarpetScriptHost getHost(CommandContext context) throws CommandSyntaxException { CarpetScriptHost host; try @@ -365,12 +365,12 @@ public class ScriptCommand host.setChatErrorSnooper(context.getSource()); return host; } - private static Collection suggestFunctionCalls(CommandContext c) throws CommandSyntaxException + private static Collection suggestFunctionCalls(CommandContext c) throws CommandSyntaxException { CarpetScriptHost host = getHost(c); return host.globalFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()); } - private static int listEvents(ServerCommandSource source) + private static int listEvents(CommandSourceStack source) { Messenger.m(source, "w Lists ALL event handlers:"); for (CarpetEventServer.Event event: CarpetEventServer.Event.getAllEvents(CarpetServer.scriptServer, null)) @@ -388,10 +388,10 @@ public class ScriptCommand } return 1; } - private static int listGlobals(CommandContext context, boolean all) throws CommandSyntaxException + private static int listGlobals(CommandContext context, boolean all) throws CommandSyntaxException { CarpetScriptHost host = getHost(context); - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); Messenger.m(source, "lb Stored functions"+((host == CarpetServer.scriptServer.globalHost)?":":" in "+host.getName()+":")); host.globalFunctionNames(host.main, (str) -> all || !str.startsWith("__")).sorted().forEach( (s) -> { @@ -429,7 +429,7 @@ public class ScriptCommand return 1; } - public static int handleCall(ServerCommandSource source, CarpetScriptHost host, Supplier call) + public static int handleCall(CommandSourceStack source, CarpetScriptHost host, Supplier call) { try { @@ -470,9 +470,9 @@ public class ScriptCommand //host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way } - private static int invoke(CommandContext context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException + private static int invoke(CommandContext context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException { - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); CarpetScriptHost host = getHost(context); if (call.startsWith("__")) { @@ -498,9 +498,9 @@ public class ScriptCommand } - private static int compute(CommandContext context, String expr) throws CommandSyntaxException + private static int compute(CommandContext context, String expr) throws CommandSyntaxException { - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); CarpetScriptHost host = getHost(context); return handleCall(source, host, () -> { CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); @@ -508,13 +508,13 @@ public class ScriptCommand }); } - private static int scriptScan(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException + private static int scriptScan(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException { - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); CarpetScriptHost host = getHost(context); - BlockBox area = BlockBox.create(a, b); + BoundingBox area = BoundingBox.fromCorners(a, b); CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); // X Y Z + int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z if (int_1 > CarpetSettings.fillLimit) { Messenger.m(source, "r too many blocks to evaluate: " + int_1); @@ -524,11 +524,11 @@ public class ScriptCommand CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); try { - for (int x = area.getMinX(); x <= area.getMaxX(); x++) + for (int x = area.minX(); x <= area.maxX(); x++) { - for (int y = area.getMinY(); y <= area.getMaxY(); y++) + for (int y = area.minY(); y <= area.maxY(); y++) { - for (int z = area.getMinZ(); z <= area.getMaxZ(); z++) + for (int z = area.minZ(); z <= area.maxZ(); z++) { try { @@ -556,36 +556,36 @@ public class ScriptCommand } - private static int scriptFill(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr, - BlockStateArgument block, Predicate replacement, String mode) throws CommandSyntaxException + private static int scriptFill(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr, + BlockInput block, Predicate replacement, String mode) throws CommandSyntaxException { - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); CarpetScriptHost host = getHost(context); - BlockBox area = BlockBox.create(a, b); + BoundingBox area = BoundingBox.fromCorners(a, b); CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); + int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); if (int_1 > CarpetSettings.fillLimit) { Messenger.m(source, "r too many blocks to evaluate: "+ int_1); return 1; } - boolean[][][] volume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()]; //X then Y then Z got messedup + boolean[][][] volume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; //X then Y then Z got messedup - BlockPos.Mutable mbpos = origin.mutableCopy(); - ServerWorld world = source.getWorld(); + BlockPos.MutableBlockPos mbpos = origin.mutable(); + ServerLevel world = source.getLevel(); - for (int x = area.getMinX(); x <= area.getMaxX(); x++) + for (int x = area.minX(); x <= area.maxX(); x++) { - for (int y = area.getMinY(); y <= area.getMaxY(); y++) + for (int y = area.minY(); y <= area.maxY(); y++) { - for (int z = area.getMinZ(); z <= area.getMaxZ(); z++) + for (int z = area.minZ(); z <= area.maxZ(); z++) { try { if (cexpr.fillAndScanCommand(host, x, y, z)) { - volume[x-area.getMinX()][y-area.getMinY()][z-area.getMinZ()]=true; + volume[x-area.minX()][y-area.minY()][z-area.minZ()]=true; } } catch (CarpetExpressionException e) @@ -599,12 +599,12 @@ public class ScriptCommand } } } - final int maxx = area.getBlockCountX()-1; - final int maxy = area.getBlockCountY()-1; - final int maxz = area.getBlockCountZ()-1; + final int maxx = area.getXSpan()-1; + final int maxy = area.getYSpan()-1; + final int maxz = area.getZSpan()-1; if ("outline".equalsIgnoreCase(mode)) { - boolean[][][] newVolume = new boolean[area.getBlockCountX()][area.getBlockCountY()][area.getBlockCountZ()]; + boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; for (int x = 0; x <= maxx; x++) { for (int y = 0; y <= maxy; y++) @@ -640,14 +640,14 @@ public class ScriptCommand { if (volume[x][y][z]) { - mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ()); + mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ()); if (replacement == null || replacement.test( - new CachedBlockPosition( world, mbpos, true))) + new BlockInWorld( world, mbpos, true))) { BlockEntity tileentity = world.getBlockEntity(mbpos); - Clearable.clear(tileentity); + Clearable.tryClear(tileentity); - if (block.setBlockState(world, mbpos,2)) + if (block.place(world, mbpos,2)) { ++affected; } @@ -668,15 +668,15 @@ public class ScriptCommand { if (volume[x][y][z]) { - mbpos.set(x+area.getMinX(), y+area.getMinY(), z+area.getMinZ()); + mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ()); Block blokc = world.getBlockState(mbpos).getBlock(); - world.updateNeighbors(mbpos, blokc); + world.blockUpdated(mbpos, blokc); } } } } } - Messenger.m(source, "gi Affected "+affected+" blocks in "+area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ()+" block volume"); + Messenger.m(source, "gi Affected "+affected+" blocks in "+area.getXSpan() * area.getYSpan() * area.getZSpan()+" block volume"); return 1; } } diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index 28da5638..156fa5a8 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -12,54 +12,53 @@ import com.mojang.brigadier.arguments.BoolArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.command.argument.DimensionArgumentType; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.DyeColor; -import net.minecraft.util.math.BlockPos; - import java.util.Arrays; import java.util.Locale; import java.util.stream.Collectors; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.DimensionArgument; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.item.DyeColor; import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; import static com.mojang.brigadier.arguments.StringArgumentType.getString; import static com.mojang.brigadier.arguments.StringArgumentType.string; import static com.mojang.brigadier.arguments.StringArgumentType.word; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class SpawnCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder literalargumentbuilder = literal("spawn"). + LiteralArgumentBuilder literalargumentbuilder = literal("spawn"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandSpawn)); literalargumentbuilder. then(literal("list"). - then(argument("pos", BlockPosArgumentType.blockPos()). - executes( (c) -> listSpawns(c.getSource(), BlockPosArgumentType.getBlockPos(c, "pos"))))). + then(argument("pos", BlockPosArgument.blockPos()). + executes( (c) -> listSpawns(c.getSource(), BlockPosArgument.getSpawnablePos(c, "pos"))))). then(literal("tracking"). executes( (c) -> printTrackingReport(c.getSource())). then(literal("start"). executes( (c) -> startTracking(c.getSource(), null, null)). - then(argument("from", BlockPosArgumentType.blockPos()). - then(argument("to", BlockPosArgumentType.blockPos()). + then(argument("from", BlockPosArgument.blockPos()). + then(argument("to", BlockPosArgument.blockPos()). executes( (c) -> startTracking( c.getSource(), - BlockPosArgumentType.getBlockPos(c, "from"), - BlockPosArgumentType.getBlockPos(c, "to")))))). + BlockPosArgument.getSpawnablePos(c, "from"), + BlockPosArgument.getSpawnablePos(c, "to")))))). then(literal("stop"). executes( (c) -> stopTracking(c.getSource()))). then(argument("type", word()). - suggests( (c, b) -> suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName),b)). + suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)). executes( (c) -> recentSpawnsForType(c.getSource(), getString(c, "type"))))). then(literal("test"). executes( (c)-> runTest(c.getSource(), 72000, null)). @@ -69,7 +68,7 @@ public class SpawnCommand getInteger(c, "ticks"), null)). then(argument("counter", word()). - suggests( (c, b) -> suggestMatching(Arrays.stream(DyeColor.values()).map(DyeColor::toString),b)). + suggests( (c, b) -> suggest(Arrays.stream(DyeColor.values()).map(DyeColor::toString),b)). executes((c)-> runTest( c.getSource(), getInteger(c, "ticks"), @@ -82,9 +81,9 @@ public class SpawnCommand then(literal("reset"). executes( (c) -> resetSpawnRates(c.getSource()))). then(argument("type", word()). - suggests( (c, b) -> suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName),b)). + suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)). then(argument("rounds", integer(0)). - suggests( (c, b) -> suggestMatching(new String[]{"1"},b)). + suggests( (c, b) -> suggest(new String[]{"1"},b)). executes( (c) -> setSpawnRates( c.getSource(), getString(c, "type"), @@ -94,41 +93,41 @@ public class SpawnCommand then(literal("set"). then(argument("cap (hostile)", integer(1,1400)). executes( (c) -> setMobcaps(c.getSource(), getInteger(c, "cap (hostile)"))))). - then(argument("dimension", DimensionArgumentType.dimension()). - executes( (c)-> mobcapsForDimension(c.getSource(), DimensionArgumentType.getDimensionArgument(c, "dimension"))))). + then(argument("dimension", DimensionArgument.dimension()). + executes( (c)-> mobcapsForDimension(c.getSource(), DimensionArgument.getDimension(c, "dimension"))))). then(literal("entities"). executes( (c) -> generalMobcaps(c.getSource()) ). then(argument("type", string()). - suggests( (c, b)->suggestMatching(Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName), b)). + suggests( (c, b)->suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName), b)). executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), false)). then(literal("all").executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), true))))); dispatcher.register(literalargumentbuilder); } - private static SpawnGroup getCategory(String string) throws CommandSyntaxException + private static MobCategory getCategory(String string) throws CommandSyntaxException { - if (!Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName).collect(Collectors.toSet()).contains(string)) + if (!Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.toSet()).contains(string)) { - throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(SpawnGroup.values()).map(SpawnGroup::getName).collect(Collectors.joining(", ")))).create(); + throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.joining(", ")))).create(); } - return SpawnGroup.byName(string.toLowerCase(Locale.ROOT)); + return MobCategory.byName(string.toLowerCase(Locale.ROOT)); } - private static int listSpawns(ServerCommandSource source, BlockPos pos) + private static int listSpawns(CommandSourceStack source, BlockPos pos) { - Messenger.send(source, SpawnReporter.report(pos, source.getWorld())); + Messenger.send(source, SpawnReporter.report(pos, source.getLevel())); return 1; } - private static int printTrackingReport(ServerCommandSource source) + private static int printTrackingReport(CommandSourceStack source) { - Messenger.send(source, SpawnReporter.tracking_report(source.getWorld())); + Messenger.send(source, SpawnReporter.tracking_report(source.getLevel())); return 1; } - private static int startTracking(ServerCommandSource source, BlockPos a, BlockPos b) + private static int startTracking(CommandSourceStack source, BlockPos a, BlockPos b) { if (SpawnReporter.track_spawns != 0L) { @@ -149,16 +148,16 @@ public class SpawnCommand Math.max(a.getZ(), b.getZ()) ); } SpawnReporter.reset_spawn_stats(source.getServer(), false); - SpawnReporter.track_spawns = (long) source.getServer().getTicks(); + SpawnReporter.track_spawns = (long) source.getServer().getTickCount(); SpawnReporter.lower_spawning_limit = lsl; SpawnReporter.upper_spawning_limit = usl; Messenger.m(source, "gi Spawning tracking started."); return 1; } - private static int stopTracking(ServerCommandSource source) + private static int stopTracking(CommandSourceStack source) { - Messenger.send(source, SpawnReporter.tracking_report(source.getWorld())); + Messenger.send(source, SpawnReporter.tracking_report(source.getLevel())); SpawnReporter.reset_spawn_stats(source.getServer(),false); SpawnReporter.track_spawns = 0L; SpawnReporter.lower_spawning_limit = null; @@ -167,19 +166,19 @@ public class SpawnCommand return 1; } - private static int recentSpawnsForType(ServerCommandSource source, String mob_type) throws CommandSyntaxException + private static int recentSpawnsForType(CommandSourceStack source, String mob_type) throws CommandSyntaxException { - SpawnGroup cat = getCategory(mob_type); - Messenger.send(source, SpawnReporter.recent_spawns(source.getWorld(), cat)); + MobCategory cat = getCategory(mob_type); + Messenger.send(source, SpawnReporter.recent_spawns(source.getLevel(), cat)); return 1; } - private static int runTest(ServerCommandSource source, int ticks, String counter) + private static int runTest(CommandSourceStack source, int ticks, String counter) { //stop tracking SpawnReporter.reset_spawn_stats(source.getServer(),false); //start tracking - SpawnReporter.track_spawns = (long) source.getServer().getTicks(); + SpawnReporter.track_spawns = (long) source.getServer().getTickCount(); //counter reset if (counter == null) { @@ -196,11 +195,11 @@ public class SpawnCommand // tick warp 0 TickSpeed.tickrate_advance(null, 0, null, null); // tick warp given player - ServerCommandSource csource = null; - ServerPlayerEntity player = null; + CommandSourceStack csource = null; + ServerPlayer player = null; try { - player = source.getPlayer(); + player = source.getPlayerOrException(); csource = source; } catch (CommandSyntaxException ignored) @@ -211,7 +210,7 @@ public class SpawnCommand return 1; } - private static int toggleMocking(ServerCommandSource source, boolean domock) + private static int toggleMocking(CommandSourceStack source, boolean domock) { if (domock) { @@ -226,15 +225,15 @@ public class SpawnCommand return 1; } - private static int generalMobcaps(ServerCommandSource source) + private static int generalMobcaps(CommandSourceStack source) { - Messenger.send(source, SpawnReporter.printMobcapsForDimension(source.getWorld(), true)); + Messenger.send(source, SpawnReporter.printMobcapsForDimension(source.getLevel(), true)); return 1; } - private static int resetSpawnRates(ServerCommandSource source) + private static int resetSpawnRates(CommandSourceStack source) { - for (SpawnGroup s: SpawnReporter.spawn_tries.keySet()) + for (MobCategory s: SpawnReporter.spawn_tries.keySet()) { SpawnReporter.spawn_tries.put(s,1); } @@ -243,32 +242,32 @@ public class SpawnCommand return 1; } - private static int setSpawnRates(ServerCommandSource source, String mobtype, int rounds) throws CommandSyntaxException + private static int setSpawnRates(CommandSourceStack source, String mobtype, int rounds) throws CommandSyntaxException { - SpawnGroup cat = getCategory(mobtype); + MobCategory cat = getCategory(mobtype); SpawnReporter.spawn_tries.put(cat, rounds); Messenger.m(source, "gi "+mobtype+" mobs will now spawn "+rounds+" times per tick"); return 1; } - private static int setMobcaps(ServerCommandSource source, int hostile_cap) + private static int setMobcaps(CommandSourceStack source, int hostile_cap) { - double desired_ratio = (double)hostile_cap/ ((SpawnGroupInterface)(Object)SpawnGroup.MONSTER).getInitialSpawnCap(); + double desired_ratio = (double)hostile_cap/ ((SpawnGroupInterface)(Object)MobCategory.MONSTER).getInitialSpawnCap(); SpawnReporter.mobcap_exponent = 4.0*Math.log(desired_ratio)/Math.log(2.0); Messenger.m(source, String.format("gi Mobcaps for hostile mobs changed to %d, other groups will follow", hostile_cap)); return 1; } - private static int mobcapsForDimension(ServerCommandSource source, ServerWorld world) + private static int mobcapsForDimension(CommandSourceStack source, ServerLevel world) { Messenger.send(source, SpawnReporter.printMobcapsForDimension(world, true)); return 1; } - private static int listEntitiesOfType(ServerCommandSource source, String mobtype, boolean all) throws CommandSyntaxException + private static int listEntitiesOfType(CommandSourceStack source, String mobtype, boolean all) throws CommandSyntaxException { - SpawnGroup cat = getCategory(mobtype); - Messenger.send(source, SpawnReporter.printEntitiesByType(cat, source.getWorld(), all)); + MobCategory cat = getCategory(mobtype); + Messenger.send(source, SpawnReporter.printEntitiesByType(cat, source.getLevel(), all)); return 1; } } diff --git a/src/main/java/carpet/commands/TestCommand.java b/src/main/java/carpet/commands/TestCommand.java index 6f097376..723773b1 100644 --- a/src/main/java/carpet/commands/TestCommand.java +++ b/src/main/java/carpet/commands/TestCommand.java @@ -4,16 +4,16 @@ import carpet.CarpetServer; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; import static com.mojang.brigadier.arguments.StringArgumentType.getString; import static com.mojang.brigadier.arguments.StringArgumentType.word; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class TestCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("testcarpet"). then(literal("dump"). @@ -26,7 +26,7 @@ public class TestCommand executes( (c)-> test(c, getString(c, "second")+" 2")))); } - private static int test(CommandContext c, String term) + private static int test(CommandContext c, String term) { Messenger.m(c.getSource(),term.substring(0,1)+" "+term+": how did you get here?"); return 1; diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 78a8af5d..f99ecaab 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -9,9 +9,9 @@ import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerPlayer; import static com.mojang.brigadier.arguments.FloatArgumentType.floatArg; import static com.mojang.brigadier.arguments.FloatArgumentType.getFloat; @@ -19,25 +19,25 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; import static com.mojang.brigadier.arguments.StringArgumentType.getString; import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.command.CommandSource.suggestMatching; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; public class TickCommand { - public static void register(CommandDispatcher dispatcher) + public static void register(CommandDispatcher dispatcher) { - LiteralArgumentBuilder literalargumentbuilder = literal("tick"). + LiteralArgumentBuilder literalargumentbuilder = literal("tick"). requires((player) -> SettingsManager.canUseCommand(player, CarpetSettings.commandTick)). then(literal("rate"). executes((c) -> queryTps(c.getSource())). then(argument("rate", floatArg(0.1F, 500.0F)). - suggests( (c, b) -> suggestMatching(new String[]{"20.0"},b)). + suggests( (c, b) -> suggest(new String[]{"20.0"},b)). executes((c) -> setTps(c.getSource(), getFloat(c, "rate"))))). then(literal("warp"). executes( (c)-> setWarp(c.getSource(), 0, null)). then(argument("ticks", integer(0)). - suggests( (c, b) -> suggestMatching(new String[]{"3600","72000"},b)). + suggests( (c, b) -> suggest(new String[]{"3600","72000"},b)). executes((c) -> setWarp(c.getSource(), getInteger(c,"ticks"), null)). then(argument("tail command", greedyString()). executes( (c) -> setWarp( @@ -53,7 +53,7 @@ public class TickCommand then(literal("step"). executes((c) -> step(c.getSource(), 1)). then(argument("ticks", integer(1,72000)). - suggests( (c, b) -> suggestMatching(new String[]{"20"},b)). + suggests( (c, b) -> suggest(new String[]{"20"},b)). executes((c) -> step(c.getSource(), getInteger(c,"ticks"))))). then(literal("superHot").executes( (c)-> toggleSuperHot(c.getSource()))). then(literal("health"). @@ -70,35 +70,35 @@ public class TickCommand } - private static int setTps(ServerCommandSource source, float tps) + private static int setTps(CommandSourceStack source, float tps) { TickSpeed.tickrate(tps, true); queryTps(source); return (int)tps; } - private static int queryTps(ServerCommandSource source) + private static int queryTps(CommandSourceStack source) { Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", TickSpeed.tickrate)); return (int)TickSpeed.tickrate; } - private static int setWarp(ServerCommandSource source, int advance, String tail_command) + private static int setWarp(CommandSourceStack source, int advance, String tail_command) { - ServerPlayerEntity player = null; + ServerPlayer player = null; try { - player = source.getPlayer(); + player = source.getPlayerOrException(); } catch (CommandSyntaxException ignored) { } - BaseText message = TickSpeed.tickrate_advance(player, advance, tail_command, source); - source.sendFeedback(message, false); + BaseComponent message = TickSpeed.tickrate_advance(player, advance, tail_command, source); + source.sendSuccess(message, false); return 1; } - private static int freezeStatus(ServerCommandSource source) + private static int freezeStatus(CommandSourceStack source) { if(TickSpeed.isPaused()) { @@ -111,7 +111,7 @@ public class TickCommand return 1; } - private static int setFreeze(ServerCommandSource source, boolean isDeep, boolean freeze) + private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean freeze) { TickSpeed.setFrozenState(freeze, isDeep); if (TickSpeed.isPaused()) @@ -125,19 +125,19 @@ public class TickCommand return 1; } - private static int toggleFreeze(ServerCommandSource source, boolean isDeep) + private static int toggleFreeze(CommandSourceStack source, boolean isDeep) { return setFreeze(source, isDeep, !TickSpeed.isPaused()); } - private static int step(ServerCommandSource source, int advance) + private static int step(CommandSourceStack source, int advance) { TickSpeed.add_ticks_to_run_in_pause(advance); Messenger.m(source, "gi Stepping " + advance + " tick" + (advance != 1 ? "s" : "")); return 1; } - private static int toggleSuperHot(ServerCommandSource source) + private static int toggleSuperHot(CommandSourceStack source) { TickSpeed.is_superHot = !TickSpeed.is_superHot; ServerNetworkHandler.updateSuperHotStateToConnectedPlayers(); @@ -152,13 +152,13 @@ public class TickCommand return 1; } - public static int healthReport(ServerCommandSource source, int ticks) + public static int healthReport(CommandSourceStack source, int ticks) { CarpetProfiler.prepare_tick_report(source, ticks); return 1; } - public static int healthEntities(ServerCommandSource source, int ticks) + public static int healthEntities(CommandSourceStack source, int ticks) { CarpetProfiler.prepare_entity_report(source, ticks); return 1; diff --git a/src/main/java/carpet/fakes/BiomeArrayInterface.java b/src/main/java/carpet/fakes/BiomeArrayInterface.java index 2e6946cc..8860abee 100644 --- a/src/main/java/carpet/fakes/BiomeArrayInterface.java +++ b/src/main/java/carpet/fakes/BiomeArrayInterface.java @@ -1,10 +1,10 @@ package carpet.fakes; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biome; public interface BiomeArrayInterface // unused { - void setBiomeAtIndex(BlockPos pos, World world, Biome what); + void setBiomeAtIndex(BlockPos pos, Level world, Biome what); } diff --git a/src/main/java/carpet/fakes/BlockEntityInterface.java b/src/main/java/carpet/fakes/BlockEntityInterface.java index ca734897..7847ce60 100644 --- a/src/main/java/carpet/fakes/BlockEntityInterface.java +++ b/src/main/java/carpet/fakes/BlockEntityInterface.java @@ -1,6 +1,6 @@ package carpet.fakes; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; public interface BlockEntityInterface { diff --git a/src/main/java/carpet/fakes/BlockPredicateInterface.java b/src/main/java/carpet/fakes/BlockPredicateInterface.java index c8d3e32b..e8f70d0e 100644 --- a/src/main/java/carpet/fakes/BlockPredicateInterface.java +++ b/src/main/java/carpet/fakes/BlockPredicateInterface.java @@ -1,17 +1,16 @@ package carpet.fakes; import carpet.script.value.Value; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.tag.Tag; - import java.util.Map; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.tags.Tag; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; public interface BlockPredicateInterface { BlockState getCMBlockState(); Tag getCMBlockTag(); Map getCMProperties(); - NbtCompound getCMDataTag(); + CompoundTag getCMDataTag(); } diff --git a/src/main/java/carpet/fakes/BlockStateArgumentInterface.java b/src/main/java/carpet/fakes/BlockStateArgumentInterface.java index ceda6f03..20610ed3 100644 --- a/src/main/java/carpet/fakes/BlockStateArgumentInterface.java +++ b/src/main/java/carpet/fakes/BlockStateArgumentInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; public interface BlockStateArgumentInterface { - NbtCompound getCMTag(); + CompoundTag getCMTag(); } diff --git a/src/main/java/carpet/fakes/ChunkGeneratorInterface.java b/src/main/java/carpet/fakes/ChunkGeneratorInterface.java index 834662bf..76db84c3 100644 --- a/src/main/java/carpet/fakes/ChunkGeneratorInterface.java +++ b/src/main/java/carpet/fakes/ChunkGeneratorInterface.java @@ -1,6 +1,6 @@ package carpet.fakes; -import net.minecraft.world.biome.Biome; +import net.minecraft.world.level.biome.Biome; public interface ChunkGeneratorInterface { diff --git a/src/main/java/carpet/fakes/ChunkHolderInterface.java b/src/main/java/carpet/fakes/ChunkHolderInterface.java index 7619279d..e9cd29cf 100644 --- a/src/main/java/carpet/fakes/ChunkHolderInterface.java +++ b/src/main/java/carpet/fakes/ChunkHolderInterface.java @@ -1,15 +1,14 @@ package carpet.fakes; import com.mojang.datafixers.util.Either; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.thread.ThreadExecutor; -import net.minecraft.world.chunk.Chunk; - import java.util.concurrent.CompletableFuture; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.thread.BlockableEventLoop; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; public interface ChunkHolderInterface { - CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor, ServerWorld world); + CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, BlockableEventLoop executor, ServerLevel world); } diff --git a/src/main/java/carpet/fakes/ChunkLightProviderInterface.java b/src/main/java/carpet/fakes/ChunkLightProviderInterface.java index 10ae0277..6da216c4 100644 --- a/src/main/java/carpet/fakes/ChunkLightProviderInterface.java +++ b/src/main/java/carpet/fakes/ChunkLightProviderInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.world.chunk.ChunkNibbleArray; +import net.minecraft.world.level.chunk.DataLayer; public interface ChunkLightProviderInterface { - int callGetCurrentLevelFromSection(ChunkNibbleArray array, long blockPos); + int callGetCurrentLevelFromSection(DataLayer array, long blockPos); } diff --git a/src/main/java/carpet/fakes/ChunkTicketManagerInterface.java b/src/main/java/carpet/fakes/ChunkTicketManagerInterface.java index 56c4c32c..2a01ed8c 100644 --- a/src/main/java/carpet/fakes/ChunkTicketManagerInterface.java +++ b/src/main/java/carpet/fakes/ChunkTicketManagerInterface.java @@ -1,16 +1,16 @@ package carpet.fakes; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ChunkTicket; -import net.minecraft.util.collection.SortedArraySet; -import net.minecraft.util.math.ChunkPos; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.Ticket; +import net.minecraft.util.SortedArraySet; +import net.minecraft.world.level.ChunkPos; public interface ChunkTicketManagerInterface { void changeSpawnChunks(ChunkPos pos, int distance); - Long2ObjectOpenHashMap>> getTicketsByPosition(); + Long2ObjectOpenHashMap>> getTicketsByPosition(); void replaceHolder(ChunkHolder oldHolder, ChunkHolder newHolder); } diff --git a/src/main/java/carpet/fakes/CoralFeatureInterface.java b/src/main/java/carpet/fakes/CoralFeatureInterface.java index a5ee25e2..9d332f6d 100644 --- a/src/main/java/carpet/fakes/CoralFeatureInterface.java +++ b/src/main/java/carpet/fakes/CoralFeatureInterface.java @@ -1,12 +1,11 @@ package carpet.fakes; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; public interface CoralFeatureInterface { - boolean growSpecific(World worldIn, Random random, BlockPos pos, BlockState blockUnder); + boolean growSpecific(Level worldIn, Random random, BlockPos pos, BlockState blockUnder); } diff --git a/src/main/java/carpet/fakes/IngredientInterface.java b/src/main/java/carpet/fakes/IngredientInterface.java index 76f4fff2..f6d93854 100644 --- a/src/main/java/carpet/fakes/IngredientInterface.java +++ b/src/main/java/carpet/fakes/IngredientInterface.java @@ -1,9 +1,8 @@ package carpet.fakes; -import net.minecraft.item.ItemStack; - import java.util.Collection; import java.util.List; +import net.minecraft.world.item.ItemStack; public interface IngredientInterface { diff --git a/src/main/java/carpet/fakes/InventoryBearerInterface.java b/src/main/java/carpet/fakes/InventoryBearerInterface.java index 5355786b..d40a02ea 100644 --- a/src/main/java/carpet/fakes/InventoryBearerInterface.java +++ b/src/main/java/carpet/fakes/InventoryBearerInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.inventory.Inventory; +import net.minecraft.world.Container; public interface InventoryBearerInterface { - Inventory getCMInventory(); // can be removed in 1.17 due to class_6067 + Container getCMInventory(); // can be removed in 1.17 due to class_6067 } diff --git a/src/main/java/carpet/fakes/LightStorageInterface.java b/src/main/java/carpet/fakes/LightStorageInterface.java index 3d8ae2da..f233a2ac 100644 --- a/src/main/java/carpet/fakes/LightStorageInterface.java +++ b/src/main/java/carpet/fakes/LightStorageInterface.java @@ -1,10 +1,10 @@ package carpet.fakes; -import net.minecraft.world.chunk.light.ChunkLightProvider; +import net.minecraft.world.level.lighting.LayerLightEngine; public interface LightStorageInterface extends Lighting_scarpetChunkCreationInterface { void processRemoveLightData(long pos); - void processRelight(ChunkLightProvider lightProvider, long pos); + void processRelight(LayerLightEngine lightProvider, long pos); } diff --git a/src/main/java/carpet/fakes/MinecraftServerInterface.java b/src/main/java/carpet/fakes/MinecraftServerInterface.java index a4422592..cceaeec7 100644 --- a/src/main/java/carpet/fakes/MinecraftServerInterface.java +++ b/src/main/java/carpet/fakes/MinecraftServerInterface.java @@ -1,18 +1,17 @@ package carpet.fakes; -import net.minecraft.resource.ServerResourceManager; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; -import net.minecraft.world.level.storage.LevelStorage; - import java.util.Map; import java.util.function.BooleanSupplier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.ServerResources; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.LevelStorageSource; public interface MinecraftServerInterface { void forceTick(BooleanSupplier sup); - LevelStorage.Session getCMSession(); - Map, ServerWorld> getCMWorlds(); - ServerResourceManager getResourceManager(); + LevelStorageSource.LevelStorageAccess getCMSession(); + Map, ServerLevel> getCMWorlds(); + ServerResources getResourceManager(); } diff --git a/src/main/java/carpet/fakes/MobEntityInterface.java b/src/main/java/carpet/fakes/MobEntityInterface.java index 9e3ae237..df0dd021 100644 --- a/src/main/java/carpet/fakes/MobEntityInterface.java +++ b/src/main/java/carpet/fakes/MobEntityInterface.java @@ -1,9 +1,8 @@ package carpet.fakes; -import net.minecraft.entity.ai.goal.Goal; -import net.minecraft.entity.ai.goal.GoalSelector; - import java.util.Map; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; public interface MobEntityInterface { diff --git a/src/main/java/carpet/fakes/PistonBlockEntityInterface.java b/src/main/java/carpet/fakes/PistonBlockEntityInterface.java index dfc692d1..247fbaab 100644 --- a/src/main/java/carpet/fakes/PistonBlockEntityInterface.java +++ b/src/main/java/carpet/fakes/PistonBlockEntityInterface.java @@ -1,6 +1,6 @@ package carpet.fakes; -import net.minecraft.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntity; public interface PistonBlockEntityInterface { diff --git a/src/main/java/carpet/fakes/PistonBlockInterface.java b/src/main/java/carpet/fakes/PistonBlockInterface.java index d4ebc9fd..dcda1741 100644 --- a/src/main/java/carpet/fakes/PistonBlockInterface.java +++ b/src/main/java/carpet/fakes/PistonBlockInterface.java @@ -1,10 +1,10 @@ package carpet.fakes; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; public interface PistonBlockInterface { - boolean publicShouldExtend(World world_1, BlockPos blockPos_1, Direction direction_1); + boolean publicShouldExtend(Level world_1, BlockPos blockPos_1, Direction direction_1); } diff --git a/src/main/java/carpet/fakes/PlacedFeatureInterface.java b/src/main/java/carpet/fakes/PlacedFeatureInterface.java index b55d9702..ce7e6cce 100644 --- a/src/main/java/carpet/fakes/PlacedFeatureInterface.java +++ b/src/main/java/carpet/fakes/PlacedFeatureInterface.java @@ -1,8 +1,6 @@ package carpet.fakes; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.gen.feature.Feature; -import net.minecraft.world.gen.feature.FeatureConfig; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; public interface PlacedFeatureInterface { ConfiguredFeature getRawFeature(); diff --git a/src/main/java/carpet/fakes/RecipeManagerInterface.java b/src/main/java/carpet/fakes/RecipeManagerInterface.java index 1078b24b..6e618389 100644 --- a/src/main/java/carpet/fakes/RecipeManagerInterface.java +++ b/src/main/java/carpet/fakes/RecipeManagerInterface.java @@ -1,11 +1,9 @@ package carpet.fakes; -import net.minecraft.item.Item; -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeType; -import net.minecraft.util.Identifier; - import java.util.List; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; public interface RecipeManagerInterface { @@ -13,5 +11,5 @@ public interface RecipeManagerInterface * Gets all the recipes for a given item. Also used for {@link carpet.helpers.HopperCounter#guessColor} to guess the * colour of an item to display it prettily */ - List> getAllMatching(RecipeType type, Identifier output); + List> getAllMatching(RecipeType type, ResourceLocation output); } diff --git a/src/main/java/carpet/fakes/RedstoneWireBlockInterface.java b/src/main/java/carpet/fakes/RedstoneWireBlockInterface.java index 35889a52..8d6b7716 100644 --- a/src/main/java/carpet/fakes/RedstoneWireBlockInterface.java +++ b/src/main/java/carpet/fakes/RedstoneWireBlockInterface.java @@ -1,11 +1,11 @@ package carpet.fakes; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; public interface RedstoneWireBlockInterface { - BlockState updateLogicPublic(World world_1, BlockPos blockPos_1, BlockState blockState_1); + BlockState updateLogicPublic(Level world_1, BlockPos blockPos_1, BlockState blockState_1); void setWiresGivePower(boolean wiresGivePower); boolean getWiresGivePower(); } diff --git a/src/main/java/carpet/fakes/ScreenHandlerInterface.java b/src/main/java/carpet/fakes/ScreenHandlerInterface.java index 241da3b9..fbd0e11d 100644 --- a/src/main/java/carpet/fakes/ScreenHandlerInterface.java +++ b/src/main/java/carpet/fakes/ScreenHandlerInterface.java @@ -1,12 +1,12 @@ package carpet.fakes; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.recipe.Recipe; -import net.minecraft.screen.Property; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.item.crafting.Recipe; public interface ScreenHandlerInterface { - Property getProperty(int index); - boolean callButtonClickListener(int button, PlayerEntity player); - boolean callSelectRecipeListener(ServerPlayerEntity player, Recipe recipe, boolean craftAll); + DataSlot getProperty(int index); + boolean callButtonClickListener(int button, Player player); + boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, boolean craftAll); } diff --git a/src/main/java/carpet/fakes/ServerChunkManagerInterface.java b/src/main/java/carpet/fakes/ServerChunkManagerInterface.java index f63cb266..a65de7bf 100644 --- a/src/main/java/carpet/fakes/ServerChunkManagerInterface.java +++ b/src/main/java/carpet/fakes/ServerChunkManagerInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.server.world.ChunkTicketManager; +import net.minecraft.server.level.DistanceManager; public interface ServerChunkManagerInterface { - ChunkTicketManager getCMTicketManager(); + DistanceManager getCMTicketManager(); } diff --git a/src/main/java/carpet/fakes/ServerLightingProviderInterface.java b/src/main/java/carpet/fakes/ServerLightingProviderInterface.java index 78ec5018..780c21b9 100644 --- a/src/main/java/carpet/fakes/ServerLightingProviderInterface.java +++ b/src/main/java/carpet/fakes/ServerLightingProviderInterface.java @@ -1,17 +1,16 @@ package carpet.fakes; import java.util.concurrent.CompletableFuture; - -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; public interface ServerLightingProviderInterface { void invokeUpdateChunkStatus(ChunkPos pos); - void removeLightData(Chunk chunk); + void removeLightData(ChunkAccess chunk); - CompletableFuture relight(Chunk chunk); + CompletableFuture relight(ChunkAccess chunk); - void resetLight(Chunk chunk, ChunkPos pos); + void resetLight(ChunkAccess chunk, ChunkPos pos); } diff --git a/src/main/java/carpet/fakes/ServerPlayerInteractionManagerInterface.java b/src/main/java/carpet/fakes/ServerPlayerInteractionManagerInterface.java index ed43336a..6fcf2a0e 100644 --- a/src/main/java/carpet/fakes/ServerPlayerInteractionManagerInterface.java +++ b/src/main/java/carpet/fakes/ServerPlayerInteractionManagerInterface.java @@ -1,6 +1,6 @@ package carpet.fakes; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; public interface ServerPlayerInteractionManagerInterface { diff --git a/src/main/java/carpet/fakes/ServerWorldInterface.java b/src/main/java/carpet/fakes/ServerWorldInterface.java index 106eb72a..8617acad 100644 --- a/src/main/java/carpet/fakes/ServerWorldInterface.java +++ b/src/main/java/carpet/fakes/ServerWorldInterface.java @@ -1,10 +1,10 @@ package carpet.fakes; -import net.minecraft.entity.Entity; -import net.minecraft.world.entity.EntityLookup; -import net.minecraft.world.level.ServerWorldProperties; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.entity.LevelEntityGetter; +import net.minecraft.world.level.storage.ServerLevelData; public interface ServerWorldInterface { - ServerWorldProperties getWorldPropertiesCM(); - EntityLookup getEntityLookupCMPublic(); + ServerLevelData getWorldPropertiesCM(); + LevelEntityGetter getEntityLookupCMPublic(); } diff --git a/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java b/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java index 2802581d..415fc313 100644 --- a/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java +++ b/src/main/java/carpet/fakes/SimpleEntityLookupInterface.java @@ -1,11 +1,10 @@ package carpet.fakes; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.entity.EntityLike; - import java.util.List; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.entity.EntityAccess; -public interface SimpleEntityLookupInterface +public interface SimpleEntityLookupInterface { List getChunkEntities(ChunkPos chpos); } diff --git a/src/main/java/carpet/fakes/SpawnHelperInnerInterface.java b/src/main/java/carpet/fakes/SpawnHelperInnerInterface.java index 4a96f526..a416cf8c 100644 --- a/src/main/java/carpet/fakes/SpawnHelperInnerInterface.java +++ b/src/main/java/carpet/fakes/SpawnHelperInnerInterface.java @@ -1,10 +1,10 @@ package carpet.fakes; -import net.minecraft.util.math.GravityField; +import net.minecraft.world.level.PotentialCalculator; public interface SpawnHelperInnerInterface { - GravityField getPotentialCalculator(); + PotentialCalculator getPotentialCalculator(); int cmGetChunkCount(); } diff --git a/src/main/java/carpet/fakes/StructureFeatureInterface.java b/src/main/java/carpet/fakes/StructureFeatureInterface.java index b0e6fe32..d253e3cf 100644 --- a/src/main/java/carpet/fakes/StructureFeatureInterface.java +++ b/src/main/java/carpet/fakes/StructureFeatureInterface.java @@ -1,16 +1,12 @@ package carpet.fakes; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.HeightLimitView; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.gen.random.ChunkRandom; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.feature.FeatureConfig; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -public interface StructureFeatureInterface +public interface StructureFeatureInterface { - boolean plopAnywhere(ServerWorld world, BlockPos pos, ChunkGenerator generator, boolean wireOnly,Biome biome, C config); + boolean plopAnywhere(ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly,Biome biome, C config); } diff --git a/src/main/java/carpet/fakes/ThreadedAnvilChunkStorageInterface.java b/src/main/java/carpet/fakes/ThreadedAnvilChunkStorageInterface.java index d1473e53..fd1fa762 100644 --- a/src/main/java/carpet/fakes/ThreadedAnvilChunkStorageInterface.java +++ b/src/main/java/carpet/fakes/ThreadedAnvilChunkStorageInterface.java @@ -2,9 +2,8 @@ package carpet.fakes; import java.util.List; import java.util.Map; - -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.util.math.ChunkPos; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.world.level.ChunkPos; public interface ThreadedAnvilChunkStorageInterface { diff --git a/src/main/java/carpet/fakes/WorldChunkInterface.java b/src/main/java/carpet/fakes/WorldChunkInterface.java index 7590c02a..d93b0a1d 100644 --- a/src/main/java/carpet/fakes/WorldChunkInterface.java +++ b/src/main/java/carpet/fakes/WorldChunkInterface.java @@ -1,8 +1,8 @@ package carpet.fakes; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; public interface WorldChunkInterface { diff --git a/src/main/java/carpet/fakes/WorldInterface.java b/src/main/java/carpet/fakes/WorldInterface.java index 3c969187..b631f282 100644 --- a/src/main/java/carpet/fakes/WorldInterface.java +++ b/src/main/java/carpet/fakes/WorldInterface.java @@ -1,16 +1,16 @@ package carpet.fakes; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; import java.util.function.Predicate; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; public interface WorldInterface { @@ -18,5 +18,5 @@ public interface WorldInterface boolean setBlockStateWithBlockEntity(BlockPos blockPos, BlockState blockState, BlockEntity newBlockEntity, int int1); - List getOtherEntitiesLimited(@Nullable Entity except, Box box, Predicate predicate, int limit); + List getOtherEntitiesLimited(@Nullable Entity except, AABB box, Predicate predicate, int limit); } diff --git a/src/main/java/carpet/helpers/BlockRotator.java b/src/main/java/carpet/helpers/BlockRotator.java index f2ee22d7..4e1cc39c 100644 --- a/src/main/java/carpet/helpers/BlockRotator.java +++ b/src/main/java/carpet/helpers/BlockRotator.java @@ -1,55 +1,55 @@ package carpet.helpers; import carpet.fakes.PistonBlockInterface; +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockSource; +import net.minecraft.core.Direction; +import net.minecraft.core.dispenser.DispenseItemBehavior; +import net.minecraft.core.dispenser.OptionalDispenseItemBehavior; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseRailBlock; +import net.minecraft.world.level.block.BedBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.ComparatorBlock; +import net.minecraft.world.level.block.DiodeBlock; +import net.minecraft.world.level.block.DirectionalBlock; +import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.EndRodBlock; +import net.minecraft.world.level.block.FenceGateBlock; +import net.minecraft.world.level.block.GlazedTerracottaBlock; +import net.minecraft.world.level.block.HopperBlock; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; +import net.minecraft.world.level.block.LeverBlock; +import net.minecraft.world.level.block.ObserverBlock; +import net.minecraft.world.level.block.RepeaterBlock; +import net.minecraft.world.level.block.RotatedPillarBlock; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.SlabBlock; +import net.minecraft.world.level.block.StairBlock; +import net.minecraft.world.level.block.TrapDoorBlock; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.ComparatorMode; +import net.minecraft.world.level.block.state.properties.Half; +import net.minecraft.world.level.block.state.properties.SlabType; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import carpet.CarpetSettings; -import net.minecraft.block.AbstractRailBlock; -import net.minecraft.block.AbstractRedstoneGateBlock; -import net.minecraft.block.BedBlock; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.ComparatorBlock; -import net.minecraft.block.DispenserBlock; -import net.minecraft.block.EndRodBlock; -import net.minecraft.block.FacingBlock; -import net.minecraft.block.FenceGateBlock; -import net.minecraft.block.GlazedTerracottaBlock; -import net.minecraft.block.HopperBlock; -import net.minecraft.block.HorizontalFacingBlock; -import net.minecraft.block.LeverBlock; -import net.minecraft.block.ObserverBlock; -import net.minecraft.block.PillarBlock; -import net.minecraft.block.PistonBlock; -import net.minecraft.block.RepeaterBlock; -import net.minecraft.block.SlabBlock; -import net.minecraft.block.StairsBlock; -import net.minecraft.block.TrapdoorBlock; -import net.minecraft.block.dispenser.DispenserBehavior; -import net.minecraft.block.dispenser.FallibleItemDispenserBehavior; -import net.minecraft.block.enums.BlockHalf; -import net.minecraft.block.enums.ComparatorMode; -import net.minecraft.block.enums.SlabType; -import net.minecraft.block.piston.PistonHandler; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.util.BlockRotation; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPointer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; public class BlockRotator { - public static boolean flipBlockWithCactus(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit) + public static boolean flipBlockWithCactus(BlockState state, Level world, Player player, InteractionHand hand, BlockHitResult hit) { //getAbilities() - if (!player.getAbilities().allowModifyWorld || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player)) + if (!player.getAbilities().mayBuild || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player)) { return false; } @@ -59,14 +59,14 @@ public class BlockRotator return retval; } - public static BlockState alternativeBlockPlacement(Block block, ItemPlacementContext context)//World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) + public static BlockState alternativeBlockPlacement(Block block, BlockPlaceContext context)//World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { //actual alternative block placement code // if (true) throw new UnsupportedOperationException("Alternative Block Placement / client controlled / is not implemnted"); Direction facing; - Vec3d vec3d = context.getHitPos(); + Vec3 vec3d = context.getClickLocation(); float hitX = (float) vec3d.x; if (hitX<2) // vanilla @@ -76,75 +76,75 @@ public class BlockRotator // now it would be great if hitX was adjusted in context to original range from 0.0 to 1.0 // since its actually using it. Its private - maybe with Reflections? // - PlayerEntity placer = context.getPlayer(); - BlockPos pos = context.getBlockPos(); - World world = context.getWorld(); + Player placer = context.getPlayer(); + BlockPos pos = context.getClickedPos(); + Level world = context.getLevel(); if (block instanceof GlazedTerracottaBlock) { - facing = Direction.byId(code); + facing = Direction.from3DDataValue(code); if(facing == Direction.UP || facing == Direction.DOWN) { - facing = placer.getHorizontalFacing().getOpposite(); + facing = placer.getDirection().getOpposite(); } - return block.getDefaultState().with(HorizontalFacingBlock.FACING, facing); + return block.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, facing); } else if (block instanceof ObserverBlock) { - return block.getDefaultState() - .with(FacingBlock.FACING, Direction.byId(code)) - .with(ObserverBlock.POWERED, true); + return block.defaultBlockState() + .setValue(DirectionalBlock.FACING, Direction.from3DDataValue(code)) + .setValue(ObserverBlock.POWERED, true); } else if (block instanceof RepeaterBlock) { - facing = Direction.byId(code % 16); + facing = Direction.from3DDataValue(code % 16); if(facing == Direction.UP || facing == Direction.DOWN) { - facing = placer.getHorizontalFacing().getOpposite(); + facing = placer.getDirection().getOpposite(); } - return block.getDefaultState() - .with(HorizontalFacingBlock.FACING, facing) - .with(RepeaterBlock.DELAY, MathHelper.clamp(code / 16, 1, 4)) - .with(RepeaterBlock.LOCKED, Boolean.FALSE); + return block.defaultBlockState() + .setValue(HorizontalDirectionalBlock.FACING, facing) + .setValue(RepeaterBlock.DELAY, Mth.clamp(code / 16, 1, 4)) + .setValue(RepeaterBlock.LOCKED, Boolean.FALSE); } - else if (block instanceof TrapdoorBlock) + else if (block instanceof TrapDoorBlock) { - return block.getDefaultState() - .with(TrapdoorBlock.FACING, Direction.byId(code % 16)) - .with(TrapdoorBlock.OPEN, Boolean.FALSE) - .with(TrapdoorBlock.HALF, (code >= 16) ? BlockHalf.TOP : BlockHalf.BOTTOM) - .with(TrapdoorBlock.OPEN, world.isReceivingRedstonePower(pos)); + return block.defaultBlockState() + .setValue(TrapDoorBlock.FACING, Direction.from3DDataValue(code % 16)) + .setValue(TrapDoorBlock.OPEN, Boolean.FALSE) + .setValue(TrapDoorBlock.HALF, (code >= 16) ? Half.TOP : Half.BOTTOM) + .setValue(TrapDoorBlock.OPEN, world.hasNeighborSignal(pos)); } else if (block instanceof ComparatorBlock) { - facing = Direction.byId(code % 16); + facing = Direction.from3DDataValue(code % 16); if((facing == Direction.UP) || (facing == Direction.DOWN)) { - facing = placer.getHorizontalFacing().getOpposite(); + facing = placer.getDirection().getOpposite(); } ComparatorMode m = (hitX >= 16)?ComparatorMode.SUBTRACT: ComparatorMode.COMPARE; - return block.getDefaultState() - .with(HorizontalFacingBlock.FACING, facing) - .with(ComparatorBlock.POWERED, Boolean.FALSE) - .with(ComparatorBlock.MODE, m); + return block.defaultBlockState() + .setValue(HorizontalDirectionalBlock.FACING, facing) + .setValue(ComparatorBlock.POWERED, Boolean.FALSE) + .setValue(ComparatorBlock.MODE, m); } else if (block instanceof DispenserBlock) { - return block.getDefaultState() - .with(DispenserBlock.FACING, Direction.byId(code)) - .with(DispenserBlock.TRIGGERED, Boolean.FALSE); + return block.defaultBlockState() + .setValue(DispenserBlock.FACING, Direction.from3DDataValue(code)) + .setValue(DispenserBlock.TRIGGERED, Boolean.FALSE); } - else if (block instanceof PistonBlock) + else if (block instanceof PistonBaseBlock) { - return block.getDefaultState() - .with(FacingBlock.FACING, Direction.byId(code)) - .with(PistonBlock.EXTENDED, Boolean.FALSE); + return block.defaultBlockState() + .setValue(DirectionalBlock.FACING, Direction.from3DDataValue(code)) + .setValue(PistonBaseBlock.EXTENDED, Boolean.FALSE); } - else if (block instanceof StairsBlock) + else if (block instanceof StairBlock) { - return block.getPlacementState(context)//worldIn, pos, facing, hitX, hitY, hitZ, meta, placer) - .with(StairsBlock.FACING, Direction.byId(code % 16)) - .with(StairsBlock.HALF, ( hitX >= 16)?BlockHalf.TOP : BlockHalf.BOTTOM); + return block.getStateForPlacement(context)//worldIn, pos, facing, hitX, hitY, hitZ, meta, placer) + .setValue(StairBlock.FACING, Direction.from3DDataValue(code % 16)) + .setValue(StairBlock.HALF, ( hitX >= 16)?Half.TOP : Half.BOTTOM); } return null; } @@ -222,109 +222,109 @@ public class BlockRotator } } - public static ItemStack dispenserRotate(BlockPointer source, ItemStack stack) + public static ItemStack dispenserRotate(BlockSource source, ItemStack stack) { - Direction sourceFace = source.getBlockState().get(DispenserBlock.FACING); - World world = source.getWorld(); - BlockPos blockpos = source.getPos().offset(sourceFace); // offset + Direction sourceFace = source.getBlockState().getValue(DispenserBlock.FACING); + Level world = source.getLevel(); + BlockPos blockpos = source.getPos().relative(sourceFace); // offset BlockState iblockstate = world.getBlockState(blockpos); Block block = iblockstate.getBlock(); // Block rotation for blocks that can be placed in all 6 or 4 rotations. - if(block instanceof FacingBlock || block instanceof DispenserBlock) + if(block instanceof DirectionalBlock || block instanceof DispenserBlock) { - Direction face = iblockstate.get(FacingBlock.FACING); - if (block instanceof PistonBlock && ( - iblockstate.get(PistonBlock.EXTENDED) - || ( ((PistonBlockInterface)block).publicShouldExtend(world, blockpos, face) && (new PistonHandler(world, blockpos, face, true)).calculatePush() ) + Direction face = iblockstate.getValue(DirectionalBlock.FACING); + if (block instanceof PistonBaseBlock && ( + iblockstate.getValue(PistonBaseBlock.EXTENDED) + || ( ((PistonBlockInterface)block).publicShouldExtend(world, blockpos, face) && (new PistonStructureResolver(world, blockpos, face, true)).resolve() ) ) ) return stack; Direction rotated_face = rotateClockwise(face, sourceFace.getAxis()); - if(sourceFace.getId() % 2 == 0 || rotated_face == face) + if(sourceFace.get3DDataValue() % 2 == 0 || rotated_face == face) { // Flip to make blocks always rotate clockwise relative to the dispenser // when index is equal to zero. when index is equal to zero the dispenser is in the opposite direction. rotated_face = rotated_face.getOpposite(); } - world.setBlockState(blockpos, iblockstate.with(FacingBlock.FACING, rotated_face), 3); + world.setBlock(blockpos, iblockstate.setValue(DirectionalBlock.FACING, rotated_face), 3); } - else if(block instanceof HorizontalFacingBlock) // Block rotation for blocks that can be placed in only 4 horizontal rotations. + else if(block instanceof HorizontalDirectionalBlock) // Block rotation for blocks that can be placed in only 4 horizontal rotations. { if (block instanceof BedBlock) return stack; - Direction face = iblockstate.get(HorizontalFacingBlock.FACING); + Direction face = iblockstate.getValue(HorizontalDirectionalBlock.FACING); face = rotateClockwise(face, Direction.Axis.Y); if(sourceFace == Direction.DOWN) { // same as above. face = face.getOpposite(); } - world.setBlockState(blockpos, iblockstate.with(HorizontalFacingBlock.FACING, face), 3); + world.setBlock(blockpos, iblockstate.setValue(HorizontalDirectionalBlock.FACING, face), 3); } else if(block == Blocks.HOPPER ) { - Direction face = iblockstate.get(HopperBlock.FACING); + Direction face = iblockstate.getValue(HopperBlock.FACING); if (face != Direction.DOWN) { face = rotateClockwise(face, Direction.Axis.Y); - world.setBlockState(blockpos, iblockstate.with(HopperBlock.FACING, face), 3); + world.setBlock(blockpos, iblockstate.setValue(HopperBlock.FACING, face), 3); } } // Send block update to the block that just have been rotated. - world.updateNeighbor(blockpos, block, source.getPos()); + world.neighborChanged(blockpos, block, source.getPos()); return stack; } - public static boolean flip_block(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit) + public static boolean flip_block(BlockState state, Level world, Player player, InteractionHand hand, BlockHitResult hit) { Block block = state.getBlock(); BlockPos pos = hit.getBlockPos(); - Vec3d hitVec = hit.getPos().subtract(pos.getX(), pos.getY(), pos.getZ()); - Direction facing = hit.getSide(); + Vec3 hitVec = hit.getLocation().subtract(pos.getX(), pos.getY(), pos.getZ()); + Direction facing = hit.getDirection(); BlockState newState = null; - if ( (block instanceof GlazedTerracottaBlock) || (block instanceof AbstractRedstoneGateBlock) || (block instanceof AbstractRailBlock) || - (block instanceof TrapdoorBlock) || (block instanceof LeverBlock) || (block instanceof FenceGateBlock)) + if ( (block instanceof GlazedTerracottaBlock) || (block instanceof DiodeBlock) || (block instanceof BaseRailBlock) || + (block instanceof TrapDoorBlock) || (block instanceof LeverBlock) || (block instanceof FenceGateBlock)) { - newState = state.rotate(BlockRotation.CLOCKWISE_90); + newState = state.rotate(Rotation.CLOCKWISE_90); } else if ((block instanceof ObserverBlock) || (block instanceof EndRodBlock)) { - newState = state.with(FacingBlock.FACING, state.get(FacingBlock.FACING).getOpposite()); + newState = state.setValue(DirectionalBlock.FACING, state.getValue(DirectionalBlock.FACING).getOpposite()); } else if (block instanceof DispenserBlock) { - newState = state.with(DispenserBlock.FACING, state.get(DispenserBlock.FACING).getOpposite()); + newState = state.setValue(DispenserBlock.FACING, state.getValue(DispenserBlock.FACING).getOpposite()); } - else if (block instanceof PistonBlock) + else if (block instanceof PistonBaseBlock) { - if (!(state.get(PistonBlock.EXTENDED))) - newState = state.with(FacingBlock.FACING, state.get(FacingBlock.FACING).getOpposite()); + if (!(state.getValue(PistonBaseBlock.EXTENDED))) + newState = state.setValue(DirectionalBlock.FACING, state.getValue(DirectionalBlock.FACING).getOpposite()); } else if (block instanceof SlabBlock) { - if (((SlabBlock) block).hasSidedTransparency(state)) + if (((SlabBlock) block).useShapeForLightOcclusion(state)) { - newState = state.with(SlabBlock.TYPE, state.get(SlabBlock.TYPE) == SlabType.TOP ? SlabType.BOTTOM : SlabType.TOP); + newState = state.setValue(SlabBlock.TYPE, state.getValue(SlabBlock.TYPE) == SlabType.TOP ? SlabType.BOTTOM : SlabType.TOP); } } else if (block instanceof HopperBlock) { - if (state.get(HopperBlock.FACING) != Direction.DOWN) + if (state.getValue(HopperBlock.FACING) != Direction.DOWN) { - newState = state.with(HopperBlock.FACING, state.get(HopperBlock.FACING).rotateYClockwise()); + newState = state.setValue(HopperBlock.FACING, state.getValue(HopperBlock.FACING).getClockWise()); } } - else if (block instanceof StairsBlock) + else if (block instanceof StairBlock) { //LOG.error(String.format("hit with facing: %s, at side %.1fX, X %.1fY, Y %.1fZ",facing, hitX, hitY, hitZ)); if ((facing == Direction.UP && hitVec.y == 1.0f) || (facing == Direction.DOWN && hitVec.y == 0.0f)) { - newState = state.with(StairsBlock.HALF, state.get(StairsBlock.HALF) == BlockHalf.TOP ? BlockHalf.BOTTOM : BlockHalf.TOP ); + newState = state.setValue(StairBlock.HALF, state.getValue(StairBlock.HALF) == Half.TOP ? Half.BOTTOM : Half.TOP ); } else { @@ -351,25 +351,25 @@ public class BlockRotator } if (turn_right) { - newState = state.rotate(BlockRotation.COUNTERCLOCKWISE_90); + newState = state.rotate(Rotation.COUNTERCLOCKWISE_90); } else { - newState = state.rotate(BlockRotation.CLOCKWISE_90); + newState = state.rotate(Rotation.CLOCKWISE_90); } } } - else if (block instanceof PillarBlock) + else if (block instanceof RotatedPillarBlock) { - switch((Direction.Axis)state.get(PillarBlock.AXIS)) { + switch((Direction.Axis)state.getValue(RotatedPillarBlock.AXIS)) { case X: - newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.Z); + newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.Z); break; case Z: - newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.Y); + newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.Y); break; case Y: - newState = (BlockState)state.with(PillarBlock.AXIS, Direction.Axis.X); + newState = (BlockState)state.setValue(RotatedPillarBlock.AXIS, Direction.Axis.X); break; } } @@ -379,34 +379,34 @@ public class BlockRotator } if (newState != null) { - world.setBlockState(pos, newState, 2 | 1024); - world.scheduleBlockRerenderIfNeeded(pos, state, newState); + world.setBlock(pos, newState, 2 | 1024); + world.setBlocksDirty(pos, state, newState); return true; } return false; } - private static boolean player_holds_cactus_mainhand(PlayerEntity playerIn) + private static boolean player_holds_cactus_mainhand(Player playerIn) { - return (!playerIn.getMainHandStack().isEmpty() - && playerIn.getMainHandStack().getItem() instanceof BlockItem && - ((BlockItem) (playerIn.getMainHandStack().getItem())).getBlock() == Blocks.CACTUS); + return (!playerIn.getMainHandItem().isEmpty() + && playerIn.getMainHandItem().getItem() instanceof BlockItem && + ((BlockItem) (playerIn.getMainHandItem().getItem())).getBlock() == Blocks.CACTUS); } public static boolean flippinEligibility(Entity entity) { - if (CarpetSettings.flippinCactus && (entity instanceof PlayerEntity)) + if (CarpetSettings.flippinCactus && (entity instanceof Player)) { - PlayerEntity player = (PlayerEntity)entity; - return (!player.getOffHandStack().isEmpty() - && player.getOffHandStack().getItem() instanceof BlockItem && - ((BlockItem) (player.getOffHandStack().getItem())).getBlock() == Blocks.CACTUS); + Player player = (Player)entity; + return (!player.getOffhandItem().isEmpty() + && player.getOffhandItem().getItem() instanceof BlockItem && + ((BlockItem) (player.getOffhandItem().getItem())).getBlock() == Blocks.CACTUS); } return false; } - public static class CactusDispenserBehaviour extends FallibleItemDispenserBehavior implements DispenserBehavior + public static class CactusDispenserBehaviour extends OptionalDispenseItemBehavior implements DispenseItemBehavior { @Override - protected ItemStack dispenseSilently(BlockPointer source, ItemStack stack) + protected ItemStack execute(BlockSource source, ItemStack stack) { if (CarpetSettings.rotatorBlock) { @@ -414,7 +414,7 @@ public class BlockRotator } else { - return super.dispenseSilently(source, stack); + return super.execute(source, stack); } } } diff --git a/src/main/java/carpet/helpers/BlockSaplingHelper.java b/src/main/java/carpet/helpers/BlockSaplingHelper.java index 90a303fd..8b70c5f7 100644 --- a/src/main/java/carpet/helpers/BlockSaplingHelper.java +++ b/src/main/java/carpet/helpers/BlockSaplingHelper.java @@ -1,15 +1,15 @@ package carpet.helpers; -import net.minecraft.block.Material; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.material.Material; public class BlockSaplingHelper { // Added code for checking water for dead shrub rule - public static boolean hasWater(WorldAccess worldIn, BlockPos pos) + public static boolean hasWater(LevelAccessor worldIn, BlockPos pos) { - for (BlockPos blockpos$mutableblockpos : BlockPos.iterate(pos.add(-4, -4, -4), pos.add(4, 1, 4))) + for (BlockPos blockpos$mutableblockpos : BlockPos.betweenClosed(pos.offset(-4, -4, -4), pos.offset(4, 1, 4))) { if (worldIn.getBlockState(blockpos$mutableblockpos).getMaterial() == Material.WATER) { diff --git a/src/main/java/carpet/helpers/CustomSpawnLists.java b/src/main/java/carpet/helpers/CustomSpawnLists.java index 083ea7a2..bb3ca3da 100644 --- a/src/main/java/carpet/helpers/CustomSpawnLists.java +++ b/src/main/java/carpet/helpers/CustomSpawnLists.java @@ -1,16 +1,16 @@ package carpet.helpers; -import net.minecraft.entity.EntityType; -import net.minecraft.util.collection.Pool; -import net.minecraft.world.biome.SpawnSettings; +import net.minecraft.util.random.WeightedRandomList; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.biome.MobSpawnSettings; public class CustomSpawnLists { - public static final Pool PYRAMID_SPAWNS = Pool.of(new SpawnSettings.SpawnEntry(EntityType.HUSK, 1, 1, 1)); - public static final Pool SHULKER_SPAWNS = Pool.of(new SpawnSettings.SpawnEntry(EntityType.SHULKER, 10, 4, 4)); - public static final Pool BASTION_SPAWNS = Pool.of( - new SpawnSettings.SpawnEntry(EntityType.PIGLIN_BRUTE, 5, 1, 2), - new SpawnSettings.SpawnEntry(EntityType.PIGLIN, 10, 2, 4), - new SpawnSettings.SpawnEntry(EntityType.HOGLIN, 2, 1, 2) + public static final WeightedRandomList PYRAMID_SPAWNS = WeightedRandomList.create(new MobSpawnSettings.SpawnerData(EntityType.HUSK, 1, 1, 1)); + public static final WeightedRandomList SHULKER_SPAWNS = WeightedRandomList.create(new MobSpawnSettings.SpawnerData(EntityType.SHULKER, 10, 4, 4)); + public static final WeightedRandomList BASTION_SPAWNS = WeightedRandomList.create( + new MobSpawnSettings.SpawnerData(EntityType.PIGLIN_BRUTE, 5, 1, 2), + new MobSpawnSettings.SpawnerData(EntityType.PIGLIN, 10, 2, 4), + new MobSpawnSettings.SpawnerData(EntityType.HOGLIN, 2, 1, 2) ); } diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 2cfa2b37..345bf784 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -1,38 +1,37 @@ package carpet.helpers; import carpet.fakes.ServerPlayerEntityInterface; -import net.minecraft.block.BlockState; -import net.minecraft.command.argument.EntityAnchorArgumentType; -import net.minecraft.entity.Entity; -import net.minecraft.entity.decoration.ItemFrameEntity; -import net.minecraft.entity.passive.HorseBaseEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.entity.vehicle.BoatEntity; -import net.minecraft.entity.vehicle.MinecartEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.network.packet.s2c.play.UpdateSelectedSlotS2CPacket; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.math.Vec3d; - import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; +import net.minecraft.commands.arguments.EntityAnchorArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.animal.horse.AbstractHorse; +import net.minecraft.world.entity.decoration.ItemFrame; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.vehicle.Boat; +import net.minecraft.world.entity.vehicle.Minecart; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; public class EntityPlayerActionPack { - private final ServerPlayerEntity player; + private final ServerPlayer player; private final Map actions = new TreeMap<>(); @@ -48,7 +47,7 @@ public class EntityPlayerActionPack private int itemUseCooldown; - public EntityPlayerActionPack(ServerPlayerEntity playerIn) + public EntityPlayerActionPack(ServerPlayer playerIn) { player = playerIn; stopAll(); @@ -84,7 +83,7 @@ public class EntityPlayerActionPack public EntityPlayerActionPack setSneaking(boolean doSneak) { sneaking = doSneak; - player.setSneaking(doSneak); + player.setShiftKeyDown(doSneak); if (sprinting && sneaking) setSprinting(false); return this; @@ -116,36 +115,36 @@ public class EntityPlayerActionPack case SOUTH: return look(0, 0); case EAST: return look(-90, 0); case WEST: return look(90, 0); - case UP: return look(player.getYaw(), -90); - case DOWN: return look(player.getYaw(), 90); + case UP: return look(player.getYRot(), -90); + case DOWN: return look(player.getYRot(), 90); } return this; } - public EntityPlayerActionPack look(Vec2f rotation) + public EntityPlayerActionPack look(Vec2 rotation) { return look(rotation.x, rotation.y); } public EntityPlayerActionPack look(float yaw, float pitch) { - player.setYaw(yaw % 360); //setYaw - player.setPitch(MathHelper.clamp(pitch, -90, 90)); // setPitch + player.setYRot(yaw % 360); //setYaw + player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch // maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F)); return this; } - public EntityPlayerActionPack lookAt(Vec3d position) + public EntityPlayerActionPack lookAt(Vec3 position) { - player.lookAt(EntityAnchorArgumentType.EntityAnchor.EYES, position); + player.lookAt(EntityAnchorArgument.Anchor.EYES, position); return this; } public EntityPlayerActionPack turn(float yaw, float pitch) { - return look(player.getYaw() + yaw, player.getPitch() + pitch); + return look(player.getYRot() + yaw, player.getXRot() + pitch); } - public EntityPlayerActionPack turn(Vec2f rotation) + public EntityPlayerActionPack turn(Vec2 rotation) { return turn(rotation.x, rotation.y); } @@ -173,12 +172,12 @@ public class EntityPlayerActionPack List entities; if (onlyRideables) { - entities = player.world.getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D), - e -> e instanceof MinecartEntity || e instanceof BoatEntity || e instanceof HorseBaseEntity); + entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D), + e -> e instanceof Minecart || e instanceof Boat || e instanceof AbstractHorse); } else { - entities = player.world.getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D)); + entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D)); } if (entities.size()==0) return this; @@ -189,7 +188,7 @@ public class EntityPlayerActionPack { if (e == player || (currentVehicle == e)) continue; - double dd = player.squaredDistanceTo(e); + double dd = player.distanceToSqr(e); if (dd= 0; i--) + for (int i = inv.getContainerSize(); i >= 0; i--) dropItemFromSlot(i, dropAll); } else // one slot { if (selectedSlot == -1) - selectedSlot = inv.selectedSlot; + selectedSlot = inv.selected; dropItemFromSlot(selectedSlot, dropAll); } } public void setSlot(int slot) { - player.getInventory().selectedSlot = slot-1; - player.networkHandler.sendPacket(new UpdateSelectedSlotS2CPacket(slot-1)); + player.getInventory().selected = slot-1; + player.connection.send(new ClientboundSetCarriedItemPacket(slot-1)); } public enum ActionType @@ -288,7 +287,7 @@ public class EntityPlayerActionPack USE(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) + boolean execute(ServerPlayer player, Action action) { EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); if (ap.itemUseCooldown > 0) @@ -301,23 +300,23 @@ public class EntityPlayerActionPack return true; } HitResult hit = getTarget(player); - for (Hand hand : Hand.values()) + for (InteractionHand hand : InteractionHand.values()) { switch (hit.getType()) { case BLOCK: { - player.updateLastActionTime(); - ServerWorld world = player.getWorld(); + player.resetLastActionTime(); + ServerLevel world = player.getLevel(); BlockHitResult blockHit = (BlockHitResult) hit; BlockPos pos = blockHit.getBlockPos(); - Direction side = blockHit.getSide(); - if (pos.getY() < player.getWorld().getTopY() - (side == Direction.UP ? 1 : 0) && world.canPlayerModifyAt(player, pos)) + Direction side = blockHit.getDirection(); + if (pos.getY() < player.getLevel().getMaxBuildHeight() - (side == Direction.UP ? 1 : 0) && world.mayInteract(player, pos)) { - ActionResult result = player.interactionManager.interactBlock(player, world, player.getStackInHand(hand), hand, blockHit); - if (result.isAccepted()) + InteractionResult result = player.gameMode.useItemOn(player, world, player.getItemInHand(hand), hand, blockHit); + if (result.consumesAction()) { - if (result.shouldSwingHand()) player.swingHand(hand); + if (result.shouldSwing()) player.swing(hand); ap.itemUseCooldown = 3; return true; } @@ -326,19 +325,19 @@ public class EntityPlayerActionPack } case ENTITY: { - player.updateLastActionTime(); + player.resetLastActionTime(); EntityHitResult entityHit = (EntityHitResult) hit; Entity entity = entityHit.getEntity(); - boolean handWasEmpty = player.getStackInHand(hand).isEmpty(); - boolean itemFrameEmpty = (entity instanceof ItemFrameEntity) && ((ItemFrameEntity) entity).getHeldItemStack().isEmpty(); - Vec3d relativeHitPos = entityHit.getPos().subtract(entity.getX(), entity.getY(), entity.getZ()); - if (entity.interactAt(player, relativeHitPos, hand).isAccepted()) + boolean handWasEmpty = player.getItemInHand(hand).isEmpty(); + boolean itemFrameEmpty = (entity instanceof ItemFrame) && ((ItemFrame) entity).getItem().isEmpty(); + Vec3 relativeHitPos = entityHit.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); + if (entity.interactAt(player, relativeHitPos, hand).consumesAction()) { ap.itemUseCooldown = 3; return true; } // fix for SS itemframe always returns CONSUME even if no action is performed - if (player.interact(entity, hand).isAccepted() && !(handWasEmpty && itemFrameEmpty)) + if (player.interactOn(entity, hand).consumesAction() && !(handWasEmpty && itemFrameEmpty)) { ap.itemUseCooldown = 3; return true; @@ -346,8 +345,8 @@ public class EntityPlayerActionPack break; } } - ItemStack handItem = player.getStackInHand(hand); - if (player.interactionManager.interactItem(player, player.getWorld(), handItem, hand).isAccepted()) + ItemStack handItem = player.getItemInHand(hand); + if (player.gameMode.useItem(player, player.getLevel(), handItem, hand).consumesAction()) { ap.itemUseCooldown = 3; return true; @@ -357,16 +356,16 @@ public class EntityPlayerActionPack } @Override - void inactiveTick(ServerPlayerEntity player, Action action) + void inactiveTick(ServerPlayer player, Action action) { EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); ap.itemUseCooldown = 0; - player.stopUsingItem(); + player.releaseUsingItem(); } }, ATTACK(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) { + boolean execute(ServerPlayer player, Action action) { HitResult hit = getTarget(player); switch (hit.getType()) { case ENTITY: { @@ -374,10 +373,10 @@ public class EntityPlayerActionPack if (!action.isContinuous) { player.attack(entityHit.getEntity()); - player.swingHand(Hand.MAIN_HAND); + player.swing(InteractionHand.MAIN_HAND); } - player.resetLastAttackedTicks(); - player.updateLastActionTime(); + player.resetAttackStrengthTicker(); + player.resetLastActionTime(); return true; } case BLOCK: { @@ -389,18 +388,18 @@ public class EntityPlayerActionPack } BlockHitResult blockHit = (BlockHitResult) hit; BlockPos pos = blockHit.getBlockPos(); - Direction side = blockHit.getSide(); - if (player.isBlockBreakingRestricted(player.world, pos, player.interactionManager.getGameMode())) return false; - if (ap.currentBlock != null && player.world.getBlockState(ap.currentBlock).isAir()) + Direction side = blockHit.getDirection(); + if (player.blockActionRestricted(player.level, pos, player.gameMode.getGameModeForPlayer())) return false; + if (ap.currentBlock != null && player.level.getBlockState(ap.currentBlock).isAir()) { ap.currentBlock = null; return false; } - BlockState state = player.world.getBlockState(pos); + BlockState state = player.level.getBlockState(pos); boolean blockBroken = false; - if (player.interactionManager.getGameMode().isCreative()) + if (player.gameMode.getGameModeForPlayer().isCreative()) { - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY()); + player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight()); ap.blockHitDelay = 5; blockBroken = true; } @@ -408,15 +407,15 @@ public class EntityPlayerActionPack { if (ap.currentBlock != null) { - player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.getWorld().getTopY()); + player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight()); } - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY()); + player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight()); boolean notAir = !state.isAir(); if (notAir && ap.curBlockDamageMP == 0) { - state.onBlockBreakStart(player.world, pos, player); + state.attack(player.level, pos, player); } - if (notAir && state.calcBlockBreakingDelta(player, player.world, pos) >= 1) + if (notAir && state.getDestroyProgress(player, player.level, pos) >= 1) { ap.currentBlock = null; //instamine?? @@ -430,19 +429,19 @@ public class EntityPlayerActionPack } else { - ap.curBlockDamageMP += state.calcBlockBreakingDelta(player, player.world, pos); + ap.curBlockDamageMP += state.getDestroyProgress(player, player.level, pos); if (ap.curBlockDamageMP >= 1) { - player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.getWorld().getTopY()); + player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight()); ap.currentBlock = null; ap.blockHitDelay = 5; blockBroken = true; } - player.world.setBlockBreakingInfo(-1, pos, (int) (ap.curBlockDamageMP * 10)); + player.level.destroyBlockProgress(-1, pos, (int) (ap.curBlockDamageMP * 10)); } - player.updateLastActionTime(); - player.swingHand(Hand.MAIN_HAND); + player.resetLastActionTime(); + player.swing(InteractionHand.MAIN_HAND); return blockBroken; } } @@ -450,23 +449,23 @@ public class EntityPlayerActionPack } @Override - void inactiveTick(ServerPlayerEntity player, Action action) + void inactiveTick(ServerPlayer player, Action action) { EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); if (ap.currentBlock == null) return; - player.world.setBlockBreakingInfo(-1, ap.currentBlock, -1); - player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopY()); + player.level.destroyBlockProgress(-1, ap.currentBlock, -1); + player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getLevel().getMaxBuildHeight()); ap.currentBlock = null; } }, JUMP(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) + boolean execute(ServerPlayer player, Action action) { if (action.limit == 1) { - if (player.isOnGround()) player.jump(); // onGround + if (player.isOnGround()) player.jumpFromGround(); // onGround } else { @@ -476,7 +475,7 @@ public class EntityPlayerActionPack } @Override - void inactiveTick(ServerPlayerEntity player, Action action) + void inactiveTick(ServerPlayer player, Action action) { player.setJumping(false); } @@ -484,32 +483,32 @@ public class EntityPlayerActionPack DROP_ITEM(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) + boolean execute(ServerPlayer player, Action action) { - player.updateLastActionTime(); - player.dropSelectedItem(false); // dropSelectedItem + player.resetLastActionTime(); + player.drop(false); // dropSelectedItem return false; } }, DROP_STACK(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) + boolean execute(ServerPlayer player, Action action) { - player.updateLastActionTime(); - player.dropSelectedItem(true); // dropSelectedItem + player.resetLastActionTime(); + player.drop(true); // dropSelectedItem return false; } }, SWAP_HANDS(true) { @Override - boolean execute(ServerPlayerEntity player, Action action) + boolean execute(ServerPlayer player, Action action) { - player.updateLastActionTime(); - ItemStack itemStack_1 = player.getStackInHand(Hand.OFF_HAND); - player.setStackInHand(Hand.OFF_HAND, player.getStackInHand(Hand.MAIN_HAND)); - player.setStackInHand(Hand.MAIN_HAND, itemStack_1); + player.resetLastActionTime(); + ItemStack itemStack_1 = player.getItemInHand(InteractionHand.OFF_HAND); + player.setItemInHand(InteractionHand.OFF_HAND, player.getItemInHand(InteractionHand.MAIN_HAND)); + player.setItemInHand(InteractionHand.MAIN_HAND, itemStack_1); return false; } }; @@ -521,10 +520,10 @@ public class EntityPlayerActionPack this.preventSpectator = preventSpectator; } - void start(ServerPlayerEntity player, Action action) {} - abstract boolean execute(ServerPlayerEntity player, Action action); - void inactiveTick(ServerPlayerEntity player, Action action) {} - void stop(ServerPlayerEntity player, Action action) + void start(ServerPlayer player, Action action) {} + abstract boolean execute(ServerPlayer player, Action action); + void inactiveTick(ServerPlayer player, Action action) {} + void stop(ServerPlayer player, Action action) { inactiveTick(player, action); } diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/helpers/FeatureGenerator.java index 41410554..9be0898a 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/helpers/FeatureGenerator.java @@ -4,80 +4,81 @@ import carpet.CarpetSettings; import carpet.fakes.ChunkGeneratorInterface; import carpet.fakes.PlacedFeatureInterface; import carpet.fakes.StructureFeatureInterface; +import com.google.common.collect.ImmutableCollection; +import com.google.common.collect.ImmutableMultimap; import com.mojang.datafixers.util.Pair; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.structure.StructureStart; -import net.minecraft.structure.pool.StructurePool; -import net.minecraft.structure.pool.StructurePoolElement; -import net.minecraft.structure.processor.StructureProcessorLists; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.intprovider.ConstantIntProvider; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.StructurePresence; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.BiomeKeys; -import net.minecraft.world.biome.BuiltinBiomes; -import net.minecraft.world.gen.StructureAccessor; -import net.minecraft.world.gen.chunk.StructuresConfig; -import net.minecraft.world.gen.feature.ConfiguredStructureFeatures; -import net.minecraft.world.gen.feature.PlacedFeature; -import net.minecraft.world.gen.feature.size.TwoLayersFeatureSize; -import net.minecraft.world.gen.foliage.BlobFoliagePlacer; -import net.minecraft.world.gen.foliage.LargeOakFoliagePlacer; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.chunk.StructureConfig; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.gen.feature.ConfiguredStructureFeature; -import net.minecraft.world.gen.feature.Feature; -import net.minecraft.world.gen.feature.FeatureConfig; -import net.minecraft.world.gen.feature.SimpleRandomFeatureConfig; -import net.minecraft.world.gen.feature.StructureFeature; -import net.minecraft.world.gen.feature.StructurePoolFeatureConfig; -import net.minecraft.world.gen.feature.TreeFeatureConfig; -import net.minecraft.world.gen.stateprovider.BlockStateProvider; -import net.minecraft.world.gen.treedecorator.BeehiveTreeDecorator; -import net.minecraft.world.gen.trunk.LargeOakTrunkPlacer; -import net.minecraft.world.gen.trunk.StraightTrunkPlacer; - import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.OptionalInt; import java.util.function.Supplier; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.data.worldgen.ProcessorLists; +import net.minecraft.data.worldgen.StructureFeatures; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.valueproviders.ConstantInt; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.StructureFeatureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.StructureSettings; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import net.minecraft.world.level.levelgen.feature.configurations.JigsawConfiguration; +import net.minecraft.world.level.levelgen.feature.configurations.SimpleRandomFeatureConfiguration; +import net.minecraft.world.level.levelgen.feature.configurations.StructureFeatureConfiguration; +import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration; +import net.minecraft.world.level.levelgen.feature.featuresize.TwoLayersFeatureSize; +import net.minecraft.world.level.levelgen.feature.foliageplacers.BlobFoliagePlacer; +import net.minecraft.world.level.levelgen.feature.foliageplacers.FancyFoliagePlacer; +import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; +import net.minecraft.world.level.levelgen.feature.structures.StructurePoolElement; +import net.minecraft.world.level.levelgen.feature.structures.StructureTemplatePool; +import net.minecraft.world.level.levelgen.feature.treedecorators.BeehiveDecorator; +import net.minecraft.world.level.levelgen.feature.trunkplacers.FancyTrunkPlacer; +import net.minecraft.world.level.levelgen.feature.trunkplacers.StraightTrunkPlacer; +import net.minecraft.world.level.levelgen.placement.PlacedFeature; +import net.minecraft.world.level.levelgen.structure.StructureCheckResult; +import net.minecraft.world.level.levelgen.structure.StructureStart; public class FeatureGenerator { public static final Object boo = new Object(); - synchronized public static Boolean plop(String featureName, ServerWorld world, BlockPos pos) + synchronized public static Boolean plop(String featureName, ServerLevel world, BlockPos pos) { Thing custom = featureMap.get(featureName); if (custom != null) { return custom.plop(world, pos); } - Identifier id = new Identifier(featureName); - ConfiguredStructureFeature structureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id); + ResourceLocation id = new ResourceLocation(featureName); + ConfiguredStructureFeature structureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id); if (structureFeature != null) { return ((StructureFeatureInterface)structureFeature.feature).plopAnywhere( - world, pos, world.getChunkManager().getChunkGenerator(), - false, world.getRegistryManager().get(Registry.BIOME_KEY).get(BiomeKeys.PLAINS), structureFeature.config); + world, pos, world.getChunkSource().getGenerator(), + false, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(Biomes.PLAINS), structureFeature.config); } - ConfiguredFeature configuredFeature = world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY).get(id); + ConfiguredFeature configuredFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).get(id); if (configuredFeature != null) { CarpetSettings.skipGenerationChecks.set(true); try { - return configuredFeature.generate(world, world.getChunkManager().getChunkGenerator(), world.random, pos); + return configuredFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { @@ -90,8 +91,8 @@ public class FeatureGenerator ConfiguredStructureFeature configuredStandard = getDefaultFeature(structure, world, pos, true); if (configuredStandard != null) return ((StructureFeatureInterface)configuredStandard.feature).plopAnywhere( - world, pos, world.getChunkManager().getChunkGenerator(), - false, world.getRegistryManager().get(Registry.BIOME_KEY).get(BiomeKeys.PLAINS), configuredStandard.config); + world, pos, world.getChunkSource().getGenerator(), + false, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(Biomes.PLAINS), configuredStandard.config); } Feature feature = Registry.FEATURE.get(id); @@ -103,7 +104,7 @@ public class FeatureGenerator CarpetSettings.skipGenerationChecks.set(true); try { - return configuredStandard.generate(world, world.getChunkManager().getChunkGenerator(), world.random, pos); + return configuredStandard.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { @@ -114,27 +115,27 @@ public class FeatureGenerator return null; } - public static ConfiguredStructureFeature resolveConfiguredStructure(String name, ServerWorld world, BlockPos pos) + public static ConfiguredStructureFeature resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos) { - Identifier id = new Identifier(name); - ConfiguredStructureFeature configuredStructureFeature = world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).get(id); + ResourceLocation id = new ResourceLocation(name); + ConfiguredStructureFeature configuredStructureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id); if (configuredStructureFeature != null) return configuredStructureFeature; StructureFeature structureFeature = Registry.STRUCTURE_FEATURE.get(id); if (structureFeature == null) return null; return getDefaultFeature(structureFeature, world, pos, true); } - synchronized public static Boolean plopGrid(ConfiguredStructureFeature structureFeature, ServerWorld world, BlockPos pos) + synchronized public static Boolean plopGrid(ConfiguredStructureFeature structureFeature, ServerLevel world, BlockPos pos) { return ((StructureFeatureInterface)structureFeature.feature).plopAnywhere( - world, pos, world.getChunkManager().getChunkGenerator(), - true, BuiltinBiomes.PLAINS, structureFeature.config); + world, pos, world.getChunkSource().getGenerator(), + true, net.minecraft.data.worldgen.biome.Biomes.PLAINS, structureFeature.config); } @FunctionalInterface private interface Thing { - Boolean plop(ServerWorld world, BlockPos pos); + Boolean plop(ServerLevel world, BlockPos pos); } private static Thing simplePlop(ConfiguredFeature feature) { @@ -142,7 +143,7 @@ public class FeatureGenerator CarpetSettings.skipGenerationChecks.set(true); try { - return feature.generate(w, w.getChunkManager().getChunkGenerator(), w.random, p); + return feature.place(w, w.getChunkSource().getGenerator(), w.random, p); } finally { @@ -151,45 +152,45 @@ public class FeatureGenerator }; } - private static Thing simpleTree(TreeFeatureConfig config) + private static Thing simpleTree(TreeConfiguration config) { //config.ignoreFluidCheck(); - return simplePlop(Feature.TREE.configure(config)); + return simplePlop(Feature.TREE.configured(config)); } - private static Thing spawnCustomStructure(StructureFeature structure, FeatureConfig conf, RegistryKey biome) + private static Thing spawnCustomStructure(StructureFeature structure, FeatureConfiguration conf, ResourceKey biome) { return setupCustomStructure(structure, conf, biome, false); } - private static Thing setupCustomStructure(StructureFeature structure, FeatureConfig conf, RegistryKey biome, boolean wireOnly) + private static Thing setupCustomStructure(StructureFeature structure, FeatureConfiguration conf, ResourceKey biome, boolean wireOnly) { - return (w, p) -> ((StructureFeatureInterface)structure).plopAnywhere(w, p, w.getChunkManager().getChunkGenerator(), wireOnly, w.getRegistryManager().get(Registry.BIOME_KEY).get(biome), conf); + return (w, p) -> ((StructureFeatureInterface)structure).plopAnywhere(w, p, w.getChunkSource().getGenerator(), wireOnly, w.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(biome), conf); } - public static Boolean spawn(String name, ServerWorld world, BlockPos pos) + public static Boolean spawn(String name, ServerLevel world, BlockPos pos) { if (featureMap.containsKey(name)) return featureMap.get(name).plop(world, pos); return null; } - private static ConfiguredStructureFeature getDefaultFeature(StructureFeature structure, ServerWorld world, BlockPos pos, boolean tryHard) + private static ConfiguredStructureFeature getDefaultFeature(StructureFeature structure, ServerLevel world, BlockPos pos, boolean tryHard) { - var definedStructures = world.getChunkManager().getChunkGenerator().getStructuresConfig().getConfiguredStructureFeature(structure); - var optinalBiome = world.getRegistryManager().get(Registry.BIOME_KEY).getKey(world.getBiome(pos)); + var definedStructures = world.getChunkSource().getGenerator().getSettings().structures(structure); + var optinalBiome = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getResourceKey(world.getBiome(pos)); if (optinalBiome.isPresent()) for (var configureStructure: definedStructures.inverse().get(optinalBiome.get())) if (configureStructure.feature == structure) return configureStructure; if (!tryHard) return null; - return world.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getEntries().stream(). + return world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).entrySet().stream(). filter(cS -> cS.getValue().feature == structure). findFirst().map(Map.Entry::getValue).orElse(null); } - private static ConfiguredFeature getDefaultFeature(Feature feature, ServerWorld world, BlockPos pos, boolean tryHard) + private static ConfiguredFeature getDefaultFeature(Feature feature, ServerLevel world, BlockPos pos, boolean tryHard) { - List>> configuredStepFeatures = world.getBiome(pos).getGenerationSettings().getFeatures(); + List>> configuredStepFeatures = world.getBiome(pos).getGenerationSettings().features(); for (List> step: configuredStepFeatures) for (Supplier provider: step) { @@ -198,38 +199,38 @@ public class FeatureGenerator return configuredFeature; } if (!tryHard) return null; - return world.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY).getEntries().stream(). + return world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).entrySet().stream(). filter(cS -> cS.getValue().feature == feature). findFirst().map(Map.Entry::getValue).orElse(null); } - public static StructureStart shouldStructureStartAt(ServerWorld world, BlockPos pos, StructureFeature structure, boolean computeBox) + public static StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, StructureFeature structure, boolean computeBox) { if (structure == StructureFeature.STRONGHOLD) return shouldStrongholdStartAt(world, pos, computeBox); long seed = world.getSeed(); - ChunkGenerator generator = world.getChunkManager().getChunkGenerator(); - StructuresConfig settings = generator.getStructuresConfig(); - StructureConfig structureConfig = settings.getForType(structure); - var structures = settings.getConfiguredStructureFeature(structure); + ChunkGenerator generator = world.getChunkSource().getGenerator(); + StructureSettings settings = generator.getSettings(); + StructureFeatureConfiguration structureConfig = settings.getConfig(structure); + var structures = settings.structures(structure); if (structureConfig == null || structures.isEmpty()) { return null; } ChunkPos chunkPos = new ChunkPos(pos); Biome biome = world.getBiome(pos); - var biomeRegistry = world.getRegistryManager().get(Registry.BIOME_KEY); + var biomeRegistry = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY); if (structures.values().stream().noneMatch(biomeKey -> biomeRegistry.get(biomeKey) == biome)) { return null; } - ChunkPos chunkPos1 = structure.getStartChunk(structureConfig, seed, chunkPos.x, chunkPos.z); + ChunkPos chunkPos1 = structure.getPotentialFeatureChunk(structureConfig, seed, chunkPos.x, chunkPos.z); if (!chunkPos1.equals(chunkPos)) { return null; } - StructureAccessor structureManager = world.getStructureAccessor(); - StructurePresence isThere = structureManager.getStructurePresence(chunkPos, structure, false); - if (isThere == StructurePresence.START_NOT_PRESENT) + StructureFeatureManager structureManager = world.structureFeatureManager(); + StructureCheckResult isThere = structureManager.checkStructurePresence(chunkPos, structure, false); + if (isThere == StructureCheckResult.START_NOT_PRESENT) { return null; } @@ -238,100 +239,100 @@ public class FeatureGenerator //StructureStart start = structureManager.getStructureStart(ChunkSectionPos.from(chunk), structure, chunk); //if (start != null && start.hasChildren()) //{ - if (!computeBox) return StructureStart.DEFAULT; + if (!computeBox) return StructureStart.INVALID_START; ConfiguredStructureFeature configuredFeature = getDefaultFeature(structure, world, pos, false); if (configuredFeature == null || configuredFeature.config == null) return null; var biomeConfig = structures.get(configuredFeature); - StructureStart filledStructure = configuredFeature.tryPlaceStart(world.getRegistryManager(), generator, generator.getBiomeSource(), - world.getStructureManager(), seed, chunkPos, 0, structureConfig, world, (b) -> biomeRegistry.getKey(b).filter(biomeConfig::contains).isPresent()); - if (filledStructure != null && filledStructure.hasChildren()) + StructureStart filledStructure = configuredFeature.generate(world.registryAccess(), generator, generator.getBiomeSource(), + world.getStructureManager(), seed, chunkPos, 0, structureConfig, world, (b) -> biomeRegistry.getResourceKey(b).filter(biomeConfig::contains).isPresent()); + if (filledStructure != null && filledStructure.isValid()) return filledStructure; return null; } - public static StructureStart shouldStrongholdStartAt(ServerWorld world, BlockPos pos, boolean computeBox) + public static StructureStart shouldStrongholdStartAt(ServerLevel world, BlockPos pos, boolean computeBox) { - ChunkGenerator generator = world.getChunkManager().getChunkGenerator(); - if (world.getRegistryKey() != World.OVERWORLD || !generator.isStrongholdStartingChunk(new ChunkPos(pos))) return null; - if (!computeBox) return StructureStart.DEFAULT; - StructuresConfig settings = generator.getStructuresConfig(); - StructureConfig structureConfig = settings.getForType(StructureFeature.STRONGHOLD); + ChunkGenerator generator = world.getChunkSource().getGenerator(); + if (world.dimension() != Level.OVERWORLD || !generator.hasStronghold(new ChunkPos(pos))) return null; + if (!computeBox) return StructureStart.INVALID_START; + StructureSettings settings = generator.getSettings(); + StructureFeatureConfiguration structureConfig = settings.getConfig(StructureFeature.STRONGHOLD); if (structureConfig != null) { - StructureStart filledStructure = ConfiguredStructureFeatures.STRONGHOLD.tryPlaceStart(world.getRegistryManager(), generator, generator.getBiomeSource(), + StructureStart filledStructure = StructureFeatures.STRONGHOLD.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, structureConfig, world, ((ChunkGeneratorInterface)generator)::canPlaceStrongholdInBiomeCM ); - if (filledStructure != null && filledStructure.hasChildren()) + if (filledStructure != null && filledStructure.isValid()) return filledStructure; } return null; } - private static TreeFeatureConfig.Builder createTree(Block block, Block block2, int i, int j, int k, int l) { - return new TreeFeatureConfig.Builder(BlockStateProvider.of(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.of(block2), new BlobFoliagePlacer(ConstantIntProvider.create(l), ConstantIntProvider.create(0), 3), new TwoLayersFeatureSize(1, 0, 1)); + private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l) { + return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1)); } public static final Map featureMap = new HashMap() {{ - put("oak_bees", simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build())); - put("fancy_oak_bees", simpleTree( (new TreeFeatureConfig.Builder(BlockStateProvider.of(Blocks.OAK_LOG), new LargeOakTrunkPlacer(3, 11, 0), BlockStateProvider.of(Blocks.OAK_LEAVES), new LargeOakFoliagePlacer(ConstantIntProvider.create(2), ConstantIntProvider.create(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build())); - put("birch_bees", simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveTreeDecorator(1.00F))).build())); + put("oak_bees", simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); + put("fancy_oak_bees", simpleTree( (new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(Blocks.OAK_LOG), new FancyTrunkPlacer(3, 11, 0), BlockStateProvider.simple(Blocks.OAK_LEAVES), new FancyFoliagePlacer(ConstantInt.of(2), ConstantInt.of(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); + put("birch_bees", simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); - put("coral_tree", simplePlop(Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT))); - put("coral_claw", simplePlop(Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT))); - put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT))); - put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configure(new SimpleRandomFeatureConfig(List.of( - () -> Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT).withPlacement(), - () -> Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT).withPlacement(), - () -> Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT).withPlacement() + put("coral_tree", simplePlop(Feature.CORAL_TREE.configured(FeatureConfiguration.NONE))); + put("coral_claw", simplePlop(Feature.CORAL_CLAW.configured(FeatureConfiguration.NONE))); + put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configured(FeatureConfiguration.NONE))); + put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configured(new SimpleRandomFeatureConfiguration(List.of( + () -> Feature.CORAL_TREE.configured(FeatureConfiguration.NONE).placed(), + () -> Feature.CORAL_CLAW.configured(FeatureConfiguration.NONE).placed(), + () -> Feature.CORAL_MUSHROOM.configured(FeatureConfiguration.NONE).placed() ))))); put("bastion_remnant_units", spawnCustomStructure( StructureFeature.BASTION_REMNANT, - new StructurePoolFeatureConfig(() -> new StructurePool( - new Identifier("bastion/starts"), - new Identifier("empty"), + new JigsawConfiguration(() -> new StructureTemplatePool( + new ResourceLocation("bastion/starts"), + new ResourceLocation("empty"), List.of( - Pair.of(StructurePoolElement.ofProcessedSingle("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.single("bastion/units/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), - StructurePool.Projection.RIGID + StructureTemplatePool.Projection.RIGID ), 6), - BiomeKeys.NETHER_WASTES + Biomes.NETHER_WASTES )); put("bastion_remnant_hoglin_stable", spawnCustomStructure( StructureFeature.BASTION_REMNANT, - new StructurePoolFeatureConfig(() -> new StructurePool( - new Identifier("bastion/starts"), - new Identifier("empty"), + new JigsawConfiguration(() -> new StructureTemplatePool( + new ResourceLocation("bastion/starts"), + new ResourceLocation("empty"), List.of( - Pair.of(StructurePoolElement.ofProcessedSingle("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.single("bastion/hoglin_stable/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), - StructurePool.Projection.RIGID + StructureTemplatePool.Projection.RIGID ), 6), - BiomeKeys.NETHER_WASTES + Biomes.NETHER_WASTES )); put("bastion_remnant_treasure", spawnCustomStructure( StructureFeature.BASTION_REMNANT, - new StructurePoolFeatureConfig(() -> new StructurePool( - new Identifier("bastion/starts"), - new Identifier("empty"), + new JigsawConfiguration(() -> new StructureTemplatePool( + new ResourceLocation("bastion/starts"), + new ResourceLocation("empty"), List.of( - Pair.of(StructurePoolElement.ofProcessedSingle("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.single("bastion/treasure/big_air_full", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), - StructurePool.Projection.RIGID + StructureTemplatePool.Projection.RIGID ), 6), - BiomeKeys.NETHER_WASTES + Biomes.NETHER_WASTES )); put("bastion_remnant_bridge", spawnCustomStructure( StructureFeature.BASTION_REMNANT, - new StructurePoolFeatureConfig(() -> new StructurePool( - new Identifier("bastion/starts"), - new Identifier("empty"), + new JigsawConfiguration(() -> new StructureTemplatePool( + new ResourceLocation("bastion/starts"), + new ResourceLocation("empty"), List.of( - Pair.of(StructurePoolElement.ofProcessedSingle("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) + Pair.of(StructurePoolElement.single("bastion/bridge/starting_pieces/entrance_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), - StructurePool.Projection.RIGID + StructureTemplatePool.Projection.RIGID ), 6), - BiomeKeys.NETHER_WASTES + Biomes.NETHER_WASTES )); }}; diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index c42efffc..0bf8c1d3 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -7,30 +7,29 @@ import carpet.utils.WoolTool; import carpet.utils.Messenger; import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; -import net.minecraft.block.AbstractBannerBlock; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; -import net.minecraft.block.MapColor; -import net.minecraft.block.Stainable; -import net.minecraft.item.BlockItem; -import net.minecraft.item.DyeItem; -import net.minecraft.item.Items; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeType; -import net.minecraft.text.Style; -import net.minecraft.text.TextColor; -import net.minecraft.util.DyeColor; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.text.BaseText; -import net.minecraft.text.TranslatableText; +import net.minecraft.ChatFormatting; +import net.minecraft.core.Registry; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.TextColor; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.Formatting; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; - +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.DyeItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AbstractBannerBlock; +import net.minecraft.world.level.block.BeaconBeamBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.MaterialColor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -58,7 +57,7 @@ public class HopperCounter * The default display colour of each item, which makes them look nicer when printing the counter contents to the chat */ - public static final TextColor WHITE = TextColor.fromFormatting(Formatting.WHITE); + public static final TextColor WHITE = TextColor.fromLegacyFormat(ChatFormatting.WHITE); static { @@ -100,7 +99,7 @@ public class HopperCounter { startTick = -1; this.color = color; - this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMapColor(),"w ") + color.getName(); + this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMaterialColor(),"w ") + color.getName(); } /** @@ -112,7 +111,7 @@ public class HopperCounter { if (startTick < 0) { - startTick = server.getWorld(World.OVERWORLD).getTime(); //OW + startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW startMillis = System.currentTimeMillis(); } Item item = stack.getItem(); @@ -126,7 +125,7 @@ public class HopperCounter public void reset(MinecraftServer server) { counter.clear(); - startTick = server.getWorld(World.OVERWORLD).getTime(); //OW + startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW startMillis = System.currentTimeMillis(); // pubSubProvider.publish(); } @@ -147,13 +146,13 @@ public class HopperCounter /** * Prints all the counters to chat, nicely formatted, and you can choose whether to diplay in in game time or IRL time */ - public static List formatAll(MinecraftServer server, boolean realtime) + public static List formatAll(MinecraftServer server, boolean realtime) { - List text = new ArrayList<>(); + List text = new ArrayList<>(); for (HopperCounter counter : COUNTERS.values()) { - List temp = counter.format(server, realtime, false); + List temp = counter.format(server, realtime, false); if (temp.size() > 1) { if (!text.isEmpty()) text.add(Messenger.s("")); @@ -171,9 +170,9 @@ public class HopperCounter * Prints a single counter's contents and timings to chat, with the option to keep it short (so no item breakdown, * only rates). Again, realtime displays IRL time as opposed to in game time. */ - public List format(MinecraftServer server, boolean realTime, boolean brief) + public List format(MinecraftServer server, boolean realTime, boolean brief) { - long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.getWorld(World.OVERWORLD).getTime() - startTick, 1); //OW + long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.getLevel(Level.OVERWORLD).getGameTime() - startTick, 1); //OW if (startTick < 0 || ticks == 0) { if (brief) @@ -201,7 +200,7 @@ public class HopperCounter String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min" )); } - List items = new ArrayList<>(); + List items = new ArrayList<>(); items.add(Messenger.c("w Items for ", prettyColour, "w (",String.format("wb %.2f", ticks*1.0/(20*60)), "w min"+(realTime?" - real time":"")+"), ", "w total: ", "wb "+total, "w , (",String.format("wb %.1f",total*1.0*(20*60*60)/ticks),"w /h):", @@ -210,7 +209,7 @@ public class HopperCounter items.addAll(counter.object2LongEntrySet().stream().sorted((e, f) -> Long.compare(f.getLongValue(), e.getLongValue())).map(e -> { Item item = e.getKey(); - BaseText itemName = new TranslatableText(item.getTranslationKey()); + BaseComponent itemName = new TranslatableComponent(item.getDescriptionId()); Style itemStyle = itemName.getStyle(); TextColor color = guessColor(item); itemName.setStyle((color != null) ? itemStyle.withColor(color) : itemStyle.withItalic(true)); @@ -229,7 +228,7 @@ public class HopperCounter */ public static int appropriateColor(int color) { - if (color == 0) return MapColor.WHITE.color; + if (color == 0) return MaterialColor.SNOW.col; int r = (color >> 16 & 255); int g = (color >> 8 & 255); int b = (color & 255); @@ -334,23 +333,23 @@ public class HopperCounter */ public static TextColor fromItem(Item item) { - if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).getDefaultMapColor().color)); - if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getColor().getMapColor().color)); + if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMaterialColor().col)); + if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getDyeColor().getMaterialColor().col)); Block block = null; - Identifier id = Registry.ITEM.getId(item); + ResourceLocation id = Registry.ITEM.getKey(item); if (item instanceof BlockItem) { block = ((BlockItem) item).getBlock(); } - else if (Registry.BLOCK.getOrEmpty(id).isPresent()) + else if (Registry.BLOCK.getOptional(id).isPresent()) { block = Registry.BLOCK.get(id); } if (block != null) { - if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMapColor().color)); - if (block instanceof Stainable) return TextColor.fromRgb(appropriateColor( ((Stainable) block).getColor().getMapColor().color)); - return TextColor.fromRgb(appropriateColor( block.getDefaultMapColor().color)); + if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMaterialColor().col)); + if (block instanceof BeaconBeamBlock) return TextColor.fromRgb(appropriateColor( ((BeaconBeamBlock) block).getColor().getMaterialColor().col)); + return TextColor.fromRgb(appropriateColor( block.defaultMaterialColor().col)); } return null; } @@ -364,7 +363,7 @@ public class HopperCounter TextColor direct = fromItem(item); if (direct != null) return direct; if (CarpetServer.minecraft_server == null) return WHITE; - Identifier id = Registry.ITEM.getId(item); + ResourceLocation id = Registry.ITEM.getKey(item); for (RecipeType type: Registry.RECIPE_TYPE) { for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id)) diff --git a/src/main/java/carpet/helpers/InventoryHelper.java b/src/main/java/carpet/helpers/InventoryHelper.java index c099ae19..f686ceeb 100644 --- a/src/main/java/carpet/helpers/InventoryHelper.java +++ b/src/main/java/carpet/helpers/InventoryHelper.java @@ -1,7 +1,7 @@ package carpet.helpers; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; public class InventoryHelper { @@ -23,12 +23,12 @@ public class InventoryHelper public static boolean cleanUpShulkerBoxTag(ItemStack stack) { boolean changed = false; - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND)) return false; - NbtCompound bet = tag.getCompound("BlockEntityTag"); + CompoundTag bet = tag.getCompound("BlockEntityTag"); if (bet.contains("Items", TAG_LIST) && bet.getList("Items", TAG_COMPOUND).isEmpty()) { bet.remove("Items"); @@ -42,7 +42,7 @@ public class InventoryHelper } if (tag.isEmpty()) { - stack.setNbt(null); + stack.setTag(null); changed = true; } return changed; @@ -50,12 +50,12 @@ public class InventoryHelper public static boolean shulkerBoxHasItems(ItemStack stack) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND)) return false; - NbtCompound bet = tag.getCompound("BlockEntityTag"); + CompoundTag bet = tag.getCompound("BlockEntityTag"); return bet.contains("Items", TAG_LIST) && !bet.getList("Items", TAG_COMPOUND).isEmpty(); } } diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java index ce9a331c..c21dd8a5 100644 --- a/src/main/java/carpet/helpers/OptimizedExplosion.java +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java @@ -6,7 +6,32 @@ import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; - +import net.minecraft.core.BlockPos; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.ProtectionEnchantment; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; import carpet.logging.logHelpers.ExplosionLogHelper; import carpet.mixins.ExplosionAccessor; import carpet.CarpetSettings; @@ -15,52 +40,25 @@ import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.Material; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.ItemEntity; -import net.minecraft.entity.TntEntity; -import net.minecraft.fluid.FluidState; -import net.minecraft.item.ItemStack; -import net.minecraft.particle.ParticleTypes; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.sound.SoundCategory; -import net.minecraft.sound.SoundEvents; -import net.minecraft.world.explosion.Explosion; -import net.minecraft.loot.context.LootContext; -import net.minecraft.loot.context.LootContextParameters; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; -import net.minecraft.block.Block; -import net.minecraft.enchantment.ProtectionEnchantment; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; - import static carpet.script.CarpetEventServer.Event.EXPLOSION_OUTCOME; public class OptimizedExplosion { private static List entitylist; - private static Vec3d vec3dmem; + private static Vec3 vec3dmem; private static long tickmem; // For disabling the explosion particles and sound public static int explosionSound = 0; // masa's optimizations - private static Object2DoubleOpenHashMap> densityCache = new Object2DoubleOpenHashMap<>(); - private static MutablePair pairMutable = new MutablePair<>(); + private static Object2DoubleOpenHashMap> densityCache = new Object2DoubleOpenHashMap<>(); + private static MutablePair pairMutable = new MutablePair<>(); private static Object2ObjectOpenHashMap stateCache = new Object2ObjectOpenHashMap<>(); private static Object2ObjectOpenHashMap fluidCache = new Object2ObjectOpenHashMap<>(); - private static BlockPos.Mutable posMutable = new BlockPos.Mutable(0, 0, 0); + private static BlockPos.MutableBlockPos posMutable = new BlockPos.MutableBlockPos(0, 0, 0); private static ObjectOpenHashSet affectedBlockPositionsSet = new ObjectOpenHashSet<>(); private static boolean firstRay; private static boolean rayCalcDone; @@ -74,7 +72,7 @@ public class OptimizedExplosion ExplosionAccessor eAccess = (ExplosionAccessor) e; entityList.clear(); - boolean eventNeeded = EXPLOSION_OUTCOME.isNeeded() && !eAccess.getWorld().isClient(); + boolean eventNeeded = EXPLOSION_OUTCOME.isNeeded() && !eAccess.getLevel().isClientSide(); blastCalc(e); if (!CarpetSettings.explosionNoBlockDamage) { @@ -89,29 +87,29 @@ public class OptimizedExplosion stateCache.clear(); fluidCache.clear(); - e.getAffectedBlocks().addAll(affectedBlockPositionsSet); + e.getToBlow().addAll(affectedBlockPositionsSet); affectedBlockPositionsSet.clear(); } - float f3 = eAccess.getPower() * 2.0F; - int k1 = MathHelper.floor(eAccess.getX() - (double) f3 - 1.0D); - int l1 = MathHelper.floor(eAccess.getX() + (double) f3 + 1.0D); - int i2 = MathHelper.floor(eAccess.getY() - (double) f3 - 1.0D); - int i1 = MathHelper.floor(eAccess.getY() + (double) f3 + 1.0D); - int j2 = MathHelper.floor(eAccess.getZ() - (double) f3 - 1.0D); - int j1 = MathHelper.floor(eAccess.getZ() + (double) f3 + 1.0D); - Vec3d vec3d = new Vec3d(eAccess.getX(), eAccess.getY(), eAccess.getZ()); + float f3 = eAccess.getRadius() * 2.0F; + int k1 = Mth.floor(eAccess.getX() - (double) f3 - 1.0D); + int l1 = Mth.floor(eAccess.getX() + (double) f3 + 1.0D); + int i2 = Mth.floor(eAccess.getY() - (double) f3 - 1.0D); + int i1 = Mth.floor(eAccess.getY() + (double) f3 + 1.0D); + int j2 = Mth.floor(eAccess.getZ() - (double) f3 - 1.0D); + int j1 = Mth.floor(eAccess.getZ() + (double) f3 + 1.0D); + Vec3 vec3d = new Vec3(eAccess.getX(), eAccess.getY(), eAccess.getZ()); - if (vec3dmem == null || !vec3dmem.equals(vec3d) || tickmem != eAccess.getWorld().getTime()) { + if (vec3dmem == null || !vec3dmem.equals(vec3d) || tickmem != eAccess.getLevel().getGameTime()) { vec3dmem = vec3d; - tickmem = eAccess.getWorld().getTime(); - entitylist = eAccess.getWorld().getOtherEntities(null, new Box(k1, i2, j2, l1, i1, j1)); + tickmem = eAccess.getLevel().getGameTime(); + entitylist = eAccess.getLevel().getEntities(null, new AABB(k1, i2, j2, l1, i1, j1)); explosionSound = 0; } explosionSound++; - Entity explodingEntity = eAccess.getEntity(); + Entity explodingEntity = eAccess.getSource(); for (int k2 = 0; k2 < entitylist.size(); ++k2) { Entity entity = entitylist.get(k2); @@ -123,23 +121,23 @@ public class OptimizedExplosion continue; } - if (entity instanceof TntEntity && explodingEntity != null && + if (entity instanceof PrimedTnt && explodingEntity != null && entity.getX() == explodingEntity.getX() && entity.getY() == explodingEntity.getY() && entity.getZ() == explodingEntity.getZ()) { if (eLogger != null) { - eLogger.onEntityImpacted(entity, new Vec3d(0,-0.9923437498509884d, 0)); + eLogger.onEntityImpacted(entity, new Vec3(0,-0.9923437498509884d, 0)); } continue; } - if (!entity.isImmuneToExplosion()) { - double d12 = Math.sqrt(entity.squaredDistanceTo(eAccess.getX(), eAccess.getY(), eAccess.getZ())) / (double) f3; + if (!entity.ignoreExplosion()) { + double d12 = Math.sqrt(entity.distanceToSqr(eAccess.getX(), eAccess.getY(), eAccess.getZ())) / (double) f3; if (d12 <= 1.0D) { double d5 = entity.getX() - eAccess.getX(); // Change in 1.16 snapshots to fix a bug with TNT jumping - double d7 = (entity instanceof TntEntity ? entity.getY() : entity.getEyeY()) - eAccess.getY(); + double d7 = (entity instanceof PrimedTnt ? entity.getY() : entity.getEyeY()) - eAccess.getY(); double d9 = entity.getZ() - eAccess.getZ(); double d13 = (double) Math.sqrt(d5 * d5 + d7 * d7 + d9 * d9); @@ -155,8 +153,8 @@ public class OptimizedExplosion if (density == Double.MAX_VALUE) { - Pair pair = Pair.of(vec3d, entity.getBoundingBox()); - density = Explosion.getExposure(vec3d, entity); + Pair pair = Pair.of(vec3d, entity.getBoundingBox()); + density = Explosion.getSeenPercent(vec3d, entity); densityCache.put(pair, density); } @@ -166,25 +164,25 @@ public class OptimizedExplosion } double d10 = (1.0D - d12) * density; - entity.damage(e.getDamageSource(), + entity.hurt(e.getDamageSource(), (float) ((int) ((d10 * d10 + d10) / 2.0D * 7.0D * (double) f3 + 1.0D))); double d11 = d10; if (entity instanceof LivingEntity) { - d11 = ProtectionEnchantment.transformExplosionKnockback((LivingEntity) entity, d10); + d11 = ProtectionEnchantment.getExplosionKnockbackAfterDampener((LivingEntity) entity, d10); } if (eLogger != null) { - eLogger.onEntityImpacted(entity, new Vec3d(d5 * d11, d7 * d11, d9 * d11)); + eLogger.onEntityImpacted(entity, new Vec3(d5 * d11, d7 * d11, d9 * d11)); } - entity.setVelocity(entity.getVelocity().add(d5 * d11, d7 * d11, d9 * d11)); + entity.setDeltaMovement(entity.getDeltaMovement().add(d5 * d11, d7 * d11, d9 * d11)); - if (entity instanceof PlayerEntity player) { + if (entity instanceof Player player) { if (!player.isSpectator() && (!player.isCreative() || !player.getAbilities().flying)) { //getAbilities - e.getAffectedPlayers().put(player, new Vec3d(d5 * d10, d7 * d10, d9 * d10)); + e.getHitPlayers().put(player, new Vec3(d5 * d10, d7 * d10, d9 * d10)); } } } @@ -198,27 +196,27 @@ public class OptimizedExplosion public static void doExplosionB(Explosion e, boolean spawnParticles) { ExplosionAccessor eAccess = (ExplosionAccessor) e; - World world = eAccess.getWorld(); + Level world = eAccess.getLevel(); double posX = eAccess.getX(); double posY = eAccess.getY(); double posZ = eAccess.getZ(); // If it is needed, calls scarpet event - if (EXPLOSION_OUTCOME.isNeeded() && !world.isClient()) { - EXPLOSION_OUTCOME.onExplosion((ServerWorld) world, eAccess.getEntity(), e::getCausingEntity, eAccess.getX(), eAccess.getY(), eAccess.getZ(), eAccess.getPower(), eAccess.isCreateFire(), e.getAffectedBlocks(), entityList, eAccess.getDestructionType()); + if (EXPLOSION_OUTCOME.isNeeded() && !world.isClientSide()) { + EXPLOSION_OUTCOME.onExplosion((ServerLevel) world, eAccess.getSource(), e::getSourceMob, eAccess.getX(), eAccess.getY(), eAccess.getZ(), eAccess.getRadius(), eAccess.isFire(), e.getToBlow(), entityList, eAccess.getBlockInteraction()); } - boolean damagesTerrain = eAccess.getDestructionType() != Explosion.DestructionType.NONE; + boolean damagesTerrain = eAccess.getBlockInteraction() != Explosion.BlockInteraction.NONE; // explosionSound incremented till disabling the explosion particles and sound if (explosionSound < 100 || explosionSound % 100 == 0) { - world.playSound(null, posX, posY, posZ, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, + world.playSound(null, posX, posY, posZ, SoundEvents.GENERIC_EXPLODE, SoundSource.BLOCKS, 4.0F, (1.0F + (world.random.nextFloat() - world.random.nextFloat()) * 0.2F) * 0.7F); if (spawnParticles) { - if (eAccess.getPower() >= 2.0F && damagesTerrain) + if (eAccess.getRadius() >= 2.0F && damagesTerrain) { world.addParticle(ParticleTypes.EXPLOSION_EMITTER, posX, posY, posZ, 1.0D, 0.0D, 0.0D); } @@ -232,56 +230,56 @@ public class OptimizedExplosion if (damagesTerrain) { ObjectArrayList> objectArrayList = new ObjectArrayList(); - Collections.shuffle(e.getAffectedBlocks(), world.random); + Collections.shuffle(e.getToBlow(), world.random); - for (BlockPos blockpos : e.getAffectedBlocks()) + for (BlockPos blockpos : e.getToBlow()) { BlockState state = world.getBlockState(blockpos); Block block = state.getBlock(); if (state.getMaterial() != Material.AIR) { - if (block.shouldDropItemsOnExplosion(e) && world instanceof ServerWorld) + if (block.dropFromExplosion(e) && world instanceof ServerLevel) { BlockEntity blockEntity = state.hasBlockEntity() ? world.getBlockEntity(blockpos) : null; //hasBlockEntity() - LootContext.Builder lootBuilder = (new LootContext.Builder((ServerWorld)eAccess.getWorld())) - .random(eAccess.getWorld().random) - .parameter(LootContextParameters.ORIGIN, Vec3d.ofCenter(blockpos)) - .parameter(LootContextParameters.TOOL, ItemStack.EMPTY) - .optionalParameter(LootContextParameters.BLOCK_ENTITY, blockEntity) - .optionalParameter(LootContextParameters.THIS_ENTITY, eAccess.getEntity()); + LootContext.Builder lootBuilder = (new LootContext.Builder((ServerLevel)eAccess.getLevel())) + .withRandom(eAccess.getLevel().random) + .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(blockpos)) + .withParameter(LootContextParams.TOOL, ItemStack.EMPTY) + .withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockEntity) + .withOptionalParameter(LootContextParams.THIS_ENTITY, eAccess.getSource()); - if (eAccess.getDestructionType() == Explosion.DestructionType.DESTROY) - lootBuilder.parameter(LootContextParameters.EXPLOSION_RADIUS, eAccess.getPower()); + if (eAccess.getBlockInteraction() == Explosion.BlockInteraction.DESTROY) + lootBuilder.withParameter(LootContextParams.EXPLOSION_RADIUS, eAccess.getRadius()); - state.getDroppedStacks(lootBuilder).forEach((itemStackx) -> { - method_24023(objectArrayList, itemStackx, blockpos.toImmutable()); + state.getDrops(lootBuilder).forEach((itemStackx) -> { + method_24023(objectArrayList, itemStackx, blockpos.immutable()); }); } - world.setBlockState(blockpos, Blocks.AIR.getDefaultState(), 3); - block.onDestroyedByExplosion(world, blockpos, e); + world.setBlock(blockpos, Blocks.AIR.defaultBlockState(), 3); + block.wasExploded(world, blockpos, e); } } - objectArrayList.forEach(p -> Block.dropStack(world, p.getRight(), p.getLeft())); + objectArrayList.forEach(p -> Block.popResource(world, p.getRight(), p.getLeft())); } - if (eAccess.isCreateFire()) + if (eAccess.isFire()) { - for (BlockPos blockpos1 : e.getAffectedBlocks()) + for (BlockPos blockpos1 : e.getToBlow()) { // Use the same Chunk reference because the positions are in the same xz-column - Chunk chunk = world.getChunk(blockpos1.getX() >> 4, blockpos1.getZ() >> 4); + ChunkAccess chunk = world.getChunk(blockpos1.getX() >> 4, blockpos1.getZ() >> 4); - BlockPos down = blockpos1.down(1); + BlockPos down = blockpos1.below(1); if (eAccess.getRandom().nextInt(3) == 0 && chunk.getBlockState(blockpos1).getMaterial() == Material.AIR && - chunk.getBlockState(down).isOpaqueFullCube(world, down) + chunk.getBlockState(down).isSolidRender(world, down) ) { - world.setBlockState(blockpos1, Blocks.FIRE.getDefaultState()); + world.setBlockAndUpdate(blockpos1, Blocks.FIRE.defaultBlockState()); } } } @@ -295,7 +293,7 @@ public class OptimizedExplosion for(int j = 0; j < i; ++j) { Pair pair = (Pair)objectArrayList.get(j); ItemStack itemStack2 = pair.getLeft(); - if (ItemEntity.canMerge(itemStack2, itemStack)) { + if (ItemEntity.areMergable(itemStack2, itemStack)) { ItemStack itemStack3 = ItemEntity.merge(itemStack2, itemStack, 16); objectArrayList.set(j, Pair.of(itemStack3, pair.getRight())); if (itemStack.isEmpty()) { @@ -328,29 +326,29 @@ public class OptimizedExplosion d0 = d0 / d3; d1 = d1 / d3; d2 = d2 / d3; - float rand = eAccess.getWorld().random.nextFloat(); + float rand = eAccess.getLevel().random.nextFloat(); if (CarpetSettings.tntRandomRange >= 0) { rand = (float) CarpetSettings.tntRandomRange; } - float f = eAccess.getPower() * (0.7F + rand * 0.6F); + float f = eAccess.getRadius() * (0.7F + rand * 0.6F); double d4 = eAccess.getX(); double d6 = eAccess.getY(); double d8 = eAccess.getZ(); for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { BlockPos blockpos = new BlockPos(d4, d6, d8); - BlockState state = eAccess.getWorld().getBlockState(blockpos); - FluidState fluidState = eAccess.getWorld().getFluidState(blockpos); + BlockState state = eAccess.getLevel().getBlockState(blockpos); + FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); if (state.getMaterial() != Material.AIR) { - float f2 = Math.max(state.getBlock().getBlastResistance(), fluidState.getBlastResistance()); - if (eAccess.getEntity() != null) - f2 = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), blockpos, state, fluidState, f2); + float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance()); + if (eAccess.getSource() != null) + f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2); f -= (f2 + 0.3F) * 0.3F; } - if (f > 0.0F && (eAccess.getEntity() == null || - eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), blockpos, state, f))) + if (f > 0.0F && (eAccess.getSource() == null || + eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), blockpos, state, f))) { affectedBlockPositionsSet.add(blockpos); } @@ -446,9 +444,9 @@ public class OptimizedExplosion double xInc = (xRel / len) * 0.3; double yInc = (yRel / len) * 0.3; double zInc = (zRel / len) * 0.3; - float rand = eAccess.getWorld().random.nextFloat(); + float rand = eAccess.getLevel().random.nextFloat(); float sizeRand = (CarpetSettings.tntRandomRange >= 0 ? (float) CarpetSettings.tntRandomRange : rand); - float size = eAccess.getPower() * (0.7F + sizeRand * 0.6F); + float size = eAccess.getRadius() * (0.7F + sizeRand * 0.6F); double posX = eAccess.getX(); double posY = eAccess.getY(); double posZ = eAccess.getZ(); @@ -464,20 +462,20 @@ public class OptimizedExplosion if (state == null) { - posImmutable = posMutable.toImmutable(); - state = eAccess.getWorld().getBlockState(posImmutable); + posImmutable = posMutable.immutable(); + state = eAccess.getLevel().getBlockState(posImmutable); stateCache.put(posImmutable, state); - fluid = eAccess.getWorld().getFluidState(posImmutable); + fluid = eAccess.getLevel().getFluidState(posImmutable); fluidCache.put(posImmutable, fluid); } if (state.getMaterial() != Material.AIR) { - float resistance = Math.max(state.getBlock().getBlastResistance(), fluid.getBlastResistance()); + float resistance = Math.max(state.getBlock().getExplosionResistance(), fluid.getExplosionResistance()); - if (eAccess.getEntity() != null) + if (eAccess.getSource() != null) { - resistance = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), posMutable, state, fluid, resistance); + resistance = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), posMutable, state, fluid, resistance); } size -= (resistance + 0.3F) * 0.3F; @@ -485,8 +483,8 @@ public class OptimizedExplosion if (size > 0.0F) { - if ((eAccess.getEntity() == null || eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), posMutable, state, size))) - affectedBlockPositionsSet.add(posImmutable != null ? posImmutable : posMutable.toImmutable()); + if ((eAccess.getSource() == null || eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), posMutable, state, size))) + affectedBlockPositionsSet.add(posImmutable != null ? posImmutable : posMutable.immutable()); } else if (firstRay) { @@ -510,7 +508,7 @@ public class OptimizedExplosion private static void blastCalc(Explosion e){ ExplosionAccessor eAccess = (ExplosionAccessor) e; - if(blastChanceLocation == null || blastChanceLocation.getSquaredDistance(eAccess.getX(), eAccess.getY(), eAccess.getZ(), false) > 200) return; + if(blastChanceLocation == null || blastChanceLocation.distSqr(eAccess.getX(), eAccess.getY(), eAccess.getZ(), false) > 200) return; chances.clear(); for (int j = 0; j < 16; ++j) { for (int k = 0; k < 16; ++k) { @@ -523,7 +521,7 @@ public class OptimizedExplosion d0 = d0 / d3; d1 = d1 / d3; d2 = d2 / d3; - float f = eAccess.getPower() * (0.7F + 0.6F); + float f = eAccess.getRadius() * (0.7F + 0.6F); double d4 = eAccess.getX(); double d6 = eAccess.getY(); double d8 = eAccess.getZ(); @@ -531,18 +529,18 @@ public class OptimizedExplosion for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { BlockPos blockpos = new BlockPos(d4, d6, d8); - BlockState state = eAccess.getWorld().getBlockState(blockpos); - FluidState fluidState = eAccess.getWorld().getFluidState(blockpos); + BlockState state = eAccess.getLevel().getBlockState(blockpos); + FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); if (state.getMaterial() != Material.AIR) { - float f2 = Math.max(state.getBlock().getBlastResistance(), fluidState.getBlastResistance()); - if (eAccess.getEntity() != null) - f2 = eAccess.getEntity().getEffectiveExplosionResistance(e, eAccess.getWorld(), blockpos, state, fluidState, f2); + float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance()); + if (eAccess.getSource() != null) + f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2); f -= (f2 + 0.3F) * 0.3F; } - if (f > 0.0F && (eAccess.getEntity() == null || - eAccess.getEntity().canExplosionDestroyBlock(e, eAccess.getWorld(), blockpos, state, f))) { + if (f > 0.0F && (eAccess.getSource() == null || + eAccess.getSource().shouldBlockExplode(e, eAccess.getLevel(), blockpos, state, f))) { if(!found && blockpos.equals(blastChanceLocation)){ chances.add(f); found = true; @@ -563,7 +561,7 @@ public class OptimizedExplosion private static void showTNTblastChance(Explosion e){ ExplosionAccessor eAccess = (ExplosionAccessor) e; - double randMax = 0.6F * eAccess.getPower(); + double randMax = 0.6F * eAccess.getRadius(); double total = 0; boolean fullyBlownUp = false; boolean first = true; @@ -587,7 +585,7 @@ public class OptimizedExplosion NumberFormat nf = NumberFormat.getNumberInstance(); nf.setRoundingMode (RoundingMode.DOWN); nf.setMaximumFractionDigits(2); - for(PlayerEntity player : eAccess.getWorld().getPlayers()){ + for(Player player : eAccess.getLevel().players()){ Messenger.m(player,"w Pop: ", "c " + nf.format(chance) + " ", "^w Chance for the block to be destroyed by the blast: " + chance, @@ -601,9 +599,9 @@ public class OptimizedExplosion "^w TNT blast rays going through the block", "?" + rays, "w Size: ", - String.format("c %.1f ", eAccess.getPower()), + String.format("c %.1f ", eAccess.getRadius()), "^w TNT blast size", - "?" + eAccess.getPower(), + "?" + eAccess.getRadius(), "w @: ", String.format("c [%.1f %.1f %.1f] ", eAccess.getX(), eAccess.getY(), eAccess.getZ()), "^w TNT blast location X:" + eAccess.getX() + " Y:" + eAccess.getY() + " Z:" + eAccess.getZ(), diff --git a/src/main/java/carpet/helpers/ParticleDisplay.java b/src/main/java/carpet/helpers/ParticleDisplay.java index a86d2973..d4468b8c 100644 --- a/src/main/java/carpet/helpers/ParticleDisplay.java +++ b/src/main/java/carpet/helpers/ParticleDisplay.java @@ -2,61 +2,60 @@ package carpet.helpers; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.ParticleEffectArgumentType; -import net.minecraft.particle.ParticleEffect; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.Vec3d; - import java.util.HashMap; import java.util.Map; +import net.minecraft.commands.arguments.ParticleArgument; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.phys.Vec3; public class ParticleDisplay { - private static Map particleCache = new HashMap<>(); + private static Map particleCache = new HashMap<>(); - private static ParticleEffect parseParticle(String name) + private static ParticleOptions parseParticle(String name) { try { - return ParticleEffectArgumentType.readParameters(new StringReader(name)); + return ParticleArgument.readParticle(new StringReader(name)); } catch (CommandSyntaxException e) { throw new RuntimeException("No such particle: "+name); } } - public static ParticleEffect getEffect(String name) + public static ParticleOptions getEffect(String name) { if (name == null) return null; - ParticleEffect res = particleCache.get(name); + ParticleOptions res = particleCache.get(name); if (res != null) return res; particleCache.put(name, parseParticle(name)); return particleCache.get(name); } - public static void drawParticleLine(ServerPlayerEntity player, Vec3d from, Vec3d to, String main, String accent, int count, double spread) + public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, String main, String accent, int count, double spread) { - ParticleEffect accentParticle = getEffect(accent); - ParticleEffect mainParticle = getEffect(main); + ParticleOptions accentParticle = getEffect(accent); + ParticleOptions mainParticle = getEffect(main); - if (accentParticle != null) ((ServerWorld)player.world).spawnParticles( + if (accentParticle != null) ((ServerLevel)player.level).sendParticles( player, accentParticle, true, to.x, to.y, to.z, count, spread, spread, spread, 0.0); - double lineLengthSq = from.squaredDistanceTo(to); + double lineLengthSq = from.distanceToSqr(to); if (lineLengthSq == 0) return; - Vec3d incvec = to.subtract(from).normalize();// multiply(50/sqrt(lineLengthSq)); + Vec3 incvec = to.subtract(from).normalize();// multiply(50/sqrt(lineLengthSq)); int pcount = 0; - for (Vec3d delta = new Vec3d(0.0,0.0,0.0); - delta.lengthSquared() updateQueue2 = new ArrayList<>(); - public RedstoneWireTurbo(RedstoneWireBlock wire) { + public RedstoneWireTurbo(RedStoneWireBlock wire) { this.wire = wire; } @@ -294,7 +293,7 @@ public class RedstoneWireTurbo /* * For a newly created UpdateNode object, determine what type of block it is. */ - private void identifyNode(final World worldIn, final UpdateNode upd1) { + private void identifyNode(final Level worldIn, final UpdateNode upd1) { final BlockPos pos = upd1.self; final BlockState oldState = worldIn.getBlockState(pos); upd1.currentState = oldState; @@ -321,9 +320,9 @@ public class RedstoneWireTurbo // others are processed internally by the breadth first search // algorithm. To preserve this game behavior, this check must // be replicated here. - if (!oldState.canPlaceAt(worldIn, pos)) { + if (!oldState.canSurvive(worldIn, pos)) { // Pop off the redstone dust - Block.dropStacks(oldState, worldIn, pos); + Block.dropResources(oldState, worldIn, pos); worldIn.removeBlock(pos, false); // Mark this position as not being redstone wire @@ -417,7 +416,7 @@ public class RedstoneWireTurbo /* * Process a node whose neighboring redstone wire has experienced value changes. */ - private void updateNode(final World worldIn, final UpdateNode upd1, final int layer) { + private void updateNode(final Level worldIn, final UpdateNode upd1, final int layer) { final BlockPos pos = upd1.self; // Mark this redstone wire as having been visited so that it can be used @@ -462,7 +461,7 @@ public class RedstoneWireTurbo * what nodes in the redstone wire graph have been visited, the neighbors * are reordered left-to-right relative to the direction of information flow. */ - private void findNeighbors(final World worldIn, final UpdateNode upd1) { + private void findNeighbors(final Level worldIn, final UpdateNode upd1) { final BlockPos pos = upd1.self; // Get the list of neighbor coordinates @@ -553,7 +552,7 @@ public class RedstoneWireTurbo * For any redstone wire block in layer N, inform neighbors to recompute their states * in layers N+1 and N+2; */ - private void propagateChanges(final World worldIn, final UpdateNode upd1, final int layer) { + private void propagateChanges(final Level worldIn, final UpdateNode upd1, final int layer) { if (upd1.neighbor_nodes == null) { // If this node has not been expanded yet, find its neigbors findNeighbors(worldIn, upd1); @@ -627,7 +626,7 @@ public class RedstoneWireTurbo * that is a function of distance from the initial call to * this.neighborChanged. */ - private void breadthFirstWalk(final World worldIn) { + private void breadthFirstWalk(final Level worldIn) { shiftQueue(); currentWalkLayer = 1; @@ -663,7 +662,7 @@ public class RedstoneWireTurbo // already keeping track of all of the neighbor positions // that need to be updated. All on its own, handling neighbors // this way reduces block updates by 1/3 (24 instead of 36). - worldIn.updateNeighbor(upd.self, wire, upd.parent); + worldIn.neighborChanged(upd.self, wire, upd.parent); } } @@ -701,7 +700,7 @@ public class RedstoneWireTurbo * order to continue processing both the first and second wire in the order of distance from the initial * trigger. */ - private BlockState scheduleReentrantNeighborChanged(final World worldIn, final BlockPos pos, final BlockState newState, final BlockPos source) + private BlockState scheduleReentrantNeighborChanged(final Level worldIn, final BlockPos pos, final BlockState newState, final BlockPos source) { if (source != null) { // If the cause of the redstone wire update is known, we can use that to help determine @@ -762,7 +761,7 @@ public class RedstoneWireTurbo * few other methods in RedstoneWireBlock. This sets off the breadth-first * walk through all redstone dust connected to the initial position triggered. */ - public BlockState updateSurroundingRedstone(final World worldIn, final BlockPos pos, final BlockState state, final BlockPos source) + public BlockState updateSurroundingRedstone(final Level worldIn, final BlockPos pos, final BlockState state, final BlockPos source) { // Check this block's neighbors and see if its power level needs to change // Use the calculateCurrentChanges method in RedstoneWireBlock since we have no @@ -832,10 +831,10 @@ public class RedstoneWireTurbo * the UpdateNode's neighbor array to find the redstone states of neighbors * that might power it. */ - private BlockState calculateCurrentChanges(final World worldIn, final UpdateNode upd) + private BlockState calculateCurrentChanges(final Level worldIn, final UpdateNode upd) { BlockState state = upd.currentState; - final int i = state.get(RedstoneWireBlock.POWER); + final int i = state.getValue(RedStoneWireBlock.POWER); int j = 0; j = getMaxCurrentStrength(upd, j); int l = 0; @@ -846,7 +845,7 @@ public class RedstoneWireTurbo // elsewhere in Minecraft into this accelerator. So sadly, we must // suffer the performance hit of this very expensive call. If there // is consistency to what this call returns, we may be able to cache it. - final int k = worldIn.getReceivedRedstonePower(upd.self); + final int k = worldIn.getBestNeighborSignal(upd.self); ((RedstoneWireBlockInterface)wire).setWiresGivePower(true); // The variable 'k' holds the maximum redstone power value of any adjacent blocks. @@ -865,7 +864,7 @@ public class RedstoneWireTurbo // position directly above the node being calculated is always // at index 1. UpdateNode center_up = upd.neighbor_nodes[1]; - boolean center_up_is_cube = center_up.currentState.isSolidBlock(worldIn, center_up.self); //isSimpleFUllBLock + boolean center_up_is_cube = center_up.currentState.isRedstoneConductor(worldIn, center_up.self); //isSimpleFUllBLock for (int m=0; m<4; m++) { // Get the neighbor array index of each of the four cardinal @@ -879,7 +878,7 @@ public class RedstoneWireTurbo // Also check the positions above and below the cardinal // neighbors - boolean neighbor_is_cube = neighbor.currentState.isSolidBlock(worldIn, neighbor.self); //isSimpleFUllBLock + boolean neighbor_is_cube = neighbor.currentState.isRedstoneConductor(worldIn, neighbor.self); //isSimpleFUllBLock if (!neighbor_is_cube) { UpdateNode neighbor_down = upd.neighbor_nodes[rs_neighbors_dn[m]]; l = getMaxCurrentStrength(neighbor_down, l); @@ -905,11 +904,11 @@ public class RedstoneWireTurbo // and set it in the world. // Possible optimization: Don't commit state changes to the world until they // need to be known by some nearby non-redstone-wire block. - state = state.with(RedstoneWireBlock.POWER, j); + state = state.setValue(RedStoneWireBlock.POWER, j); // [gnembon] added state check cause other things in the tick may have popped it up already // https://github.com/gnembon/fabric-carpet/issues/117 if (worldIn.getBlockState(upd.self).getBlock() == Blocks.REDSTONE_WIRE) - worldIn.setBlockState(upd.self, state, 2); + worldIn.setBlock(upd.self, state, 2); } return state; @@ -921,7 +920,7 @@ public class RedstoneWireTurbo */ private static int getMaxCurrentStrength(final UpdateNode upd, final int strength) { if (upd.type != UpdateNode.Type.REDSTONE) return strength; - final int i = upd.currentState.get(RedstoneWireBlock.POWER); + final int i = upd.currentState.getValue(RedStoneWireBlock.POWER); return i > strength ? i : strength; } } \ No newline at end of file diff --git a/src/main/java/carpet/helpers/ThrowableSuppression.java b/src/main/java/carpet/helpers/ThrowableSuppression.java index 76ae4e14..981c0945 100644 --- a/src/main/java/carpet/helpers/ThrowableSuppression.java +++ b/src/main/java/carpet/helpers/ThrowableSuppression.java @@ -1,6 +1,6 @@ package carpet.helpers; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; public class ThrowableSuppression extends RuntimeException{ diff --git a/src/main/java/carpet/helpers/TickSpeed.java b/src/main/java/carpet/helpers/TickSpeed.java index 0ee668be..8ba2cf65 100644 --- a/src/main/java/carpet/helpers/TickSpeed.java +++ b/src/main/java/carpet/helpers/TickSpeed.java @@ -3,14 +3,13 @@ package carpet.helpers; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; - +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerPlayer; import carpet.CarpetServer; import carpet.network.ServerNetworkHandler; import carpet.utils.Messenger; -import net.minecraft.server.command.CommandManager; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; public class TickSpeed { @@ -20,9 +19,9 @@ public class TickSpeed public static long time_bias = 0; public static long time_warp_start_time = 0; public static long time_warp_scheduled_ticks = 0; - public static ServerPlayerEntity time_advancerer = null; + public static ServerPlayer time_advancerer = null; public static String tick_warp_callback = null; - public static ServerCommandSource tick_warp_sender = null; + public static CommandSourceStack tick_warp_sender = null; public static int player_active_timeout = 0; public static boolean process_entities = true; private static boolean deepFreeze = false; @@ -102,7 +101,7 @@ public class TickSpeed ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(); } - public static BaseText tickrate_advance(ServerPlayerEntity player, int advance, String callback, ServerCommandSource source) + public static BaseComponent tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source) { if (0 == advance) { @@ -119,7 +118,7 @@ public class TickSpeed if (time_bias > 0) { String who = "Another player"; - if (time_advancerer != null) who = time_advancerer.getEntityName(); + if (time_advancerer != null) who = time_advancerer.getScoreboardName(); return Messenger.c("l "+who+" is already advancing time at the moment. Try later or ask them"); } time_advancerer = player; @@ -147,10 +146,10 @@ public class TickSpeed time_warp_start_time = 0; if (tick_warp_callback != null) { - CommandManager icommandmanager = tick_warp_sender.getServer().getCommandManager(); + Commands icommandmanager = tick_warp_sender.getServer().getCommands(); try { - icommandmanager.execute(tick_warp_sender, tick_warp_callback); + icommandmanager.performCommand(tick_warp_sender, tick_warp_callback); } catch (Throwable var23) { diff --git a/src/main/java/carpet/helpers/Tracer.java b/src/main/java/carpet/helpers/Tracer.java index 556d204b..6eed3486 100644 --- a/src/main/java/carpet/helpers/Tracer.java +++ b/src/main/java/carpet/helpers/Tracer.java @@ -1,16 +1,15 @@ package carpet.helpers; -import net.minecraft.entity.Entity; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.RaycastContext; -import net.minecraft.world.World; - import java.util.Optional; import java.util.function.Predicate; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; public class Tracer { @@ -20,7 +19,7 @@ public class Tracer double maxSqDist = reach * reach; if (blockHit != null) { - maxSqDist = blockHit.getPos().squaredDistanceTo(source.getCameraPosVec(partialTicks)); + maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks)); } EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist); return entityHit == null ? blockHit : entityHit; @@ -28,31 +27,31 @@ public class Tracer public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids) { - Vec3d pos = source.getCameraPosVec(partialTicks); - Vec3d rotation = source.getRotationVec(partialTicks); - Vec3d reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); - return source.world.raycast(new RaycastContext(pos, reachEnd, RaycastContext.ShapeType.OUTLINE, fluids ? - RaycastContext.FluidHandling.ANY : RaycastContext.FluidHandling.NONE, source)); + Vec3 pos = source.getEyePosition(partialTicks); + Vec3 rotation = source.getViewVector(partialTicks); + Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); + return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ? + ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source)); } public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist) { - Vec3d pos = source.getCameraPosVec(partialTicks); - Vec3d reachVec = source.getRotationVec(partialTicks).multiply(reach); - Box box = source.getBoundingBox().stretch(reachVec).expand(1); - return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.collides(), maxSqDist); + Vec3 pos = source.getEyePosition(partialTicks); + Vec3 reachVec = source.getViewVector(partialTicks).scale(reach); + AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1); + return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist); } - public static EntityHitResult rayTraceEntities(Entity source, Vec3d start, Vec3d end, Box box, Predicate predicate, double maxSqDistance) + public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate predicate, double maxSqDistance) { - World world = source.world; + Level world = source.level; double targetDistance = maxSqDistance; Entity target = null; - Vec3d targetHitPos = null; - for (Entity current : world.getOtherEntities(source, box, predicate)) + Vec3 targetHitPos = null; + for (Entity current : world.getEntities(source, box, predicate)) { - Box currentBox = current.getBoundingBox().expand(current.getTargetingMargin()); - Optional currentHit = currentBox.raycast(start, end); + AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius()); + Optional currentHit = currentBox.clip(start, end); if (currentBox.contains(start)) { if (targetDistance >= 0) @@ -64,8 +63,8 @@ public class Tracer } else if (currentHit.isPresent()) { - Vec3d currentHitPos = currentHit.get(); - double currentDistance = start.squaredDistanceTo(currentHitPos); + Vec3 currentHitPos = currentHit.get(); + double currentDistance = start.distanceToSqr(currentHitPos); if (currentDistance < targetDistance || targetDistance == 0) { if (current.getRootVehicle() == source.getRootVehicle()) diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index 6cabcfc4..57006b41 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -8,17 +8,16 @@ import carpet.mixins.PlayerListHeaderS2CPacketMixin; import carpet.utils.Messenger; import carpet.utils.SpawnReporter; import io.netty.buffer.Unpooled; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.protocol.game.ClientboundTabListPacket; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.MathHelper; -import net.minecraft.text.BaseText; -import net.minecraft.text.LiteralText; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; - +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -43,18 +42,18 @@ public class HUDController HUDListeners.add(listener); } - public static Map> player_huds = new HashMap<>(); + public static Map> player_huds = new HashMap<>(); //keyed with player names so unlogged players don't hold the reference - public static final Map scarpet_headers = new HashMap<>(); + public static final Map scarpet_headers = new HashMap<>(); - public static final Map scarpet_footers = new HashMap<>(); + public static final Map scarpet_footers = new HashMap<>(); public static void resetScarpetHUDs() { scarpet_headers.clear(); scarpet_footers.clear(); } - public static void addMessage(ServerPlayerEntity player, BaseText hudMessage) + public static void addMessage(ServerPlayer player, BaseComponent hudMessage) { if (player == null) return; if (!player_huds.containsKey(player)) @@ -63,29 +62,29 @@ public class HUDController } else { - player_huds.get(player).add(new LiteralText("\n")); + player_huds.get(player).add(new TextComponent("\n")); } player_huds.get(player).add(hudMessage); } - public static void clear_player(PlayerEntity player) + public static void clear_player(Player player) { - PacketByteBuf packetData = new PacketByteBuf(Unpooled.buffer()).writeText(new LiteralText("")).writeText(new LiteralText("")); - PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(packetData); + FriendlyByteBuf packetData = new FriendlyByteBuf(Unpooled.buffer()).writeComponent(new TextComponent("")).writeComponent(new TextComponent("")); + ClientboundTabListPacket packet = new ClientboundTabListPacket(packetData); //((PlayerListHeaderS2CPacketMixin)packet).setHeader(new LiteralText("")); //((PlayerListHeaderS2CPacketMixin)packet).setFooter(new LiteralText("")); - ((ServerPlayerEntity)player).networkHandler.sendPacket(packet); + ((ServerPlayer)player).connection.send(packet); } - public static void update_hud(MinecraftServer server, List force) + public static void update_hud(MinecraftServer server, List force) { - if (((server.getTicks() % 20 != 0) && force == null) || CarpetServer.minecraft_server == null) + if (((server.getTickCount() % 20 != 0) && force == null) || CarpetServer.minecraft_server == null) return; player_huds.clear(); - server.getPlayerManager().getPlayerList().forEach(p -> { - BaseText scarpetFOoter = scarpet_footers.get(p.getEntityName()); + server.getPlayerList().getPlayers().forEach(p -> { + BaseComponent scarpetFOoter = scarpet_footers.get(p.getScoreboardName()); if (scarpetFOoter != null) HUDController.addMessage(p, scarpetFOoter); }); @@ -94,20 +93,20 @@ public class HUDController if (LoggerRegistry.__mobcaps) LoggerRegistry.getLogger("mobcaps").log((option, player) -> { - RegistryKey dim = player.world.getRegistryKey(); //getDimType + ResourceKey dim = player.level.dimension(); //getDimType switch (option) { case "overworld": - dim = World.OVERWORLD; // OW + dim = Level.OVERWORLD; // OW break; case "nether": - dim = World.NETHER; // nether + dim = Level.NETHER; // nether break; case "end": - dim = World.END; // end + dim = Level.END; // end break; } - return new BaseText[]{SpawnReporter.printMobcapsForDimension(server.getWorld(dim), false).get(0)}; + return new BaseComponent[]{SpawnReporter.printMobcapsForDimension(server.getLevel(dim), false).get(0)}; }); if(LoggerRegistry.__counter) @@ -119,43 +118,43 @@ public class HUDController // extensions have time to pitch in. HUDListeners.forEach(l -> l.accept(server)); - Set targets = new HashSet<>(player_huds.keySet()); + Set targets = new HashSet<>(player_huds.keySet()); if (force!= null) targets.addAll(force); - for (ServerPlayerEntity player: targets) + for (ServerPlayer player: targets) { - PacketByteBuf packetData = new PacketByteBuf(Unpooled.buffer()). - writeText(scarpet_headers.getOrDefault(player.getEntityName(), new LiteralText(""))). - writeText(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0]))); - PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(packetData); + FriendlyByteBuf packetData = new FriendlyByteBuf(Unpooled.buffer()). + writeComponent(scarpet_headers.getOrDefault(player.getScoreboardName(), new TextComponent(""))). + writeComponent(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0]))); + ClientboundTabListPacket packet = new ClientboundTabListPacket(packetData); //PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(); //((PlayerListHeaderS2CPacketMixin)packet).setHeader(scarpet_headers.getOrDefault(player.getEntityName(), new LiteralText(""))); //((PlayerListHeaderS2CPacketMixin)packet).setFooter(Messenger.c(player_huds.getOrDefault(player, Collections.emptyList()).toArray(new Object[0]))); - player.networkHandler.sendPacket(packet); + player.connection.send(packet); } } - private static BaseText [] send_tps_display(MinecraftServer server) + private static BaseComponent [] send_tps_display(MinecraftServer server) { - double MSPT = MathHelper.average(server.lastTickLengths) * 1.0E-6D; + double MSPT = Mth.average(server.tickTimes) * 1.0E-6D; double TPS = 1000.0D / Math.max((TickSpeed.time_warp_start_time != 0)?0.0:TickSpeed.mspt, MSPT); String color = Messenger.heatmap_color(MSPT,TickSpeed.mspt); - return new BaseText[]{Messenger.c( + return new BaseComponent[]{Messenger.c( "g TPS: ", String.format(Locale.US, "%s %.1f",color, TPS), "g MSPT: ", String.format(Locale.US,"%s %.1f", color, MSPT))}; } - private static BaseText [] send_counter_info(MinecraftServer server, String color) + private static BaseComponent [] send_counter_info(MinecraftServer server, String color) { - List res = new ArrayList<>(); + List res = new ArrayList<>(); Arrays.asList(color.split(",")).forEach(c ->{ HopperCounter counter = HopperCounter.getCounter(c); if (counter != null) res.addAll(counter.format(server, false, true)); }); - return res.toArray(new BaseText[0]); + return res.toArray(new BaseComponent[0]); } - private static BaseText [] packetCounter() + private static BaseComponent [] packetCounter() { - BaseText [] ret = new BaseText[]{ + BaseComponent [] ret = new BaseComponent[]{ Messenger.c("w I/" + PacketCounter.totalIn + " O/" + PacketCounter.totalOut), }; PacketCounter.reset(); diff --git a/src/main/java/carpet/logging/HUDLogger.java b/src/main/java/carpet/logging/HUDLogger.java index be5a695b..e4cf6afd 100644 --- a/src/main/java/carpet/logging/HUDLogger.java +++ b/src/main/java/carpet/logging/HUDLogger.java @@ -1,9 +1,8 @@ package carpet.logging; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; - import java.lang.reflect.Field; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerPlayer; public class HUDLogger extends Logger { @@ -38,15 +37,15 @@ public class HUDLogger extends Logger @Override public void removePlayer(String playerName) { - ServerPlayerEntity player = playerFromName(playerName); + ServerPlayer player = playerFromName(playerName); if (player != null) HUDController.clear_player(player); super.removePlayer(playerName); } @Override - public void sendPlayerMessage(ServerPlayerEntity player, BaseText... messages) + public void sendPlayerMessage(ServerPlayer player, BaseComponent... messages) { - for (BaseText m:messages) HUDController.addMessage(player, m); + for (BaseComponent m:messages) HUDController.addMessage(player, m); } diff --git a/src/main/java/carpet/logging/Logger.java b/src/main/java/carpet/logging/Logger.java index f6b2bd7e..903fd58e 100644 --- a/src/main/java/carpet/logging/Logger.java +++ b/src/main/java/carpet/logging/Logger.java @@ -2,11 +2,6 @@ package carpet.logging; import carpet.CarpetServer; import carpet.CarpetSettings; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.util.Util; - import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashMap; @@ -14,6 +9,10 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Supplier; +import net.minecraft.Util; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; public class Logger { @@ -136,15 +135,15 @@ public class Logger * will repeat invocation for players that share the same option */ @FunctionalInterface - public interface lMessage { BaseText [] get(String playerOption, PlayerEntity player);} + public interface lMessage { BaseComponent [] get(String playerOption, Player player);} public void log(lMessage messagePromise) { for (Map.Entry en : subscribedOnlinePlayers.entrySet()) { - ServerPlayerEntity player = playerFromName(en.getKey()); + ServerPlayer player = playerFromName(en.getKey()); if (player != null) { - BaseText [] messages = messagePromise.get(en.getValue(),player); + BaseComponent [] messages = messagePromise.get(en.getValue(),player); if (messages != null) sendPlayerMessage(player, messages); } @@ -156,13 +155,13 @@ public class Logger * and served the same way to all other players subscribed to the same option */ @FunctionalInterface - public interface lMessageIgnorePlayer { BaseText [] get(String playerOption);} + public interface lMessageIgnorePlayer { BaseComponent [] get(String playerOption);} public void log(lMessageIgnorePlayer messagePromise) { - Map cannedMessages = new HashMap<>(); + Map cannedMessages = new HashMap<>(); for (Map.Entry en : subscribedOnlinePlayers.entrySet()) { - ServerPlayerEntity player = playerFromName(en.getKey()); + ServerPlayer player = playerFromName(en.getKey()); if (player != null) { String option = en.getValue(); @@ -170,7 +169,7 @@ public class Logger { cannedMessages.put(option,messagePromise.get(option)); } - BaseText [] messages = cannedMessages.get(option); + BaseComponent [] messages = cannedMessages.get(option); if (messages != null) sendPlayerMessage(player, messages); } @@ -179,12 +178,12 @@ public class Logger /** * guarantees that message is evaluated once, so independent from the player and chosen option */ - public void log(Supplier messagePromise) + public void log(Supplier messagePromise) { - BaseText [] cannedMessages = null; + BaseComponent [] cannedMessages = null; for (Map.Entry en : subscribedOnlinePlayers.entrySet()) { - ServerPlayerEntity player = playerFromName(en.getKey()); + ServerPlayer player = playerFromName(en.getKey()); if (player != null) { if (cannedMessages == null) cannedMessages = messagePromise.get(); @@ -193,22 +192,22 @@ public class Logger } } - public void sendPlayerMessage(ServerPlayerEntity player, BaseText ... messages) + public void sendPlayerMessage(ServerPlayer player, BaseComponent ... messages) { - Arrays.stream(messages).forEach(message -> player.sendSystemMessage(message, Util.NIL_UUID)); + Arrays.stream(messages).forEach(message -> player.sendMessage(message, Util.NIL_UUID)); } /** * Gets the {@code PlayerEntity} instance for a player given their UUID. Returns null if they are offline. */ - protected ServerPlayerEntity playerFromName(String name) + protected ServerPlayer playerFromName(String name) { - return CarpetServer.minecraft_server.getPlayerManager().getPlayer(name); + return CarpetServer.minecraft_server.getPlayerList().getPlayerByName(name); } // ----- Event Handlers ----- // - public void onPlayerConnect(PlayerEntity player, boolean firstTime) + public void onPlayerConnect(Player player, boolean firstTime) { // If the player was subscribed to the log and offline, move them to the set of online subscribers. String playerName = player.getName().getString(); @@ -228,7 +227,7 @@ public class Logger LoggerRegistry.setAccess(this); } - public void onPlayerDisconnect(PlayerEntity player) + public void onPlayerDisconnect(Player player) { // If the player was subscribed to the log, move them to the set of offline subscribers. String playerName = player.getName().getString(); diff --git a/src/main/java/carpet/logging/LoggerRegistry.java b/src/main/java/carpet/logging/LoggerRegistry.java index 9a2d84ab..ab5b4ec4 100644 --- a/src/main/java/carpet/logging/LoggerRegistry.java +++ b/src/main/java/carpet/logging/LoggerRegistry.java @@ -2,15 +2,14 @@ package carpet.logging; import carpet.CarpetServer; import carpet.CarpetSettings; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.util.DyeColor; - import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.DyeColor; public class LoggerRegistry { @@ -152,7 +151,7 @@ public class LoggerRegistry loggerRegistry.clear(); playerSubscriptions.clear(); } - public static void playerConnected(PlayerEntity player) + public static void playerConnected(Player player) { boolean firstTime = false; if (!seenPlayers.contains(player.getName().getString())) @@ -167,7 +166,7 @@ public class LoggerRegistry } } - public static void playerDisconnected(PlayerEntity player) + public static void playerDisconnected(Player player) { for(Logger log: loggerRegistry.values() ) { diff --git a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java index 05121056..b14c9641 100644 --- a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java +++ b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java @@ -4,23 +4,22 @@ import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.text.BaseText; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.explosion.Explosion; - import java.util.ArrayList; import java.util.List; +import net.minecraft.core.Registry; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.phys.Vec3; import static carpet.utils.Messenger.c; public class ExplosionLogHelper { private final boolean createFire; - private final Explosion.DestructionType blockDestructionType; - public final Vec3d pos; + private final Explosion.BlockInteraction blockDestructionType; + public final Vec3 pos; public final Entity entity; private final float power; private boolean affectBlocks = false; @@ -30,10 +29,10 @@ public class ExplosionLogHelper private static int explosionCountInCurretGT = 0; private static boolean newTick; - public ExplosionLogHelper(Entity entity, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType blockDestructionType) { + public ExplosionLogHelper(Entity entity, double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType) { this.entity = entity; this.power = power; - this.pos = new Vec3d(x,y,z); + this.pos = new Vec3(x,y,z); this.createFire = createFire; this.blockDestructionType = blockDestructionType; } @@ -53,7 +52,7 @@ public class ExplosionLogHelper } explosionCountInCurretGT++; LoggerRegistry.getLogger("explosions").log( (option) -> { - List messages = new ArrayList<>(); + List messages = new ArrayList<>(); if(newTick) messages.add(c("wb tick : ", "d " + gametime)); if ("brief".equals(option)) { @@ -79,27 +78,27 @@ public class ExplosionLogHelper messages.add(c((k.pos.equals(pos))?"r - TNT":"w - ", Messenger.dblt((k.pos.equals(pos))?"r":"y", k.pos.x, k.pos.y, k.pos.z), "w dV", Messenger.dblt("d", k.accel.x, k.accel.y, k.accel.z), - "w "+Registry.ENTITY_TYPE.getId(k.type).getPath(), (v>1)?"l ("+v+")":"" + "w "+Registry.ENTITY_TYPE.getKey(k.type).getPath(), (v>1)?"l ("+v+")":"" )); }); } } - return messages.toArray(new BaseText[0]); + return messages.toArray(new BaseComponent[0]); }); } - public void onEntityImpacted(Entity entity, Vec3d accel) + public void onEntityImpacted(Entity entity, Vec3 accel) { EntityChangedStatusWithCount ent = new EntityChangedStatusWithCount(entity, accel); impactedEntities.put(ent, impactedEntities.getOrDefault(ent, 0)+1); } - public static record EntityChangedStatusWithCount(Vec3d pos, EntityType type, Vec3d accel) + public static record EntityChangedStatusWithCount(Vec3 pos, EntityType type, Vec3 accel) { - public EntityChangedStatusWithCount(Entity e, Vec3d accel) + public EntityChangedStatusWithCount(Entity e, Vec3 accel) { - this(e.getPos(), e.getType(), accel); + this(e.position(), e.getType(), accel); } } } diff --git a/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java b/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java index 5a876784..ff66ee3c 100644 --- a/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java +++ b/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java @@ -2,18 +2,18 @@ package carpet.logging.logHelpers; import carpet.helpers.ParticleDisplay; import carpet.logging.LoggerRegistry; -import net.minecraft.entity.Entity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.math.Vec3d; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; public class PathfindingVisualizer { - public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) + public static void slowPath(Entity entity, Vec3 target, float miliseconds, boolean successful) { if (!LoggerRegistry.__pathfinding) return; LoggerRegistry.getLogger("pathfinding").log( (option, player)-> { - if (!(player instanceof ServerPlayerEntity)) + if (!(player instanceof ServerPlayer)) return null; int minDuration; try @@ -26,14 +26,14 @@ public class PathfindingVisualizer } if (miliseconds < minDuration) return null; - if (player.squaredDistanceTo(entity) > 1000 && player.squaredDistanceTo(target) > 1000) + if (player.distanceToSqr(entity) > 1000 && player.distanceToSqr(target) > 1000) return null; if (minDuration < 1) minDuration = 1; String accent = successful ? "happy_villager" : "angry_villager"; String color = (miliseconds/minDuration < 2)? "dust 1 1 0 1" : ((miliseconds/minDuration < 4)?"dust 1 0.5 0 1":"dust 1 0 0 1"); - ParticleDisplay.drawParticleLine((ServerPlayerEntity) player, entity.getPos(), target, color, accent, 5, 0.5); + ParticleDisplay.drawParticleLine((ServerPlayer) player, entity.position(), target, color, accent, 5, 0.5); return null; }); } diff --git a/src/main/java/carpet/logging/logHelpers/TNTLogHelper.java b/src/main/java/carpet/logging/logHelpers/TNTLogHelper.java index 371af31a..de2a059c 100644 --- a/src/main/java/carpet/logging/logHelpers/TNTLogHelper.java +++ b/src/main/java/carpet/logging/logHelpers/TNTLogHelper.java @@ -2,8 +2,8 @@ package carpet.logging.logHelpers; import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; -import net.minecraft.text.BaseText; -import net.minecraft.util.math.Vec3d; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.world.phys.Vec3; public class TNTLogHelper { @@ -11,11 +11,11 @@ public class TNTLogHelper private double primedX, primedY, primedZ; private static long lastGametime = 0; private static int tntCount = 0; - private Vec3d primedAngle; + private Vec3 primedAngle; /** * Runs when the TNT is primed. Expects the position and motion angle of the TNT. */ - public void onPrimed(double x, double y, double z, Vec3d motion) + public void onPrimed(double x, double y, double z, Vec3 motion) { primedX = x; primedY = y; @@ -37,12 +37,12 @@ public class TNTLogHelper switch (option) { case "brief": - return new BaseText[]{Messenger.c( + return new BaseComponent[]{Messenger.c( "l P ",Messenger.dblt("l",primedX,primedY,primedZ), "w ",Messenger.dblt("l", primedAngle.x, primedAngle.y, primedAngle.z), "r E ",Messenger.dblt("r",x, y, z))}; case "full": - return new BaseText[]{Messenger.c( + return new BaseComponent[]{Messenger.c( "r #" + tntCount, "m @" + gametime, "g : ", diff --git a/src/main/java/carpet/logging/logHelpers/TrajectoryLogHelper.java b/src/main/java/carpet/logging/logHelpers/TrajectoryLogHelper.java index 4841fb61..50055167 100644 --- a/src/main/java/carpet/logging/logHelpers/TrajectoryLogHelper.java +++ b/src/main/java/carpet/logging/logHelpers/TrajectoryLogHelper.java @@ -3,11 +3,10 @@ package carpet.logging.logHelpers; import carpet.logging.Logger; import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; -import net.minecraft.util.math.Vec3d; -import net.minecraft.text.BaseText; - import java.util.ArrayList; import java.util.List; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.world.phys.Vec3; /** * A generic log helper for logging the trajectory of things like blocks and throwables. @@ -19,8 +18,8 @@ public class TrajectoryLogHelper private boolean doLog; private Logger logger; - private ArrayList positions = new ArrayList<>(); - private ArrayList motions = new ArrayList<>(); + private ArrayList positions = new ArrayList<>(); + private ArrayList motions = new ArrayList<>(); public TrajectoryLogHelper(String logName) { @@ -28,10 +27,10 @@ public class TrajectoryLogHelper this.doLog = this.logger.hasOnlineSubscribers(); } - public void onTick(double x, double y, double z, Vec3d velocity) + public void onTick(double x, double y, double z, Vec3 velocity) { if (!doLog) return; - positions.add(new Vec3d(x, y, z)); + positions.add(new Vec3(x, y, z)); motions.add(velocity); } @@ -39,7 +38,7 @@ public class TrajectoryLogHelper { if (!doLog) return; logger.log( (option) -> { - List comp = new ArrayList<>(); + List comp = new ArrayList<>(); switch (option) { case "brief": @@ -48,8 +47,8 @@ public class TrajectoryLogHelper for (int i = 0; i < positions.size(); i++) { - Vec3d pos = positions.get(i); - Vec3d mot = motions.get(i); + Vec3 pos = positions.get(i); + Vec3 mot = motions.get(i); line.add("w x"); line.add(String.format("^w Tick: %d\nx: %f\ny: %f\nz: %f\n------------\nmx: %f\nmy: %f\nmz: %f", i, pos.x, pos.y, pos.z, mot.x, mot.y, mot.z)); @@ -64,15 +63,15 @@ public class TrajectoryLogHelper comp.add(Messenger.c("w ---------")); for (int i = 0; i < positions.size(); i++) { - Vec3d pos = positions.get(i); - Vec3d mot = motions.get(i); + Vec3 pos = positions.get(i); + Vec3 mot = motions.get(i); comp.add(Messenger.c( String.format("w tick: %3d pos",i),Messenger.dblt("w",pos.x, pos.y, pos.z), "w mot",Messenger.dblt("w",mot.x, mot.y, mot.z))); } break; } - return comp.toArray(new BaseText[0]); + return comp.toArray(new BaseComponent[0]); }); doLog = false; } diff --git a/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java index 66c1e68d..47cd8996 100644 --- a/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java +++ b/src/main/java/carpet/mixins/AbstractCauldronBlock_stackableSBoxesMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.AbstractCauldronBlock; -import net.minecraft.block.BlockState; -import net.minecraft.block.ShulkerBoxBlock; -import net.minecraft.block.cauldron.CauldronBehavior; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.cauldron.CauldronInteraction; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -19,16 +19,16 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(AbstractCauldronBlock.class) public class AbstractCauldronBlock_stackableSBoxesMixin { - @Redirect(method = "onUse", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/cauldron/CauldronBehavior;interact(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/util/Hand;Lnet/minecraft/item/ItemStack;)Lnet/minecraft/util/ActionResult;")) - private ActionResult wrapInteractor(CauldronBehavior cauldronBehavior, BlockState blockState, World world, BlockPos blockPos, PlayerEntity playerEntity, Hand hand, ItemStack itemStack) + @Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/cauldron/CauldronInteraction;interact(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/InteractionResult;")) + private InteractionResult wrapInteractor(CauldronInteraction cauldronBehavior, BlockState blockState, Level world, BlockPos blockPos, Player playerEntity, InteractionHand hand, ItemStack itemStack) { int count = -1; if (CarpetSettings.shulkerBoxStackSize > 1 && itemStack.getItem() instanceof BlockItem && ((BlockItem)itemStack.getItem()).getBlock() instanceof ShulkerBoxBlock) count = itemStack.getCount(); - ActionResult result = cauldronBehavior.interact(blockState, world, blockPos, playerEntity, hand, itemStack); - if (count > 0 && result.isAccepted()) + InteractionResult result = cauldronBehavior.interact(blockState, world, blockPos, playerEntity, hand, itemStack); + if (count > 0 && result.consumesAction()) { - ItemStack current = playerEntity.getStackInHand(hand); + ItemStack current = playerEntity.getItemInHand(hand); if (current.getItem() instanceof BlockItem && ((BlockItem)itemStack.getItem()).getBlock() instanceof ShulkerBoxBlock) current.setCount(count); } diff --git a/src/main/java/carpet/mixins/AbstractRecipeScreenHandler_scarpetMixin.java b/src/main/java/carpet/mixins/AbstractRecipeScreenHandler_scarpetMixin.java index 151c272b..86da2daf 100644 --- a/src/main/java/carpet/mixins/AbstractRecipeScreenHandler_scarpetMixin.java +++ b/src/main/java/carpet/mixins/AbstractRecipeScreenHandler_scarpetMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.fakes.ScreenHandlerInterface; -import net.minecraft.recipe.Recipe; -import net.minecraft.screen.AbstractRecipeScreenHandler; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.inventory.RecipeBookMenu; +import net.minecraft.world.item.crafting.Recipe; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(AbstractRecipeScreenHandler.class) +@Mixin(RecipeBookMenu.class) public class AbstractRecipeScreenHandler_scarpetMixin { - @Inject(method = "fillInputSlots",at = @At("HEAD"), cancellable = true) - private void selectRecipeCallback(boolean craftAll, Recipe recipe, ServerPlayerEntity player, CallbackInfo ci) { + @Inject(method = "handlePlacement",at = @At("HEAD"), cancellable = true) + private void selectRecipeCallback(boolean craftAll, Recipe recipe, ServerPlayer player, CallbackInfo ci) { if(((ScreenHandlerInterface) this).callSelectRecipeListener(player,recipe,craftAll)) ci.cancel(); } diff --git a/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java b/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java index 9150fa92..cdfe9a1e 100644 --- a/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java +++ b/src/main/java/carpet/mixins/ArmorStandEntity_scarpetMarkerMixin.java @@ -2,10 +2,6 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.script.api.Auxiliary; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.decoration.ArmorStandEntity; -import net.minecraft.world.World; import org.apache.commons.lang3.StringUtils; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -13,11 +9,15 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Optional; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.level.Level; -@Mixin(ArmorStandEntity.class) +@Mixin(ArmorStand.class) public abstract class ArmorStandEntity_scarpetMarkerMixin extends LivingEntity { - protected ArmorStandEntity_scarpetMarkerMixin(EntityType entityType_1, World world_1) + protected ArmorStandEntity_scarpetMarkerMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } @@ -26,15 +26,15 @@ public abstract class ArmorStandEntity_scarpetMarkerMixin extends LivingEntity * Remove all markers that do not belong to any script host and not part of the global one when loaded * @param ci */ - @Inject(method = "readCustomDataFromNbt", at = @At("HEAD")) + @Inject(method = "readAdditionalSaveData", at = @At("HEAD")) private void checkScarpetMarkerUnloaded(CallbackInfo ci) { - if (!world.isClient) + if (!level.isClientSide) { - if (getScoreboardTags().contains(Auxiliary.MARKER_STRING)) + if (getTags().contains(Auxiliary.MARKER_STRING)) { String prefix = Auxiliary.MARKER_STRING+"_"; - Optional owner = getScoreboardTags().stream().filter(s -> s.startsWith(prefix)).findFirst(); + Optional owner = getTags().stream().filter(s -> s.startsWith(prefix)).findFirst(); if (owner.isPresent()) { String hostName = StringUtils.removeStart(owner.get(),prefix); diff --git a/src/main/java/carpet/mixins/BarrierBlock_updateSuppressionBlockMixin.java b/src/main/java/carpet/mixins/BarrierBlock_updateSuppressionBlockMixin.java index 44b5665c..ea9cff32 100644 --- a/src/main/java/carpet/mixins/BarrierBlock_updateSuppressionBlockMixin.java +++ b/src/main/java/carpet/mixins/BarrierBlock_updateSuppressionBlockMixin.java @@ -1,54 +1,54 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BarrierBlock; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.PoweredRailBlock; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BarrierBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.PoweredRailBlock; +import net.minecraft.world.level.block.state.BlockState; @Mixin(BarrierBlock.class) public class BarrierBlock_updateSuppressionBlockMixin extends Block { private boolean shouldPower = false; - public BarrierBlock_updateSuppressionBlockMixin(Settings settings) { super(settings); } + public BarrierBlock_updateSuppressionBlockMixin(Properties settings) { super(settings); } @Override - public int getWeakRedstonePower(BlockState state, BlockView world, BlockPos pos, Direction direction) { + public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction direction) { return (shouldPower && direction == Direction.DOWN) ? 15 : 0; } @Override - public void neighborUpdate(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { + public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { if (CarpetSettings.updateSuppressionBlockSetting != -1) { - if (fromPos.equals(pos.up())) { + if (fromPos.equals(pos.above())) { BlockState stateAbove = world.getBlockState(fromPos); - if (stateAbove.isOf(Blocks.ACTIVATOR_RAIL) && !stateAbove.get(PoweredRailBlock.POWERED)) { + if (stateAbove.is(Blocks.ACTIVATOR_RAIL) && !stateAbove.getValue(PoweredRailBlock.POWERED)) { if (CarpetSettings.updateSuppressionBlockSetting > 0) { - world.createAndScheduleBlockTick(pos, this, CarpetSettings.updateSuppressionBlockSetting); + world.scheduleTick(pos, this, CarpetSettings.updateSuppressionBlockSetting); } throw new StackOverflowError("updateSuppressionBlock"); } } } - super.neighborUpdate(state, world, pos, block, fromPos, notify); + super.neighborChanged(state, world, pos, block, fromPos, notify); } @Override - public void scheduledTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { - BlockPos posAbove = pos.up(); + public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { + BlockPos posAbove = pos.above(); BlockState stateAbove = world.getBlockState(posAbove); - if (stateAbove.isOf(Blocks.ACTIVATOR_RAIL) && !stateAbove.get(PoweredRailBlock.POWERED)) { + if (stateAbove.is(Blocks.ACTIVATOR_RAIL) && !stateAbove.getValue(PoweredRailBlock.POWERED)) { shouldPower = true; - world.setBlockState(posAbove, stateAbove.with(PoweredRailBlock.POWERED, true), 3); + world.setBlock(posAbove, stateAbove.setValue(PoweredRailBlock.POWERED, true), 3); shouldPower = false; } } diff --git a/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java b/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java index 32ef1331..512df06a 100644 --- a/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java +++ b/src/main/java/carpet/mixins/BastionRemnantFeatureMixin.java @@ -4,20 +4,13 @@ import carpet.CarpetSettings; import com.google.common.collect.Lists; import com.mojang.serialization.Codec; -import net.minecraft.entity.EntityType; -import net.minecraft.util.collection.Pool; -import net.minecraft.world.MobSpawnerLogic; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.gen.feature.BastionRemnantFeature; - -import net.minecraft.world.gen.feature.JigsawFeature; -import net.minecraft.world.gen.feature.StructurePoolFeatureConfig; import org.spongepowered.asm.mixin.Mixin; import java.util.Collections; import java.util.List; +import net.minecraft.world.level.levelgen.feature.BastionFeature; -@Mixin(BastionRemnantFeature.class) +@Mixin(BastionFeature.class) public abstract class BastionRemnantFeatureMixin //extends JigsawFeature { /* diff --git a/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java b/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java index 93c104d7..7dc2e5d3 100644 --- a/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java +++ b/src/main/java/carpet/mixins/BiomeArray_getBiomeArrayMixin.java @@ -1,12 +1,6 @@ package carpet.mixins; import carpet.fakes.BiomeArrayInterface; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -//import net.minecraft.world.biome.source.BiomeArray; -import net.minecraft.world.biome.source.BiomeCoords; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/main/java/carpet/mixins/BlazeEntityShootFireballGoal_extremeMixin.java b/src/main/java/carpet/mixins/BlazeEntityShootFireballGoal_extremeMixin.java index cf82dd89..0fca369c 100644 --- a/src/main/java/carpet/mixins/BlazeEntityShootFireballGoal_extremeMixin.java +++ b/src/main/java/carpet/mixins/BlazeEntityShootFireballGoal_extremeMixin.java @@ -7,7 +7,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; -@Mixin(targets = "net.minecraft.entity.mob.BlazeEntity$ShootFireballGoal") +@Mixin(targets = "net.minecraft.world.entity.monster.Blaze$BlazeAttackGoal") public class BlazeEntityShootFireballGoal_extremeMixin { @Redirect(method = "tick()V", expect = 2, at = @At( diff --git a/src/main/java/carpet/mixins/BlazeEntity_extremeMixin.java b/src/main/java/carpet/mixins/BlazeEntity_extremeMixin.java index ce30387c..ecce1c38 100644 --- a/src/main/java/carpet/mixins/BlazeEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/BlazeEntity_extremeMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.mob.BlazeEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.monster.Blaze; -@Mixin(BlazeEntity.class) +@Mixin(Blaze.class) public class BlazeEntity_extremeMixin { // unused actually - @Redirect(method = "mobTick", expect = 1, at = @At( + @Redirect(method = "customServerAiStep", expect = 1, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java b/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java index a848ee2e..a0436244 100644 --- a/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java +++ b/src/main/java/carpet/mixins/BlockEntity_movableBEMixin.java @@ -1,8 +1,8 @@ package carpet.mixins; import carpet.fakes.BlockEntityInterface; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.entity.BlockEntity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; @@ -12,10 +12,10 @@ import org.spongepowered.asm.mixin.Shadow; public abstract class BlockEntity_movableBEMixin implements BlockEntityInterface { @Mutable - @Shadow @Final protected BlockPos pos; + @Shadow @Final protected BlockPos worldPosition; public void setCMPos(BlockPos newPos) { - pos = newPos; + worldPosition = newPos; }; } diff --git a/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java b/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java index eb1769b5..a89577f5 100644 --- a/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/BlockItem_creativeNoClipMixin.java @@ -1,14 +1,14 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.ShapeContext; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -18,19 +18,19 @@ public class BlockItem_creativeNoClipMixin { @Redirect(method = "canPlace", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/World;canPlace(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/ShapeContext;)Z" + target = "Lnet/minecraft/world/level/Level;isUnobstructed(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Z" )) - private boolean canSpectatingPlace(World world, BlockState state, BlockPos pos, ShapeContext context, - ItemPlacementContext contextOuter, BlockState stateOuter) + private boolean canSpectatingPlace(Level world, BlockState state, BlockPos pos, CollisionContext context, + BlockPlaceContext contextOuter, BlockState stateOuter) { - PlayerEntity player = contextOuter.getPlayer(); + Player player = contextOuter.getPlayer(); if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.getAbilities().flying) { // copy from canPlace VoxelShape voxelShape = state.getCollisionShape(world, pos, context); - return voxelShape.isEmpty() || world.doesNotIntersectEntities(player, voxelShape.offset(pos.getX(), pos.getY(), pos.getZ())); + return voxelShape.isEmpty() || world.isUnobstructed(player, voxelShape.move(pos.getX(), pos.getY(), pos.getZ())); } - return world.canPlace(state, pos, context); + return world.isUnobstructed(state, pos, context); } } diff --git a/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java b/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java index e6f1092b..c3516759 100644 --- a/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java @@ -1,9 +1,5 @@ package carpet.mixins; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.ActionResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -11,17 +7,22 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import static carpet.script.CarpetEventServer.Event.PLAYER_PLACES_BLOCK; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.context.BlockPlaceContext; + @Mixin(BlockItem.class) public class BlockItem_scarpetEventMixin { - @Inject(method = "place(Lnet/minecraft/item/ItemPlacementContext;)Lnet/minecraft/util/ActionResult;", at = @At( + @Inject(method = "place(Lnet/minecraft/world/item/context/BlockPlaceContext;)Lnet/minecraft/world/InteractionResult;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/Block;onPlaced(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/item/ItemStack;)V", + target = "Lnet/minecraft/world/level/block/Block;setPlacedBy(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/item/ItemStack;)V", shift = At.Shift.AFTER )) - private void afterPlacement(ItemPlacementContext context, CallbackInfoReturnable cir) + private void afterPlacement(BlockPlaceContext context, CallbackInfoReturnable cir) { - if (context.getPlayer() instanceof ServerPlayerEntity && PLAYER_PLACES_BLOCK.isNeeded()) - PLAYER_PLACES_BLOCK.onBlockPlaced((ServerPlayerEntity) context.getPlayer(), context.getBlockPos(), context.getHand(), context.getStack()); + if (context.getPlayer() instanceof ServerPlayer && PLAYER_PLACES_BLOCK.isNeeded()) + PLAYER_PLACES_BLOCK.onBlockPlaced((ServerPlayer) context.getPlayer(), context.getClickedPos(), context.getHand(), context.getItemInHand()); } } diff --git a/src/main/java/carpet/mixins/BlockLightStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/BlockLightStorage_scarpetChunkCreationMixin.java index 2e700c1e..abf20a55 100644 --- a/src/main/java/carpet/mixins/BlockLightStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/BlockLightStorage_scarpetChunkCreationMixin.java @@ -4,55 +4,55 @@ import org.spongepowered.asm.mixin.Mixin; import carpet.fakes.ChunkLightProviderInterface; import carpet.fakes.LightStorageInterface; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.LightType; -import net.minecraft.world.chunk.ChunkNibbleArray; -import net.minecraft.world.chunk.ChunkProvider; -import net.minecraft.world.chunk.light.BlockLightStorage; -import net.minecraft.world.chunk.light.BlockLightStorage.Data; -import net.minecraft.world.chunk.light.ChunkLightProvider; -import net.minecraft.world.chunk.light.LightStorage; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.chunk.LightChunkGetter; +import net.minecraft.world.level.lighting.BlockLightSectionStorage; +import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap; +import net.minecraft.world.level.lighting.LayerLightEngine; +import net.minecraft.world.level.lighting.LayerLightSectionStorage; -@Mixin(BlockLightStorage.class) -public abstract class BlockLightStorage_scarpetChunkCreationMixin extends LightStorage implements LightStorageInterface +@Mixin(BlockLightSectionStorage.class) +public abstract class BlockLightStorage_scarpetChunkCreationMixin extends LayerLightSectionStorage implements LightStorageInterface { - private BlockLightStorage_scarpetChunkCreationMixin(final LightType lightType, final ChunkProvider chunkProvider, final Data lightData) + private BlockLightStorage_scarpetChunkCreationMixin(final LightLayer lightType, final LightChunkGetter chunkProvider, final BlockDataLayerStorageMap lightData) { super(lightType, chunkProvider, lightData); } @Override - public void processRelight(final ChunkLightProvider lightProvider, final long cPos) + public void processRelight(final LayerLightEngine lightProvider, final long cPos) { final LevelPropagator_resetChunkInterface levelPropagator = (LevelPropagator_resetChunkInterface) lightProvider; for (int y = -1; y < 17; ++y) { - final long sectionPos = ChunkSectionPos.asLong(ChunkSectionPos.unpackX(cPos), y, ChunkSectionPos.unpackZ(cPos)); - final long pos = BlockPos.asLong(ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackX(sectionPos)), ChunkSectionPos.getBlockCoord(y), ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackZ(sectionPos))); + final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); + final long pos = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(sectionPos)), SectionPos.sectionToBlockCoord(y), SectionPos.sectionToBlockCoord(SectionPos.z(sectionPos))); - if (!this.hasSection(sectionPos)) + if (!this.storingLightForSection(sectionPos)) continue; - for (final Direction dir : Direction.Type.HORIZONTAL) + for (final Direction dir : Direction.Plane.HORIZONTAL) { - final ChunkNibbleArray neighborLightArray = this.getLightSection(ChunkSectionPos.offset(sectionPos, dir)); + final DataLayer neighborLightArray = this.getDataLayerData(SectionPos.offset(sectionPos, dir)); if (neighborLightArray == null) continue; - final int ox = 15 * Math.max(dir.getOffsetX(), 0); - final int oz = 15 * Math.max(dir.getOffsetZ(), 0); + final int ox = 15 * Math.max(dir.getStepX(), 0); + final int oz = 15 * Math.max(dir.getStepZ(), 0); - final int dx = Math.abs(dir.getOffsetZ()); - final int dz = Math.abs(dir.getOffsetX()); + final int dx = Math.abs(dir.getStepZ()); + final int dz = Math.abs(dir.getStepX()); for (int t = 0; t < 16; ++t) for (int dy = 0; dy < 16; ++dy) { - final long dst = BlockPos.add(pos, ox + t * dx, dy, oz + t * dz); + final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); final long src = BlockPos.offset(dst, dir); final int srcLevel = ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborLightArray, src); diff --git a/src/main/java/carpet/mixins/BlockStateArgument_fillUpdatesMixin.java b/src/main/java/carpet/mixins/BlockStateArgument_fillUpdatesMixin.java index 0cd7abaa..225e28c2 100644 --- a/src/main/java/carpet/mixins/BlockStateArgument_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/BlockStateArgument_fillUpdatesMixin.java @@ -5,26 +5,26 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.WorldAccess; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; -@Mixin(BlockStateArgument.class) +@Mixin(BlockInput.class) public class BlockStateArgument_fillUpdatesMixin { - @Redirect(method = "setBlockState", at = @At( + @Redirect(method = "place", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/Block;postProcessState(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/WorldAccess;Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;" + target = "Lnet/minecraft/world/level/block/Block;updateFromNeighbourShapes(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;" )) - private BlockState postProcessStateProxy(BlockState state, WorldAccess serverWorld, BlockPos blockPos) + private BlockState postProcessStateProxy(BlockState state, LevelAccessor serverWorld, BlockPos blockPos) { if (CarpetSettings.impendingFillSkipUpdates.get()) { return state; } - return Block.postProcessState(state, serverWorld, blockPos); + return Block.updateFromNeighbourShapes(state, serverWorld, blockPos); } } diff --git a/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java b/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java index 16d905c7..477ce298 100644 --- a/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java +++ b/src/main/java/carpet/mixins/BlockStateArgument_scarpetMixin.java @@ -1,21 +1,21 @@ package carpet.mixins; import carpet.fakes.BlockStateArgumentInterface; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.nbt.CompoundTag; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(BlockStateArgument.class) +@Mixin(BlockInput.class) public class BlockStateArgument_scarpetMixin implements BlockStateArgumentInterface { - @Shadow @Final private @Nullable NbtCompound data; + @Shadow @Final private @Nullable CompoundTag tag; @Override - public NbtCompound getCMTag() + public CompoundTag getCMTag() { - return data; + return tag; } } diff --git a/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java index 3e9c2449..6984a673 100644 --- a/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java +++ b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java @@ -1,19 +1,19 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.BuddingAmethystBlock; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.piston.PistonBehavior; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.enchantment.Enchantments; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.item.PickaxeItem; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.PickaxeItem; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.BuddingAmethystBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.PushReaction; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -22,24 +22,24 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(BuddingAmethystBlock.class) public class BuddingAmethystBlock_movableAmethystMixin extends Block { - public BuddingAmethystBlock_movableAmethystMixin(Settings settings) { + public BuddingAmethystBlock_movableAmethystMixin(Properties settings) { super(settings); } - @Inject(at = @At("HEAD"), method = "getPistonBehavior(Lnet/minecraft/block/BlockState;)Lnet/minecraft/block/piston/PistonBehavior;", cancellable = true) - void getPistonBehavior(BlockState state, CallbackInfoReturnable cir) { - if (CarpetSettings.movableAmethyst) cir.setReturnValue(PistonBehavior.NORMAL); + @Inject(at = @At("HEAD"), method = "getPistonPushReaction(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/world/level/material/PushReaction;", cancellable = true) + void getPistonBehavior(BlockState state, CallbackInfoReturnable cir) { + if (CarpetSettings.movableAmethyst) cir.setReturnValue(PushReaction.NORMAL); } @Override - public void afterBreak(World world, PlayerEntity player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) { - super.afterBreak(world, player, pos, state, blockEntity, stack); + public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) { + super.playerDestroy(world, player, pos, state, blockEntity, stack); // doing it here rather than though loottables since loottables are loaded on reload // drawback - not controlled via loottables, but hey if (CarpetSettings.movableAmethyst && stack.getItem() instanceof PickaxeItem && - EnchantmentHelper.getLevel(Enchantments.SILK_TOUCH, stack) > 0 + EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0 ) - dropStack(world, pos, Items.BUDDING_AMETHYST.getDefaultStack()); + popResource(world, pos, Items.BUDDING_AMETHYST.getDefaultInstance()); } } diff --git a/src/main/java/carpet/mixins/CarpetBlockMixin.java b/src/main/java/carpet/mixins/CarpetBlockMixin.java index 32b4b481..887e8930 100644 --- a/src/main/java/carpet/mixins/CarpetBlockMixin.java +++ b/src/main/java/carpet/mixins/CarpetBlockMixin.java @@ -1,28 +1,28 @@ package carpet.mixins; import carpet.utils.WoolTool; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.DyedCarpetBlock; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.WoolCarpetBlock; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; -@Mixin(DyedCarpetBlock.class) // WoolCarpetBlock +@Mixin(WoolCarpetBlock.class) // WoolCarpetBlock public abstract class CarpetBlockMixin extends Block { - public CarpetBlockMixin(Settings block$Settings_1) + public CarpetBlockMixin(Properties block$Settings_1) { super(block$Settings_1); } - public BlockState getPlacementState(ItemPlacementContext context) + public BlockState getStateForPlacement(BlockPlaceContext context) { - BlockState state = super.getPlacementState(context); - if (context.getPlayer() != null && !context.getWorld().isClient) + BlockState state = super.getStateForPlacement(context); + if (context.getPlayer() != null && !context.getLevel().isClientSide) { // getColor() - WoolTool.carpetPlacedAction(((DyedCarpetBlock)(Object)this).getDyeColor(), context.getPlayer(), context.getBlockPos(), (ServerWorld) context.getWorld()); + WoolTool.carpetPlacedAction(((WoolCarpetBlock)(Object)this).getColor(), context.getPlayer(), context.getClickedPos(), (ServerLevel) context.getLevel()); } return state; } diff --git a/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java index be348daf..26b5ff7a 100644 --- a/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java +++ b/src/main/java/carpet/mixins/CauldronBlock_stackableSBoxesMixin.java @@ -1,16 +1,7 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.CauldronBlock; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.world.level.block.CauldronBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/main/java/carpet/mixins/CaveScalerMixin_scarpetMixin.java b/src/main/java/carpet/mixins/CaveScalerMixin_scarpetMixin.java index c363eb7d..9a249d61 100644 --- a/src/main/java/carpet/mixins/CaveScalerMixin_scarpetMixin.java +++ b/src/main/java/carpet/mixins/CaveScalerMixin_scarpetMixin.java @@ -1,14 +1,14 @@ package carpet.mixins; -import net.minecraft.world.gen.NoiseColumnSampler; +import net.minecraft.world.level.levelgen.NoiseSampler; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; -@Mixin(NoiseColumnSampler.CaveScaler.class) +@Mixin(NoiseSampler.QuantizedSpaghettiRarity.class) public interface CaveScalerMixin_scarpetMixin { @Invoker - static double invokeScaleTunnels(double d) { + static double invokeGetSpaghettiRarity3D(double d) { throw new AssertionError(); } } diff --git a/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java b/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java index 1fd3fd76..68fb35cd 100644 --- a/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java @@ -1,25 +1,25 @@ package carpet.mixins; import carpet.fakes.ChunkGeneratorInterface; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.chunk.ChunkGenerator; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(ChunkGenerator.class) public abstract class ChunkGenerator_scarpetMixin implements ChunkGeneratorInterface { - @Shadow protected abstract void generateStrongholdPositions(); - @Shadow private static boolean canPlaceStrongholdInBiome(Biome biome) { return true;} + @Shadow protected abstract void generateStrongholds(); + @Shadow private static boolean validStrongholdBiome(Biome biome) { return true;} @Override public void initStrongholds() { - generateStrongholdPositions(); + generateStrongholds(); } @Override public boolean canPlaceStrongholdInBiomeCM(Biome biome) { - return canPlaceStrongholdInBiome(biome); + return validStrongholdBiome(biome); } } diff --git a/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java index 46d27686..0f9e5044 100644 --- a/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkHolder_scarpetChunkCreationMixin.java @@ -2,39 +2,39 @@ package carpet.mixins; import carpet.fakes.ChunkHolderInterface; import com.mojang.datafixers.util.Either; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.thread.ThreadExecutor; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.chunk.ProtoChunk; -import net.minecraft.world.chunk.UpgradeData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReferenceArray; +import net.minecraft.core.Registry; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.thread.BlockableEventLoop; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.ProtoChunk; +import net.minecraft.world.level.chunk.UpgradeData; @Mixin(ChunkHolder.class) public abstract class ChunkHolder_scarpetChunkCreationMixin implements ChunkHolderInterface { - @Shadow protected abstract void combineSavingFuture(CompletableFuture> newChunkFuture, String type); + @Shadow protected abstract void updateChunkToSave(CompletableFuture> newChunkFuture, String type); - @Shadow @Final private AtomicReferenceArray>> futuresByStatus; + @Shadow @Final private AtomicReferenceArray>> futures; @Override - public CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, ThreadExecutor executor, ServerWorld world) + public CompletableFuture> setDefaultProtoChunk(ChunkPos chpos, BlockableEventLoop executor, ServerLevel world) { int i = ChunkStatus.EMPTY.getIndex(); - CompletableFuture> completableFuture2 = CompletableFuture.supplyAsync( - () -> Either.left(new ProtoChunk(chpos, UpgradeData.NO_UPGRADE_DATA, world, world.getRegistryManager().get(Registry.BIOME_KEY), null)), // todo figure out what that does - maybe add an option to reset with blending enabled..? + CompletableFuture> completableFuture2 = CompletableFuture.supplyAsync( + () -> Either.left(new ProtoChunk(chpos, UpgradeData.EMPTY, world, world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), null)), // todo figure out what that does - maybe add an option to reset with blending enabled..? executor ); - combineSavingFuture(completableFuture2, "unfull"); // possible debug data - futuresByStatus.set(i, completableFuture2); + updateChunkToSave(completableFuture2, "unfull"); // possible debug data + futures.set(i, completableFuture2); return completableFuture2; } } diff --git a/src/main/java/carpet/mixins/ChunkLightProvider_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkLightProvider_scarpetChunkCreationMixin.java index 37728338..82f497d6 100644 --- a/src/main/java/carpet/mixins/ChunkLightProvider_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkLightProvider_scarpetChunkCreationMixin.java @@ -7,30 +7,30 @@ import org.spongepowered.asm.mixin.gen.Invoker; import carpet.fakes.ChunkLightProviderInterface; import carpet.fakes.Lighting_scarpetChunkCreationInterface; -import net.minecraft.world.chunk.ChunkNibbleArray; -import net.minecraft.world.chunk.light.ChunkLightProvider; -import net.minecraft.world.chunk.light.LightStorage; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.lighting.LayerLightEngine; +import net.minecraft.world.level.lighting.LayerLightSectionStorage; -@Mixin(ChunkLightProvider.class) +@Mixin(LayerLightEngine.class) public abstract class ChunkLightProvider_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface, ChunkLightProviderInterface { @Shadow @Final - protected LightStorage lightStorage; + protected LayerLightSectionStorage storage; @Override public void removeLightData(final long pos) { - ((Lighting_scarpetChunkCreationInterface) this.lightStorage).removeLightData(pos); + ((Lighting_scarpetChunkCreationInterface) this.storage).removeLightData(pos); } @Override public void relight(final long pos) { - ((Lighting_scarpetChunkCreationInterface) this.lightStorage).relight(pos); + ((Lighting_scarpetChunkCreationInterface) this.storage).relight(pos); } @Override - @Invoker("getCurrentLevelFromSection") - public abstract int callGetCurrentLevelFromSection(ChunkNibbleArray array, long blockPos); + @Invoker("getLevel") + public abstract int callGetCurrentLevelFromSection(DataLayer array, long blockPos); } diff --git a/src/main/java/carpet/mixins/ChunkMixin.java b/src/main/java/carpet/mixins/ChunkMixin.java index 5ae9c74e..40f45099 100644 --- a/src/main/java/carpet/mixins/ChunkMixin.java +++ b/src/main/java/carpet/mixins/ChunkMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.Chunk; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.chunk.ChunkAccess; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(Chunk.class) +@Mixin(ChunkAccess.class) public abstract class ChunkMixin { // failed to mixin into interface. need to mixin in two places that uses it - @Inject(method = "markBlockForPostProcessing(Lnet/minecraft/util/math/BlockPos;)V", + @Inject(method = "markPosForPostprocessing(Lnet/minecraft/core/BlockPos;)V", at =@At("HEAD"), cancellable = true) private void squashWarnings(BlockPos blockPos_1, CallbackInfo ci) { diff --git a/src/main/java/carpet/mixins/ChunkRegion_scarpetPlopMixin.java b/src/main/java/carpet/mixins/ChunkRegion_scarpetPlopMixin.java index f4a11509..8558a966 100644 --- a/src/main/java/carpet/mixins/ChunkRegion_scarpetPlopMixin.java +++ b/src/main/java/carpet/mixins/ChunkRegion_scarpetPlopMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ChunkRegion; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.WorldGenRegion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ChunkRegion.class) +@Mixin(WorldGenRegion.class) public class ChunkRegion_scarpetPlopMixin { - @Inject(method = "markBlockForPostProcessing", at = @At("HEAD"), cancellable = true) + @Inject(method = "markPosForPostprocessing", at = @At("HEAD"), cancellable = true) private void markOrNot(BlockPos blockPos, CallbackInfo ci) { if (CarpetSettings.skipGenerationChecks.get()) ci.cancel(); diff --git a/src/main/java/carpet/mixins/ChunkTicketManager_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkTicketManager_scarpetChunkCreationMixin.java index f5aaf552..531ad681 100644 --- a/src/main/java/carpet/mixins/ChunkTicketManager_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkTicketManager_scarpetChunkCreationMixin.java @@ -1,26 +1,25 @@ package carpet.mixins; import java.util.Set; - +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.DistanceManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import carpet.fakes.ChunkTicketManagerInterface; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ChunkTicketManager; -@Mixin(ChunkTicketManager.class) +@Mixin(DistanceManager.class) public abstract class ChunkTicketManager_scarpetChunkCreationMixin implements ChunkTicketManagerInterface { @Shadow @Final - private Set chunkHolders; + private Set chunksToUpdateFutures; @Override public void replaceHolder(final ChunkHolder oldHolder, final ChunkHolder newHolder) { - this.chunkHolders.remove(oldHolder); - this.chunkHolders.add(newHolder); + this.chunksToUpdateFutures.remove(oldHolder); + this.chunksToUpdateFutures.add(newHolder); } } diff --git a/src/main/java/carpet/mixins/ChunkTicketManager_scarpetMixin.java b/src/main/java/carpet/mixins/ChunkTicketManager_scarpetMixin.java index e22b9bda..36843e9e 100644 --- a/src/main/java/carpet/mixins/ChunkTicketManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ChunkTicketManager_scarpetMixin.java @@ -2,22 +2,22 @@ package carpet.mixins; import carpet.fakes.ChunkTicketManagerInterface; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import net.minecraft.server.world.ChunkTicket; -import net.minecraft.server.world.ChunkTicketManager; -import net.minecraft.util.collection.SortedArraySet; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.Ticket; +import net.minecraft.util.SortedArraySet; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(ChunkTicketManager.class) +@Mixin(DistanceManager.class) public abstract class ChunkTicketManager_scarpetMixin implements ChunkTicketManagerInterface { - @Shadow @Final private Long2ObjectOpenHashMap>> ticketsByPosition; + @Shadow @Final private Long2ObjectOpenHashMap>> tickets; @Override - public Long2ObjectOpenHashMap>> getTicketsByPosition() + public Long2ObjectOpenHashMap>> getTicketsByPosition() { - return ticketsByPosition; + return tickets; } } diff --git a/src/main/java/carpet/mixins/ChunkTicketManager_spawnChunksMixin.java b/src/main/java/carpet/mixins/ChunkTicketManager_spawnChunksMixin.java index 3873c8ed..f4270e46 100644 --- a/src/main/java/carpet/mixins/ChunkTicketManager_spawnChunksMixin.java +++ b/src/main/java/carpet/mixins/ChunkTicketManager_spawnChunksMixin.java @@ -2,40 +2,40 @@ package carpet.mixins; import carpet.fakes.ChunkTicketManagerInterface; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import net.minecraft.server.world.ChunkTicket; -import net.minecraft.server.world.ChunkTicketManager; -import net.minecraft.server.world.ChunkTicketType; -import net.minecraft.util.collection.SortedArraySet; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.Ticket; +import net.minecraft.server.level.TicketType; +import net.minecraft.util.SortedArraySet; import net.minecraft.util.Unit; -import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.level.ChunkPos; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.Iterator; -@Mixin(ChunkTicketManager.class) +@Mixin(DistanceManager.class) public abstract class ChunkTicketManager_spawnChunksMixin implements ChunkTicketManagerInterface { - @Shadow @Final private Long2ObjectOpenHashMap>> ticketsByPosition; + @Shadow @Final private Long2ObjectOpenHashMap>> tickets; - @Shadow protected abstract void removeTicket(long pos, ChunkTicket ticket); + @Shadow protected abstract void removeTicket(long pos, Ticket ticket); - @Shadow public abstract void addTicket(ChunkTicketType type, ChunkPos pos, int radius, T argument); + @Shadow public abstract void addRegionTicket(TicketType type, ChunkPos pos, int radius, T argument); @Override public void changeSpawnChunks(ChunkPos chunkPos, int distance) { long pos = chunkPos.toLong(); - SortedArraySet> set = ticketsByPosition.get(pos); - ChunkTicket existingTicket = null; + SortedArraySet> set = tickets.get(pos); + Ticket existingTicket = null; if (set != null) { - Iterator> iter = set.iterator(); + Iterator> iter = set.iterator(); while(iter.hasNext()) { - ChunkTicket ticket = iter.next(); - if (ticket.getType() == ChunkTicketType.START) + Ticket ticket = iter.next(); + if (ticket.getType() == TicketType.START) { existingTicket = ticket; iter.remove(); @@ -50,6 +50,6 @@ public abstract class ChunkTicketManager_spawnChunksMixin implements ChunkTicket } // set optionally new spawn ticket if (distance > 0) - addTicket(ChunkTicketType.START, chunkPos, distance, Unit.INSTANCE); + addRegionTicket(TicketType.START, chunkPos, distance, Unit.INSTANCE); } } diff --git a/src/main/java/carpet/mixins/ChunkTicketManager_tickMixin.java b/src/main/java/carpet/mixins/ChunkTicketManager_tickMixin.java index bbaeea46..4f22f6e4 100644 --- a/src/main/java/carpet/mixins/ChunkTicketManager_tickMixin.java +++ b/src/main/java/carpet/mixins/ChunkTicketManager_tickMixin.java @@ -1,23 +1,23 @@ package carpet.mixins; import carpet.helpers.TickSpeed; -import net.minecraft.server.world.ChunkTicketManager; +import net.minecraft.server.level.DistanceManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ChunkTicketManager.class) +@Mixin(DistanceManager.class) public class ChunkTicketManager_tickMixin { - @Shadow private long age; + @Shadow private long ticketTickCounter; - @Inject(method = "purge", at = @At("HEAD"), cancellable = true) + @Inject(method = "purgeStaleTickets", at = @At("HEAD"), cancellable = true) private void pauseTicketSystem(CallbackInfo ci) { // pausing expiry of tickets // that will prevent also chunks from unloading, so require a deep frozen state - if (!TickSpeed.process_entities && TickSpeed.deeplyFrozen()) age--; + if (!TickSpeed.process_entities && TickSpeed.deeplyFrozen()) ticketTickCounter--; } } diff --git a/src/main/java/carpet/mixins/ClientConnectionMixin.java b/src/main/java/carpet/mixins/ClientConnectionMixin.java index 7d245809..1109338b 100644 --- a/src/main/java/carpet/mixins/ClientConnectionMixin.java +++ b/src/main/java/carpet/mixins/ClientConnectionMixin.java @@ -6,15 +6,15 @@ import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; -import net.minecraft.network.ClientConnection; -import net.minecraft.network.Packet; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ClientConnection.class) +@Mixin(Connection.class) public abstract class ClientConnectionMixin implements ClientConnectionInterface { // Add to the packet counter whenever a packet is received. @@ -25,7 +25,7 @@ public abstract class ClientConnectionMixin implements ClientConnectionInterface } // Add to the packet counter whenever a packet is sent. - @Inject(method = "sendImmediately", at = @At("HEAD")) + @Inject(method = "sendPacket", at = @At("HEAD")) private void packetOutCount(Packet packet_1, GenericFutureListener> genericFutureListener_1, CallbackInfo ci) { diff --git a/src/main/java/carpet/mixins/ClientPlayNetworkHandlerMixin.java b/src/main/java/carpet/mixins/ClientPlayNetworkHandlerMixin.java index 362828ea..f14243fc 100644 --- a/src/main/java/carpet/mixins/ClientPlayNetworkHandlerMixin.java +++ b/src/main/java/carpet/mixins/ClientPlayNetworkHandlerMixin.java @@ -2,40 +2,40 @@ package carpet.mixins; import carpet.network.CarpetClient; import carpet.network.ClientNetworkHandler; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; -import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket; -import net.minecraft.text.Text; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientboundLoginPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ClientPlayNetworkHandler.class) +@Mixin(ClientPacketListener.class) public abstract class ClientPlayNetworkHandlerMixin { - @Shadow private MinecraftClient client; + @Shadow private Minecraft minecraft; - @Inject(method = "onCustomPayload", at = @At("HEAD"), cancellable = true) - private void onOnCustomPayload(CustomPayloadS2CPacket packet, CallbackInfo ci) + @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) + private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackInfo ci) { - if (CarpetClient.CARPET_CHANNEL.equals(packet.getChannel())) + if (CarpetClient.CARPET_CHANNEL.equals(packet.getIdentifier())) { - ClientNetworkHandler.handleData(packet.getData(), client.player); + ClientNetworkHandler.handleData(packet.getData(), minecraft.player); ci.cancel(); } } - @Inject(method = "onGameJoin", at = @At("RETURN")) - private void onGameJoined(GameJoinS2CPacket packet, CallbackInfo info) + @Inject(method = "handleLogin", at = @At("RETURN")) + private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info) { - CarpetClient.gameJoined(client.player); + CarpetClient.gameJoined(minecraft.player); } - @Inject(method = "onDisconnected", at = @At("HEAD")) - private void onCMDisconnected(Text reason, CallbackInfo ci) + @Inject(method = "onDisconnect", at = @At("HEAD")) + private void onCMDisconnected(Component reason, CallbackInfo ci) { CarpetClient.disconnect(); } diff --git a/src/main/java/carpet/mixins/ClientPlayerEntity_clientCommandMixin.java b/src/main/java/carpet/mixins/ClientPlayerEntity_clientCommandMixin.java index b5bbb703..2d352ab7 100644 --- a/src/main/java/carpet/mixins/ClientPlayerEntity_clientCommandMixin.java +++ b/src/main/java/carpet/mixins/ClientPlayerEntity_clientCommandMixin.java @@ -3,16 +3,16 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.network.CarpetClient; import carpet.settings.SettingsManager; -import net.minecraft.client.network.ClientPlayerEntity; +import net.minecraft.client.player.LocalPlayer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ClientPlayerEntity.class) +@Mixin(LocalPlayer.class) public class ClientPlayerEntity_clientCommandMixin { - @Inject(method = "sendChatMessage", at = @At("HEAD")) + @Inject(method = "chat", at = @At("HEAD")) private void inspectMessage(String string, CallbackInfo ci) { if (string.startsWith("/call ")) @@ -22,11 +22,11 @@ public class ClientPlayerEntity_clientCommandMixin } if (CarpetServer.minecraft_server == null && !CarpetClient.isCarpet()) { - ClientPlayerEntity playerSource = (ClientPlayerEntity)(Object) this; - CarpetServer.settingsManager.inspectClientsideCommand(playerSource.getCommandSource(), string); + LocalPlayer playerSource = (LocalPlayer)(Object) this; + CarpetServer.settingsManager.inspectClientsideCommand(playerSource.createCommandSourceStack(), string); CarpetServer.extensions.forEach(e -> { SettingsManager sm = e.customSettingsManager(); - if (sm != null) sm.inspectClientsideCommand(playerSource.getCommandSource(), string); + if (sm != null) sm.inspectClientsideCommand(playerSource.createCommandSourceStack(), string); }); } } diff --git a/src/main/java/carpet/mixins/CloneCommandMixin.java b/src/main/java/carpet/mixins/CloneCommandMixin.java index dd33e699..92e49309 100644 --- a/src/main/java/carpet/mixins/CloneCommandMixin.java +++ b/src/main/java/carpet/mixins/CloneCommandMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.server.command.CloneCommand; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.server.commands.CloneCommands; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; @@ -12,20 +12,20 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(CloneCommand.class) +@Mixin(CloneCommands.class) public abstract class CloneCommandMixin { - @ModifyConstant(method = "execute", constant = @Constant(intValue = 32768)) + @ModifyConstant(method = "clone", constant = @Constant(intValue = 32768)) private static int fillLimit(int original) { return CarpetSettings.fillLimit; } - @Redirect(method = "execute", at = @At( + @Redirect(method = "clone", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" )) - private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) + private static void conditionalUpdating(ServerLevel serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.blockUpdated(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/CommandFunctionManager_tickMixin.java b/src/main/java/carpet/mixins/CommandFunctionManager_tickMixin.java index 034f06db..ab292bde 100644 --- a/src/main/java/carpet/mixins/CommandFunctionManager_tickMixin.java +++ b/src/main/java/carpet/mixins/CommandFunctionManager_tickMixin.java @@ -2,13 +2,13 @@ package carpet.mixins; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; -import net.minecraft.server.function.CommandFunctionManager; +import net.minecraft.server.ServerFunctionManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(CommandFunctionManager.class) +@Mixin(ServerFunctionManager.class) public class CommandFunctionManager_tickMixin { CarpetProfiler.ProfilerToken currentSection; diff --git a/src/main/java/carpet/mixins/CommandManagerMixin.java b/src/main/java/carpet/mixins/CommandManagerMixin.java index 8ab4f861..4c8fc081 100644 --- a/src/main/java/carpet/mixins/CommandManagerMixin.java +++ b/src/main/java/carpet/mixins/CommandManagerMixin.java @@ -3,8 +3,8 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.CarpetSettings; import com.mojang.brigadier.CommandDispatcher; -import net.minecraft.server.command.CommandManager; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import org.slf4j.Logger; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -16,35 +16,35 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(CommandManager.class) +@Mixin(Commands.class) public abstract class CommandManagerMixin { @Shadow @Final - private CommandDispatcher dispatcher; + private CommandDispatcher dispatcher; @Inject(method = "", at = @At("RETURN")) - private void onRegister(CommandManager.RegistrationEnvironment arg, CallbackInfo ci) { + private void onRegister(Commands.CommandSelection arg, CallbackInfo ci) { CarpetServer.registerCarpetCommands(this.dispatcher); CarpetServer.registerCarpetCommands(this.dispatcher, arg); } - @Inject(method = "execute", at = @At("HEAD")) - private void onExecuteBegin(ServerCommandSource serverCommandSource_1, String string_1, CallbackInfoReturnable cir) + @Inject(method = "performCommand", at = @At("HEAD")) + private void onExecuteBegin(CommandSourceStack serverCommandSource_1, String string_1, CallbackInfoReturnable cir) { if (!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); } - @Inject(method = "execute", at = @At("RETURN")) - private void onExecuteEnd(ServerCommandSource serverCommandSource_1, String string_1, CallbackInfoReturnable cir) + @Inject(method = "performCommand", at = @At("RETURN")) + private void onExecuteEnd(CommandSourceStack serverCommandSource_1, String string_1, CallbackInfoReturnable cir) { CarpetSettings.impendingFillSkipUpdates.set(false); } @SuppressWarnings("UnresolvedMixinReference") - @Redirect(method = "execute", at = @At( + @Redirect(method = "performCommand", at = @At( value = "INVOKE", target = "Lorg/slf4j/Logger;isDebugEnabled()Z" ), diff --git a/src/main/java/carpet/mixins/ContainerMixin.java b/src/main/java/carpet/mixins/ContainerMixin.java index 96e650fa..29a9a002 100644 --- a/src/main/java/carpet/mixins/ContainerMixin.java +++ b/src/main/java/carpet/mixins/ContainerMixin.java @@ -1,13 +1,6 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.screen.slot.Slot; -import net.minecraft.screen.slot.SlotActionType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.util.collection.DefaultedList; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -17,39 +10,46 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; +import net.minecraft.core.NonNullList; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; -@Mixin(ScreenHandler.class) +@Mixin(AbstractContainerMenu.class) public abstract class ContainerMixin { - @Shadow public abstract void onSlotClick(int int_1, int int_2, SlotActionType slotActionType_1, PlayerEntity playerEntity_1); + @Shadow public abstract void clicked(int int_1, int int_2, ClickType slotActionType_1, Player playerEntity_1); - @Shadow public abstract void sendContentUpdates(); + @Shadow public abstract void broadcastChanges(); - @Shadow @Final public DefaultedList slots; + @Shadow @Final public NonNullList slots; - @Shadow protected abstract void endQuickCraft(); + @Shadow protected abstract void resetQuickCraft(); - @Shadow public abstract ItemStack getCursorStack(); + @Shadow public abstract ItemStack getCarried(); - @Inject( method = "internalOnSlotClick", at = @At(value = "HEAD"), cancellable = true) - private void onThrowClick(int slotId, int clickData, SlotActionType actionType, PlayerEntity playerEntity, CallbackInfo ci) + @Inject( method = "doClick", at = @At(value = "HEAD"), cancellable = true) + private void onThrowClick(int slotId, int clickData, ClickType actionType, Player playerEntity, CallbackInfo ci) { - if (actionType == SlotActionType.THROW && CarpetSettings.ctrlQCraftingFix && this.getCursorStack().isEmpty() && slotId >= 0) + if (actionType == ClickType.THROW && CarpetSettings.ctrlQCraftingFix && this.getCarried().isEmpty() && slotId >= 0) { ItemStack itemStack_1 = ItemStack.EMPTY; Slot slot_4 = slots.get(slotId); - if (/*slot_4 != null && */slot_4.hasStack() && slot_4.canTakeItems(playerEntity)) + if (/*slot_4 != null && */slot_4.hasItem() && slot_4.mayPickup(playerEntity)) { if(slotId == 0 && clickData == 1) { - Item craftedItem = slot_4.getStack().getItem(); - while(slot_4.hasStack() && slot_4.getStack().getItem() == craftedItem) + Item craftedItem = slot_4.getItem().getItem(); + while(slot_4.hasItem() && slot_4.getItem().getItem() == craftedItem) { - this.onSlotClick(slotId, 0, SlotActionType.THROW, playerEntity); + this.clicked(slotId, 0, ClickType.THROW, playerEntity); } - this.sendContentUpdates(); - this.endQuickCraft(); + this.broadcastChanges(); + this.resetQuickCraft(); ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/CoralBlockMixin.java b/src/main/java/carpet/mixins/CoralBlockMixin.java index 40d5ec1d..471cc2fa 100644 --- a/src/main/java/carpet/mixins/CoralBlockMixin.java +++ b/src/main/java/carpet/mixins/CoralBlockMixin.java @@ -2,80 +2,80 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.CoralFeatureInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.CoralBlock; -import net.minecraft.block.CoralParentBlock; -import net.minecraft.block.Fertilizable; -import net.minecraft.block.MapColor; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.tag.BlockTags; -import net.minecraft.tag.FluidTags; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.CoralClawFeature; -import net.minecraft.world.gen.feature.CoralFeature; -import net.minecraft.world.gen.feature.CoralMushroomFeature; -import net.minecraft.world.gen.feature.CoralTreeFeature; -import net.minecraft.world.gen.feature.DefaultFeatureConfig; import org.spongepowered.asm.mixin.Mixin; import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseCoralPlantTypeBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.BonemealableBlock; +import net.minecraft.world.level.block.CoralPlantBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.CoralClawFeature; +import net.minecraft.world.level.levelgen.feature.CoralFeature; +import net.minecraft.world.level.levelgen.feature.CoralMushroomFeature; +import net.minecraft.world.level.levelgen.feature.CoralTreeFeature; +import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; +import net.minecraft.world.level.material.MaterialColor; -@Mixin(CoralBlock.class) -public abstract class CoralBlockMixin implements Fertilizable +@Mixin(CoralPlantBlock.class) +public abstract class CoralBlockMixin implements BonemealableBlock { - public boolean isFertilizable(BlockView var1, BlockPos var2, BlockState var3, boolean var4) + public boolean isValidBonemealTarget(BlockGetter var1, BlockPos var2, BlockState var3, boolean var4) { return CarpetSettings.renewableCoral == CarpetSettings.RenewableCoralMode.EXPANDED || CarpetSettings.renewableCoral == CarpetSettings.RenewableCoralMode.TRUE - && var3.get(CoralParentBlock.WATERLOGGED) - && var1.getFluidState(var2.up()).isIn(FluidTags.WATER); + && var3.getValue(BaseCoralPlantTypeBlock.WATERLOGGED) + && var1.getFluidState(var2.above()).is(FluidTags.WATER); } - public boolean canGrow(World var1, Random var2, BlockPos var3, BlockState var4) + public boolean isBonemealSuccess(Level var1, Random var2, BlockPos var3, BlockState var4) { return (double)var1.random.nextFloat() < 0.15D; } - public void grow(ServerWorld worldIn, Random random, BlockPos pos, BlockState blockUnder) + public void performBonemeal(ServerLevel worldIn, Random random, BlockPos pos, BlockState blockUnder) { CoralFeature coral; int variant = random.nextInt(3); if (variant == 0) - coral = new CoralClawFeature(DefaultFeatureConfig.CODEC); + coral = new CoralClawFeature(NoneFeatureConfiguration.CODEC); else if (variant == 1) - coral = new CoralTreeFeature(DefaultFeatureConfig.CODEC); + coral = new CoralTreeFeature(NoneFeatureConfiguration.CODEC); else - coral = new CoralMushroomFeature(DefaultFeatureConfig.CODEC); + coral = new CoralMushroomFeature(NoneFeatureConfiguration.CODEC); - MapColor color = blockUnder.getMapColor(worldIn, pos); + MaterialColor color = blockUnder.getMapColor(worldIn, pos); BlockState proper_block = blockUnder; - for (Block block: BlockTags.CORAL_BLOCKS.values()) + for (Block block: BlockTags.CORAL_BLOCKS.getValues()) { - proper_block = block.getDefaultState(); + proper_block = block.defaultBlockState(); if (proper_block.getMapColor(worldIn,pos) == color) { break; } } - worldIn.setBlockState(pos, Blocks.WATER.getDefaultState(), 4); + worldIn.setBlock(pos, Blocks.WATER.defaultBlockState(), 4); if (!((CoralFeatureInterface)coral).growSpecific(worldIn, random, pos, proper_block)) { - worldIn.setBlockState(pos, blockUnder, 3); + worldIn.setBlock(pos, blockUnder, 3); } else { if (worldIn.random.nextInt(10)==0) { - BlockPos randomPos = pos.add(worldIn.random.nextInt(16)-8,worldIn.random.nextInt(8),worldIn.random.nextInt(16)-8 ); + BlockPos randomPos = pos.offset(worldIn.random.nextInt(16)-8,worldIn.random.nextInt(8),worldIn.random.nextInt(16)-8 ); if (BlockTags.CORAL_BLOCKS.contains(worldIn.getBlockState(randomPos).getBlock())) { - worldIn.setBlockState(randomPos, Blocks.WET_SPONGE.getDefaultState(), 3); + worldIn.setBlock(randomPos, Blocks.WET_SPONGE.defaultBlockState(), 3); } } } diff --git a/src/main/java/carpet/mixins/CoralFanBlockMixin.java b/src/main/java/carpet/mixins/CoralFanBlockMixin.java index 9d51902b..d112b897 100644 --- a/src/main/java/carpet/mixins/CoralFanBlockMixin.java +++ b/src/main/java/carpet/mixins/CoralFanBlockMixin.java @@ -2,69 +2,79 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.CoralFeatureInterface; -import net.minecraft.block.*; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.tag.BlockTags; -import net.minecraft.tag.FluidTags; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.*; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseCoralPlantTypeBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.BonemealableBlock; +import net.minecraft.world.level.block.CoralFanBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.CoralClawFeature; +import net.minecraft.world.level.levelgen.feature.CoralFeature; +import net.minecraft.world.level.levelgen.feature.CoralMushroomFeature; +import net.minecraft.world.level.levelgen.feature.CoralTreeFeature; +import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; +import net.minecraft.world.level.material.MaterialColor; import org.spongepowered.asm.mixin.Mixin; import java.util.Random; @Mixin(CoralFanBlock.class) -public abstract class CoralFanBlockMixin implements Fertilizable +public abstract class CoralFanBlockMixin implements BonemealableBlock { - public boolean isFertilizable(BlockView var1, BlockPos var2, BlockState var3, boolean var4) + public boolean isValidBonemealTarget(BlockGetter var1, BlockPos var2, BlockState var3, boolean var4) { return CarpetSettings.renewableCoral == CarpetSettings.RenewableCoralMode.EXPANDED - && var3.get(CoralParentBlock.WATERLOGGED) - && var1.getFluidState(var2.up()).isIn(FluidTags.WATER); + && var3.getValue(BaseCoralPlantTypeBlock.WATERLOGGED) + && var1.getFluidState(var2.above()).is(FluidTags.WATER); } - public boolean canGrow(World var1, Random var2, BlockPos var3, BlockState var4) + public boolean isBonemealSuccess(Level var1, Random var2, BlockPos var3, BlockState var4) { return (double)var1.random.nextFloat() < 0.15D; } - public void grow(ServerWorld worldIn, Random random, BlockPos pos, BlockState blockUnder) + public void performBonemeal(ServerLevel worldIn, Random random, BlockPos pos, BlockState blockUnder) { CoralFeature coral; int variant = random.nextInt(3); if (variant == 0) - coral = new CoralClawFeature(DefaultFeatureConfig.CODEC); + coral = new CoralClawFeature(NoneFeatureConfiguration.CODEC); else if (variant == 1) - coral = new CoralTreeFeature(DefaultFeatureConfig.CODEC); + coral = new CoralTreeFeature(NoneFeatureConfiguration.CODEC); else - coral = new CoralMushroomFeature(DefaultFeatureConfig.CODEC); + coral = new CoralMushroomFeature(NoneFeatureConfiguration.CODEC); - MapColor color = blockUnder.getMapColor(worldIn, pos); + MaterialColor color = blockUnder.getMapColor(worldIn, pos); BlockState proper_block = blockUnder; - for (Block block: BlockTags.CORAL_BLOCKS.values()) + for (Block block: BlockTags.CORAL_BLOCKS.getValues()) { - proper_block = block.getDefaultState(); + proper_block = block.defaultBlockState(); if (proper_block.getMapColor(worldIn,pos) == color) { break; } } - worldIn.setBlockState(pos, Blocks.WATER.getDefaultState(), 4); + worldIn.setBlock(pos, Blocks.WATER.defaultBlockState(), 4); if (!((CoralFeatureInterface)coral).growSpecific(worldIn, random, pos, proper_block)) { - worldIn.setBlockState(pos, blockUnder, 3); + worldIn.setBlock(pos, blockUnder, 3); } else { if (worldIn.random.nextInt(10)==0) { - BlockPos randomPos = pos.add(worldIn.random.nextInt(16)-8,worldIn.random.nextInt(8),worldIn.random.nextInt(16)-8 ); + BlockPos randomPos = pos.offset(worldIn.random.nextInt(16)-8,worldIn.random.nextInt(8),worldIn.random.nextInt(16)-8 ); if (BlockTags.CORAL_BLOCKS.contains(worldIn.getBlockState(randomPos).getBlock())) { - worldIn.setBlockState(randomPos, Blocks.WET_SPONGE.getDefaultState(), 3); + worldIn.setBlock(randomPos, Blocks.WET_SPONGE.defaultBlockState(), 3); } } } diff --git a/src/main/java/carpet/mixins/CoralFeatureMixin.java b/src/main/java/carpet/mixins/CoralFeatureMixin.java index 41b88df0..06713ca9 100644 --- a/src/main/java/carpet/mixins/CoralFeatureMixin.java +++ b/src/main/java/carpet/mixins/CoralFeatureMixin.java @@ -1,25 +1,25 @@ package carpet.mixins; import carpet.fakes.CoralFeatureInterface; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.WorldAccess; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.CoralFeature; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.CoralFeature; @Mixin(CoralFeature.class) public abstract class CoralFeatureMixin implements CoralFeatureInterface { - @Shadow protected abstract boolean generateCoral(WorldAccess var1, Random var2, BlockPos var3, BlockState var4); + @Shadow protected abstract boolean placeFeature(LevelAccessor var1, Random var2, BlockPos var3, BlockState var4); @Override - public boolean growSpecific(World worldIn, Random random, BlockPos pos, BlockState blockUnder) + public boolean growSpecific(Level worldIn, Random random, BlockPos pos, BlockState blockUnder) { - return generateCoral(worldIn, random, pos, blockUnder); + return placeFeature(worldIn, random, pos, blockUnder); } } diff --git a/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java b/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java index e2dcf2d7..6478744b 100644 --- a/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java +++ b/src/main/java/carpet/mixins/CrashReport_addScarpetAppsMixin.java @@ -2,8 +2,7 @@ package carpet.mixins; import java.util.function.Supplier; import java.util.stream.Collectors; - -import net.minecraft.util.SystemDetails; +import net.minecraft.SystemReport; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -12,15 +11,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import carpet.CarpetServer; -@Mixin(SystemDetails.class) +@Mixin(SystemReport.class) public abstract class CrashReport_addScarpetAppsMixin { - @Shadow public abstract void addSection(String name, Supplier valueSupplier); + @Shadow public abstract void setDetail(String name, Supplier valueSupplier); @Inject(method = "", at = @At("RETURN")) private void fillSystemDetails(CallbackInfo info) { if (CarpetServer.scriptServer == null || CarpetServer.scriptServer.modules.isEmpty()) return; - addSection("Loaded Scarpet Apps", () -> { + setDetail("Loaded Scarpet Apps", () -> { return CarpetServer.scriptServer.modules.keySet().stream().collect(Collectors.joining("\n\t\t", "\n\t\t", "")); }); } diff --git a/src/main/java/carpet/mixins/DebugRenderer_scarpetRenderMixin.java b/src/main/java/carpet/mixins/DebugRenderer_scarpetRenderMixin.java index 0ed9e836..d7030e8c 100644 --- a/src/main/java/carpet/mixins/DebugRenderer_scarpetRenderMixin.java +++ b/src/main/java/carpet/mixins/DebugRenderer_scarpetRenderMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.network.CarpetClient; -import net.minecraft.client.render.debug.DebugRenderer; +import net.minecraft.client.renderer.debug.DebugRenderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -10,7 +10,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(DebugRenderer.class) public class DebugRenderer_scarpetRenderMixin { - @Inject(method = "reset", at = @At("HEAD")) + @Inject(method = "clear", at = @At("HEAD")) private void resetScarpetRenderes(CallbackInfo ci) { if (CarpetClient.shapes != null) diff --git a/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java b/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java index be213bfb..1bb1a4e0 100644 --- a/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java +++ b/src/main/java/carpet/mixins/DesertPyramidFeatureMixin.java @@ -3,16 +3,11 @@ package carpet.mixins; import carpet.CarpetSettings; import com.google.common.collect.Lists; import com.mojang.serialization.Codec; -import net.minecraft.entity.EntityType; -import net.minecraft.util.collection.Pool; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.gen.feature.DefaultFeatureConfig; -import net.minecraft.world.gen.feature.DesertPyramidFeature; -import net.minecraft.world.gen.feature.StructureFeature; import org.spongepowered.asm.mixin.Mixin; import java.util.Collections; import java.util.List; +import net.minecraft.world.level.levelgen.feature.DesertPyramidFeature; @Mixin(DesertPyramidFeature.class) public abstract class DesertPyramidFeatureMixin diff --git a/src/main/java/carpet/mixins/DirectionMixin.java b/src/main/java/carpet/mixins/DirectionMixin.java index eb82727a..ac5d14e2 100644 --- a/src/main/java/carpet/mixins/DirectionMixin.java +++ b/src/main/java/carpet/mixins/DirectionMixin.java @@ -3,8 +3,8 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.EntityInterface; import carpet.helpers.BlockRotator; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -12,13 +12,13 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(Direction.class) public abstract class DirectionMixin { - @Redirect(method = "getEntityFacingOrder", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;getYaw(F)F")) + @Redirect(method = "orderedByNearest", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;getViewYRot(F)F")) private static float getYaw(Entity entity, float float_1) { float yaw; if (!CarpetSettings.placementRotationFix) { - yaw = entity.getYaw(float_1); + yaw = entity.getViewYRot(float_1); } else { @@ -30,10 +30,10 @@ public abstract class DirectionMixin } return yaw; } - @Redirect(method = "getEntityFacingOrder", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;getPitch(F)F")) + @Redirect(method = "orderedByNearest", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;getViewXRot(F)F")) private static float getPitch(Entity entity, float float_1) { - float pitch = entity.getPitch(float_1); + float pitch = entity.getViewXRot(float_1); if (BlockRotator.flippinEligibility(entity)) { pitch = -pitch; diff --git a/src/main/java/carpet/mixins/DispenserBlock_cactusMixin.java b/src/main/java/carpet/mixins/DispenserBlock_cactusMixin.java index ec386f71..f5f8be8e 100644 --- a/src/main/java/carpet/mixins/DispenserBlock_cactusMixin.java +++ b/src/main/java/carpet/mixins/DispenserBlock_cactusMixin.java @@ -1,11 +1,11 @@ package carpet.mixins; import carpet.helpers.BlockRotator; -import net.minecraft.block.DispenserBlock; -import net.minecraft.block.dispenser.DispenserBehavior; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; +import net.minecraft.core.dispenser.DispenseItemBehavior; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.DispenserBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -14,8 +14,8 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(DispenserBlock.class) public abstract class DispenserBlock_cactusMixin { - @Inject(method = "getBehaviorForItem", at = @At("HEAD"), cancellable = true) - private void registerCarpetBehaviors(ItemStack stack, CallbackInfoReturnable cir) + @Inject(method = "getDispenseMethod", at = @At("HEAD"), cancellable = true) + private void registerCarpetBehaviors(ItemStack stack, CallbackInfoReturnable cir) { Item item = stack.getItem(); if (item == Items.CACTUS) diff --git a/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java b/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java index 83f0ecc3..69d0ecfd 100644 --- a/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java +++ b/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.DispenserBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.DispenserBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -11,15 +11,15 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(DispenserBlock.class) public class DispenserBlock_qcMixin { - @Redirect(method = "neighborUpdate", at = @At( + @Redirect(method = "neighborChanged", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/World;isReceivingRedstonePower(Lnet/minecraft/util/math/BlockPos;)Z", + target = "Lnet/minecraft/world/level/Level;hasNeighborSignal(Lnet/minecraft/core/BlockPos;)Z", ordinal = 1 )) - private boolean checkUpPower(World world, BlockPos blockPos_1) + private boolean checkUpPower(Level world, BlockPos blockPos_1) { if (!CarpetSettings.quasiConnectivity) return false; - return world.isReceivingRedstonePower(blockPos_1); + return world.hasNeighborSignal(blockPos_1); } } diff --git a/src/main/java/carpet/mixins/EndCityFeatureMixin.java b/src/main/java/carpet/mixins/EndCityFeatureMixin.java index 60d627a9..7cebaeec 100644 --- a/src/main/java/carpet/mixins/EndCityFeatureMixin.java +++ b/src/main/java/carpet/mixins/EndCityFeatureMixin.java @@ -3,16 +3,11 @@ package carpet.mixins; import carpet.CarpetSettings; import com.google.common.collect.Lists; import com.mojang.serialization.Codec; -import net.minecraft.entity.EntityType; -import net.minecraft.util.collection.Pool; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.gen.feature.DefaultFeatureConfig; -import net.minecraft.world.gen.feature.EndCityFeature; -import net.minecraft.world.gen.feature.StructureFeature; import org.spongepowered.asm.mixin.Mixin; import java.util.Collections; import java.util.List; +import net.minecraft.world.level.levelgen.feature.EndCityFeature; @Mixin(EndCityFeature.class) public abstract class EndCityFeatureMixin //extends StructureFeature diff --git a/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java index 36df899d..8ae40e65 100644 --- a/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/EndGatewayBlockEntity_creativeNoClipMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.entity.EndGatewayBlockEntity; -import net.minecraft.entity.Entity; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(EndGatewayBlockEntity.class) +@Mixin(TheEndGatewayBlockEntity.class) public class EndGatewayBlockEntity_creativeNoClipMixin { - @Inject(method = "canTeleport", cancellable = true, at = @At("HEAD")) + @Inject(method = "canEntityTeleport", cancellable = true, at = @At("HEAD")) private static void checkFlyingCreative(Entity entity, CallbackInfoReturnable cir) { if (CarpetSettings.isCreativeFlying(entity)) cir.setReturnValue(false); diff --git a/src/main/java/carpet/mixins/EntityMixin.java b/src/main/java/carpet/mixins/EntityMixin.java index c3d27838..fca20d32 100644 --- a/src/main/java/carpet/mixins/EntityMixin.java +++ b/src/main/java/carpet/mixins/EntityMixin.java @@ -2,9 +2,9 @@ package carpet.mixins; import carpet.fakes.EntityInterface; import carpet.patches.EntityPlayerMPFake; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.MathHelper; -import net.minecraft.world.World; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -16,23 +16,23 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; public abstract class EntityMixin implements EntityInterface { @Shadow - public float yaw; + public float yRot; @Shadow - public float prevYaw; + public float yRotO; - @Shadow public @Nullable abstract Entity getPrimaryPassenger(); + @Shadow public @Nullable abstract Entity getControllingPassenger(); - @Shadow public World world; + @Shadow public Level level; public float getMainYaw(float partialTicks) { - return partialTicks == 1.0F ? this.yaw : MathHelper.lerp(partialTicks, this.prevYaw, this.yaw); + return partialTicks == 1.0F ? this.yRot : Mth.lerp(partialTicks, this.yRotO, this.yRot); } - @Inject(method = "isLogicalSideForUpdatingMovement", at = @At("HEAD"), cancellable = true) + @Inject(method = "isControlledByLocalInstance", at = @At("HEAD"), cancellable = true) private void isFakePlayer(CallbackInfoReturnable cir) { - if (getPrimaryPassenger() instanceof EntityPlayerMPFake) cir.setReturnValue(!world.isClient); + if (getControllingPassenger() instanceof EntityPlayerMPFake) cir.setReturnValue(!level.isClientSide); } } diff --git a/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java b/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java index b85704cd..969a5be7 100644 --- a/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java +++ b/src/main/java/carpet/mixins/EntityNavigation_pathfindingMixin.java @@ -2,11 +2,6 @@ package carpet.mixins; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.PathfindingVisualizer; -import net.minecraft.entity.ai.pathing.EntityNavigation; -import net.minecraft.entity.ai.pathing.Path; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -15,45 +10,50 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Set; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; -@Mixin(EntityNavigation.class) +@Mixin(PathNavigation.class) public abstract class EntityNavigation_pathfindingMixin { - @Shadow @Final protected MobEntity entity; + @Shadow @Final protected Mob mob; - @Shadow protected @Nullable abstract Path findPathTo(Set set, int i, boolean bl, int j); + @Shadow protected @Nullable abstract Path createPath(Set set, int i, boolean bl, int j); - @Redirect(method = "findPathTo(Lnet/minecraft/util/math/BlockPos;I)Lnet/minecraft/entity/ai/pathing/Path;", at = @At( + @Redirect(method = "createPath(Lnet/minecraft/core/BlockPos;I)Lnet/minecraft/world/level/pathfinder/Path;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathTo(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" + target = "Lnet/minecraft/world/entity/ai/navigation/PathNavigation;createPath(Ljava/util/Set;IZI)Lnet/minecraft/world/level/pathfinder/Path;" )) - private Path pathToBlock(EntityNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) + private Path pathToBlock(PathNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) { if (!LoggerRegistry.__pathfinding) - return findPathTo(set_1, int_1, boolean_1, int_2); + return createPath(set_1, int_1, boolean_1, int_2); long start = System.nanoTime(); - Path path = findPathTo(set_1, int_1, boolean_1, int_2); + Path path = createPath(set_1, int_1, boolean_1, int_2); long finish = System.nanoTime(); float duration = (1.0F*((finish - start)/1000))/1000; - set_1.forEach(b -> PathfindingVisualizer.slowPath(entity, Vec3d.ofBottomCenter(b), duration, path != null)); // ground centered position + set_1.forEach(b -> PathfindingVisualizer.slowPath(mob, Vec3.atBottomCenterOf(b), duration, path != null)); // ground centered position return path; } - @Redirect(method = "findPathTo(Lnet/minecraft/entity/Entity;I)Lnet/minecraft/entity/ai/pathing/Path;", at = @At( + @Redirect(method = "createPath(Lnet/minecraft/world/entity/Entity;I)Lnet/minecraft/world/level/pathfinder/Path;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/ai/pathing/EntityNavigation;findPathTo(Ljava/util/Set;IZI)Lnet/minecraft/entity/ai/pathing/Path;" + target = "Lnet/minecraft/world/entity/ai/navigation/PathNavigation;createPath(Ljava/util/Set;IZI)Lnet/minecraft/world/level/pathfinder/Path;" )) - private Path pathToEntity(EntityNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) + private Path pathToEntity(PathNavigation entityNavigation, Set set_1, int int_1, boolean boolean_1, int int_2) { if (!LoggerRegistry.__pathfinding) - return findPathTo(set_1, int_1, boolean_1, int_2); + return createPath(set_1, int_1, boolean_1, int_2); long start = System.nanoTime(); - Path path = findPathTo(set_1, int_1, boolean_1, int_2); + Path path = createPath(set_1, int_1, boolean_1, int_2); long finish = System.nanoTime(); float duration = (1.0F*((finish - start)/1000))/1000; - set_1.forEach(b -> PathfindingVisualizer.slowPath(entity, Vec3d.ofBottomCenter(b), duration, path != null)); + set_1.forEach(b -> PathfindingVisualizer.slowPath(mob, Vec3.atBottomCenterOf(b), duration, path != null)); return path; } } diff --git a/src/main/java/carpet/mixins/EntityTrackerEntry_leashFixMixin.java b/src/main/java/carpet/mixins/EntityTrackerEntry_leashFixMixin.java index 620b65ea..a96d1460 100644 --- a/src/main/java/carpet/mixins/EntityTrackerEntry_leashFixMixin.java +++ b/src/main/java/carpet/mixins/EntityTrackerEntry_leashFixMixin.java @@ -1,11 +1,6 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.network.packet.s2c.play.EntityAttachS2CPacket; -import net.minecraft.entity.Entity; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.network.Packet; -import net.minecraft.server.network.EntityTrackerEntry; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -14,20 +9,25 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; -@Mixin(EntityTrackerEntry.class) +@Mixin(ServerEntity.class) public class EntityTrackerEntry_leashFixMixin { @Shadow @Final private Entity entity; - @Inject(method = "sendPackets", at = @At("RETURN")) + @Inject(method = "sendPairingData", at = @At("RETURN")) private void sendLeashPackets(Consumer> consumer_1, CallbackInfo ci) { if (CarpetSettings.leadFix) { - if (entity instanceof MobEntity) + if (entity instanceof Mob) { - consumer_1.accept( new EntityAttachS2CPacket(entity, ((MobEntity) entity).getHoldingEntity())); + consumer_1.accept( new ClientboundSetEntityLinkPacket(entity, ((Mob) entity).getLeashHolder())); } } } diff --git a/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java index fe12d200..7a576b46 100644 --- a/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/Entity_scarpetEventsMixin.java @@ -2,8 +2,8 @@ package carpet.mixins; import carpet.fakes.EntityInterface; import carpet.script.EntityEventsGroup; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.Vec3d; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -15,18 +15,18 @@ public abstract class Entity_scarpetEventsMixin implements EntityInterface { //@Shadow public boolean removed; - @Shadow protected int netherPortalTime; - @Shadow private int netherPortalCooldown; + @Shadow protected int portalTime; + @Shadow private int portalCooldown; @Shadow public abstract boolean isRemoved(); - @Shadow private Vec3d pos, velocity; + @Shadow private Vec3 position, deltaMovement; private boolean permanentVehicle; private final EntityEventsGroup events = new EntityEventsGroup((Entity) (Object)this); - private Vec3d pos1, motion; + private Vec3 pos1, motion; @Override public EntityEventsGroup getEventContainer() @@ -49,25 +49,25 @@ public abstract class Entity_scarpetEventsMixin implements EntityInterface @Override public int getPublicNetherPortalCooldown() { - return netherPortalCooldown; + return portalCooldown; } @Override public void setPublicNetherPortalCooldown(int what) { - netherPortalCooldown = what; + portalCooldown = what; } @Override public int getPortalTimer() { - return netherPortalTime; + return portalTime; } @Override public void setPortalTimer(int amount) { - netherPortalTime = amount; + portalTime = amount; } @Inject(method = "tick", at = @At("HEAD")) @@ -84,17 +84,17 @@ public abstract class Entity_scarpetEventsMixin implements EntityInterface } - @Inject(method = "setPos", at = @At("HEAD")) + @Inject(method = "setPosRaw", at = @At("HEAD")) private void firstPos(CallbackInfo ci) { - pos1 = this.pos; - motion = this.velocity; + pos1 = this.position; + motion = this.deltaMovement; } - @Inject(method = "setPos", at = @At("TAIL")) + @Inject(method = "setPosRaw", at = @At("TAIL")) private void secondPos(CallbackInfo ci) { - if(pos1!=this.pos) - events.onEvent(EntityEventsGroup.Event.ON_MOVE, motion, pos1, this.pos); + if(pos1!=this.position) + events.onEvent(EntityEventsGroup.Event.ON_MOVE, motion, pos1, this.position); } } diff --git a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java index c499fa9a..5c8e8cee 100644 --- a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java +++ b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java @@ -1,45 +1,45 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.ExperienceOrbEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ExperienceOrbEntity.class) +@Mixin(ExperienceOrb.class) public abstract class ExperienceOrbEntityMixin extends Entity { @Shadow - private int pickingCount; + private int count; @Shadow - private int amount; + private int value; - public ExperienceOrbEntityMixin(EntityType type, World world) + public ExperienceOrbEntityMixin(EntityType type, Level world) { super(type, world); } @Shadow - protected abstract int repairPlayerGears(PlayerEntity player, int amount); + protected abstract int repairPlayerItems(Player player, int amount); - @Inject(method = "onPlayerCollision", at = @At("HEAD")) - private void addXP(PlayerEntity player, CallbackInfo ci) { - if (CarpetSettings.xpNoCooldown && !world.isClient) { - player.experiencePickUpDelay = 0; + @Inject(method = "playerTouch", at = @At("HEAD")) + private void addXP(Player player, CallbackInfo ci) { + if (CarpetSettings.xpNoCooldown && !level.isClientSide) { + player.takeXpDelay = 0; // reducing the count to 1 and leaving vanilla to deal with it - while (this.pickingCount > 1) { - int remainder = this.repairPlayerGears(player, this.amount); + while (this.count > 1) { + int remainder = this.repairPlayerItems(player, this.value); if (remainder > 0) { - player.addExperience(remainder); + player.giveExperiencePoints(remainder); } - this.pickingCount--; + this.count--; } } } diff --git a/src/main/java/carpet/mixins/ExplosionAccessor.java b/src/main/java/carpet/mixins/ExplosionAccessor.java index f75510fc..6371192f 100644 --- a/src/main/java/carpet/mixins/ExplosionAccessor.java +++ b/src/main/java/carpet/mixins/ExplosionAccessor.java @@ -1,24 +1,24 @@ package carpet.mixins; -import net.minecraft.entity.Entity; -import net.minecraft.world.World; -import net.minecraft.world.explosion.Explosion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import java.util.Random; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; @Mixin(Explosion.class) public interface ExplosionAccessor { @Accessor - boolean isCreateFire(); + boolean isFire(); @Accessor - Explosion.DestructionType getDestructionType(); + Explosion.BlockInteraction getBlockInteraction(); @Accessor - World getWorld(); + Level getLevel(); @Accessor Random getRandom(); @@ -33,9 +33,9 @@ public interface ExplosionAccessor { double getZ(); @Accessor - float getPower(); + float getRadius(); @Accessor - Entity getEntity(); + Entity getSource(); } diff --git a/src/main/java/carpet/mixins/ExplosionMixin.java b/src/main/java/carpet/mixins/ExplosionMixin.java index 49e1fd23..781b96fa 100644 --- a/src/main/java/carpet/mixins/ExplosionMixin.java +++ b/src/main/java/carpet/mixins/ExplosionMixin.java @@ -4,15 +4,6 @@ import carpet.helpers.OptimizedExplosion; import carpet.CarpetSettings; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.ExplosionLogHelper; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.entity.Entity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.explosion.Explosion; -import net.minecraft.world.explosion.ExplosionBehavior; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,19 +13,28 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.ExplosionDamageCalculator; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; @Mixin(value = Explosion.class) public abstract class ExplosionMixin { @Shadow @Final - private List affectedBlocks; + private List toBlow; - @Shadow @Final private World world; + @Shadow @Final private Level level; private ExplosionLogHelper eLogger; - @Inject(method = "collectBlocksAndDamageEntities", at = @At("HEAD"), + @Inject(method = "explode", at = @At("HEAD"), cancellable = true) private void onExplosionA(CallbackInfo ci) { @@ -45,18 +45,18 @@ public abstract class ExplosionMixin } } - @Inject(method = "affectWorld", at = @At("HEAD"), + @Inject(method = "finalizeExplosion", at = @At("HEAD"), cancellable = true) private void onExplosionB(boolean spawnParticles, CallbackInfo ci) { if (eLogger != null) { - eLogger.setAffectBlocks( ! affectedBlocks.isEmpty()); - eLogger.onExplosionDone(this.world.getTime()); + eLogger.setAffectBlocks( ! toBlow.isEmpty()); + eLogger.onExplosionDone(this.level.getGameTime()); } if (CarpetSettings.explosionNoBlockDamage) { - affectedBlocks.clear(); + toBlow.clear(); } if (CarpetSettings.optimizedTNT) { @@ -66,31 +66,31 @@ public abstract class ExplosionMixin } //optional due to Overwrite in Lithium //should kill most checks if no block damage is requested - @Redirect(method = "collectBlocksAndDamageEntities", require = 0, at = @At(value = "INVOKE", - target ="Lnet/minecraft/world/World;getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;")) - private BlockState noBlockCalcsWithNoBLockDamage(World world, BlockPos pos) + @Redirect(method = "explode", require = 0, at = @At(value = "INVOKE", + target ="Lnet/minecraft/world/level/Level;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;")) + private BlockState noBlockCalcsWithNoBLockDamage(Level world, BlockPos pos) { - if (CarpetSettings.explosionNoBlockDamage) return Blocks.BEDROCK.getDefaultState(); + if (CarpetSettings.explosionNoBlockDamage) return Blocks.BEDROCK.defaultBlockState(); return world.getBlockState(pos); } - @Inject(method = "(Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/entity/damage/DamageSource;Lnet/minecraft/world/explosion/ExplosionBehavior;DDDFZLnet/minecraft/world/explosion/Explosion$DestructionType;)V", + @Inject(method = "(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;)V", at = @At(value = "RETURN")) - private void onExplosionCreated(World world, Entity entity, DamageSource damageSource, ExplosionBehavior explosionBehavior, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType destructionType, CallbackInfo ci) + private void onExplosionCreated(Level world, Entity entity, DamageSource damageSource, ExplosionDamageCalculator explosionBehavior, double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction destructionType, CallbackInfo ci) { - if (LoggerRegistry.__explosions && ! world.isClient) + if (LoggerRegistry.__explosions && ! world.isClientSide) { eLogger = new ExplosionLogHelper(entity, x, y, z, power, createFire, destructionType); } } - @Redirect(method = "collectBlocksAndDamageEntities", - at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;setVelocity(Lnet/minecraft/util/math/Vec3d;)V")) - private void setVelocityAndUpdateLogging(Entity entity, Vec3d velocity) + @Redirect(method = "explode", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;setDeltaMovement(Lnet/minecraft/world/phys/Vec3;)V")) + private void setVelocityAndUpdateLogging(Entity entity, Vec3 velocity) { if (eLogger != null) { - eLogger.onEntityImpacted(entity, velocity.subtract(entity.getVelocity())); + eLogger.onEntityImpacted(entity, velocity.subtract(entity.getDeltaMovement())); } - entity.setVelocity(velocity); + entity.setDeltaMovement(velocity); } } diff --git a/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java b/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java index 24810333..049d2c84 100644 --- a/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/Explosion_scarpetEventMixin.java @@ -1,14 +1,5 @@ package carpet.mixins; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.explosion.Explosion; -import net.minecraft.world.explosion.ExplosionBehavior; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -22,57 +13,66 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.ArrayList; import java.util.List; import java.util.Set; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.ExplosionDamageCalculator; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import static carpet.script.CarpetEventServer.Event.EXPLOSION_OUTCOME; @Mixin(value = Explosion.class, priority = 990) public abstract class Explosion_scarpetEventMixin { - @Shadow @Final private World world; + @Shadow @Final private Level level; @Shadow @Final private double x; @Shadow @Final private double y; @Shadow @Final private double z; - @Shadow @Final private float power; - @Shadow @Final private boolean createFire; - @Shadow @Final private List affectedBlocks; - @Shadow @Final private Explosion.DestructionType destructionType; - @Shadow @Final private @Nullable Entity entity; + @Shadow @Final private float radius; + @Shadow @Final private boolean fire; + @Shadow @Final private List toBlow; + @Shadow @Final private Explosion.BlockInteraction blockInteraction; + @Shadow @Final private @Nullable Entity source; - @Shadow /*@Nullable*/ public abstract /*@Nullable*/ LivingEntity getCausingEntity(); + @Shadow /*@Nullable*/ public abstract /*@Nullable*/ LivingEntity getSourceMob(); - @Shadow public static float getExposure(Vec3d source, Entity entity) {return 0.0f;} + @Shadow public static float getSeenPercent(Vec3 source, Entity entity) {return 0.0f;} private List affectedEntities; - @Inject(method = "(Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/entity/damage/DamageSource;Lnet/minecraft/world/explosion/ExplosionBehavior;DDDFZLnet/minecraft/world/explosion/Explosion$DestructionType;)V", + @Inject(method = "(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;)V", at = @At(value = "RETURN")) - private void onExplosionCreated(World world, Entity entity, DamageSource damageSource, ExplosionBehavior explosionBehavior, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType destructionType, CallbackInfo ci) + private void onExplosionCreated(Level world, Entity entity, DamageSource damageSource, ExplosionDamageCalculator explosionBehavior, double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction destructionType, CallbackInfo ci) { - if (EXPLOSION_OUTCOME.isNeeded() && !world.isClient()) + if (EXPLOSION_OUTCOME.isNeeded() && !world.isClientSide()) { affectedEntities = new ArrayList<>(); } } - @Redirect(method = "collectBlocksAndDamageEntities", at=@At( + @Redirect(method = "explode", at=@At( value = "INVOKE", - target = "Lnet/minecraft/world/explosion/Explosion;getExposure(Lnet/minecraft/util/math/Vec3d;Lnet/minecraft/entity/Entity;)F") + target = "Lnet/minecraft/world/level/Explosion;getSeenPercent(Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/entity/Entity;)F") ) - private float onExplosion(Vec3d source, Entity entity) + private float onExplosion(Vec3 source, Entity entity) { if (affectedEntities != null) { affectedEntities.add(entity); } - return getExposure(source, entity); + return getSeenPercent(source, entity); } - @Inject(method = "affectWorld", at = @At("HEAD")) + @Inject(method = "finalizeExplosion", at = @At("HEAD")) private void onExplosion(boolean spawnParticles, CallbackInfo ci) { - if (EXPLOSION_OUTCOME.isNeeded() && !world.isClient()) + if (EXPLOSION_OUTCOME.isNeeded() && !level.isClientSide()) { - EXPLOSION_OUTCOME.onExplosion((ServerWorld) world, entity, this::getCausingEntity, x, y, z, power, createFire, affectedBlocks, affectedEntities, destructionType); + EXPLOSION_OUTCOME.onExplosion((ServerLevel) level, source, this::getSourceMob, x, y, z, radius, fire, toBlow, affectedEntities, blockInteraction); } } } diff --git a/src/main/java/carpet/mixins/FallingBlockEntityMixin.java b/src/main/java/carpet/mixins/FallingBlockEntityMixin.java index 82db5835..2e86c9b2 100644 --- a/src/main/java/carpet/mixins/FallingBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/FallingBlockEntityMixin.java @@ -2,11 +2,11 @@ package carpet.mixins; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.TrajectoryLogHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.FallingBlockEntity; -import net.minecraft.entity.projectile.ProjectileEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.item.FallingBlockEntity; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -16,12 +16,12 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; public abstract class FallingBlockEntityMixin extends Entity { private TrajectoryLogHelper logHelper; - public FallingBlockEntityMixin(EntityType entityType_1, World world_1) { super(entityType_1, world_1); } + public FallingBlockEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Inject(method = "(Lnet/minecraft/entity/EntityType;Lnet/minecraft/world/World;)V", at = @At("RETURN")) - private void addLogger(EntityType entityType_1, World world_1, CallbackInfo ci) + @Inject(method = "(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V", at = @At("RETURN")) + private void addLogger(EntityType entityType_1, Level world_1, CallbackInfo ci) { - if (LoggerRegistry.__fallingBlocks && !world_1.isClient) + if (LoggerRegistry.__fallingBlocks && !world_1.isClientSide) logHelper = new TrajectoryLogHelper("fallingBlocks"); } @@ -29,7 +29,7 @@ public abstract class FallingBlockEntityMixin extends Entity private void tickCheck(CallbackInfo ci) { if (LoggerRegistry.__fallingBlocks && logHelper != null) - logHelper.onTick(getX(), getY(), getZ(), getVelocity()); + logHelper.onTick(getX(), getY(), getZ(), getDeltaMovement()); } @Override diff --git a/src/main/java/carpet/mixins/FallingBlockEntity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/FallingBlockEntity_scarpetEventsMixin.java index 0855cfda..d3ee411b 100644 --- a/src/main/java/carpet/mixins/FallingBlockEntity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/FallingBlockEntity_scarpetEventsMixin.java @@ -2,10 +2,10 @@ package carpet.mixins; import carpet.fakes.EntityInterface; import carpet.script.EntityEventsGroup; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.FallingBlockEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.item.FallingBlockEntity; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -14,7 +14,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(FallingBlockEntity.class) public abstract class FallingBlockEntity_scarpetEventsMixin extends Entity { - public FallingBlockEntity_scarpetEventsMixin(EntityType type, World world) + public FallingBlockEntity_scarpetEventsMixin(EntityType type, Level world) { super(type, world); } diff --git a/src/main/java/carpet/mixins/FillCommandMixin.java b/src/main/java/carpet/mixins/FillCommandMixin.java index 42fb38c5..a237b7f2 100644 --- a/src/main/java/carpet/mixins/FillCommandMixin.java +++ b/src/main/java/carpet/mixins/FillCommandMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.server.command.FillCommand; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.server.commands.FillCommand; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; @@ -14,18 +14,18 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(FillCommand.class) public abstract class FillCommandMixin { - @ModifyConstant(method = "execute", constant = @Constant(intValue = 32768)) + @ModifyConstant(method = "fillBlocks", constant = @Constant(intValue = 32768)) private static int fillLimit(int original) { return CarpetSettings.fillLimit; } - @Redirect(method = "execute", at = @At( + @Redirect(method = "fillBlocks", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" )) - private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) + private static void conditionalUpdating(ServerLevel serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.blockUpdated(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/FireworkEntity_extremeMixin.java b/src/main/java/carpet/mixins/FireworkEntity_extremeMixin.java index 4196726c..7ca3e937 100644 --- a/src/main/java/carpet/mixins/FireworkEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/FireworkEntity_extremeMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.projectile.FireworkRocketEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.projectile.FireworkRocketEntity; @Mixin(FireworkRocketEntity.class) public class FireworkEntity_extremeMixin { - @Redirect(method = "(Lnet/minecraft/world/World;DDDLnet/minecraft/item/ItemStack;)V", expect = 2, at = @At( + @Redirect(method = "(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/item/ItemStack;)V", expect = 2, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/FishingBobberEntity_extremeMixin.java b/src/main/java/carpet/mixins/FishingBobberEntity_extremeMixin.java index 0fafca63..ede13cb2 100644 --- a/src/main/java/carpet/mixins/FishingBobberEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/FishingBobberEntity_extremeMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.projectile.FishingBobberEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.projectile.FishingHook; -@Mixin(FishingBobberEntity.class) +@Mixin(FishingHook.class) public class FishingBobberEntity_extremeMixin { - @Redirect(method = "(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/world/World;II)V", expect =3, at = @At( + @Redirect(method = "(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/level/Level;II)V", expect =3, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java b/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java index 456bc9bf..d080bc1b 100644 --- a/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java +++ b/src/main/java/carpet/mixins/FlatChunkGeneratorMixin.java @@ -2,91 +2,91 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.CustomSpawnLists; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.util.collection.Pool; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.gen.StructureAccessor; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.chunk.FlatChunkGenerator; -import net.minecraft.world.gen.chunk.StructuresConfig; -import net.minecraft.world.gen.feature.NetherFortressFeature; -import net.minecraft.world.gen.feature.OceanMonumentFeature; -import net.minecraft.world.gen.feature.PillagerOutpostFeature; -import net.minecraft.world.gen.feature.StructureFeature; -import net.minecraft.world.gen.feature.SwampHutFeature; import org.spongepowered.asm.mixin.Mixin; import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.util.random.WeightedRandomList; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.StructureFeatureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.FlatLevelSource; +import net.minecraft.world.level.levelgen.StructureSettings; +import net.minecraft.world.level.levelgen.feature.NetherFortressFeature; +import net.minecraft.world.level.levelgen.feature.OceanMonumentFeature; +import net.minecraft.world.level.levelgen.feature.PillagerOutpostFeature; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import net.minecraft.world.level.levelgen.feature.SwamplandHutFeature; -@Mixin(FlatChunkGenerator.class) +@Mixin(FlatLevelSource.class) public abstract class FlatChunkGeneratorMixin extends ChunkGenerator { - public FlatChunkGeneratorMixin(BiomeSource biomeSource, StructuresConfig structuresConfig) + public FlatChunkGeneratorMixin(BiomeSource biomeSource, StructureSettings structuresConfig) { super(biomeSource, structuresConfig); } @Override - public Pool getEntitySpawnList(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos) + public WeightedRandomList getMobsAt(Biome biome, StructureFeatureManager accessor, MobCategory group, BlockPos pos) { - if (!CarpetSettings.flatWorldStructureSpawning) return super.getEntitySpawnList(biome, accessor, group, pos); + if (!CarpetSettings.flatWorldStructureSpawning) return super.getMobsAt(biome, accessor, group, pos); // vanila noise one - if (accessor.getStructureAt(pos, StructureFeature.SWAMP_HUT).hasChildren()) { - if (group == SpawnGroup.MONSTER) { - return SwampHutFeature.MONSTER_SPAWNS; + if (accessor.getStructureAt(pos, StructureFeature.SWAMP_HUT).isValid()) { + if (group == MobCategory.MONSTER) { + return SwamplandHutFeature.SWAMPHUT_ENEMIES; } - if (group == SpawnGroup.CREATURE) { - return SwampHutFeature.CREATURE_SPAWNS; + if (group == MobCategory.CREATURE) { + return SwamplandHutFeature.SWAMPHUT_ANIMALS; } } - if (group == SpawnGroup.MONSTER) { - if (accessor.getStructureAt(pos, StructureFeature.PILLAGER_OUTPOST).hasChildren()) { - return PillagerOutpostFeature.MONSTER_SPAWNS; + if (group == MobCategory.MONSTER) { + if (accessor.getStructureAt(pos, StructureFeature.PILLAGER_OUTPOST).isValid()) { + return PillagerOutpostFeature.OUTPOST_ENEMIES; } - if (accessor.getStructureAt(pos, StructureFeature.MONUMENT).hasChildren()) { - return OceanMonumentFeature.MONSTER_SPAWNS; + if (accessor.getStructureAt(pos, StructureFeature.OCEAN_MONUMENT).isValid()) { + return OceanMonumentFeature.MONUMENT_ENEMIES; } - if (accessor.getStructureAt(pos, StructureFeature.FORTRESS).hasChildren()) { - return NetherFortressFeature.MONSTER_SPAWNS; + if (accessor.getStructureAt(pos, StructureFeature.NETHER_BRIDGE).isValid()) { + return NetherFortressFeature.FORTRESS_ENEMIES; } } // carpet spawns - if (group == SpawnGroup.MONSTER) + if (group == MobCategory.MONSTER) { if (CarpetSettings.huskSpawningInTemples) { - if (accessor.getStructureAt(pos, StructureFeature.DESERT_PYRAMID).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.DESERT_PYRAMID).isValid()) { return CustomSpawnLists.PYRAMID_SPAWNS; } } if (CarpetSettings.shulkerSpawningInEndCities) { - if (accessor.getStructureAt(pos, StructureFeature.END_CITY).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.END_CITY).isValid()) { return CustomSpawnLists.SHULKER_SPAWNS; } } if (CarpetSettings.piglinsSpawningInBastions) { - if (accessor.getStructureAt(pos, StructureFeature.BASTION_REMNANT).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.BASTION_REMNANT).isValid()) { return CustomSpawnLists.BASTION_SPAWNS; } } } - return (group == SpawnGroup.UNDERGROUND_WATER_CREATURE || group == SpawnGroup.AXOLOTLS) && accessor.getStructureAt(pos, StructureFeature.MONUMENT).hasChildren() ? SpawnSettings.EMPTY_ENTRY_POOL : super.getEntitySpawnList(biome, accessor, group, pos); + return (group == MobCategory.UNDERGROUND_WATER_CREATURE || group == MobCategory.AXOLOTLS) && accessor.getStructureAt(pos, StructureFeature.OCEAN_MONUMENT).isValid() ? MobSpawnSettings.EMPTY_MOB_LIST : super.getMobsAt(biome, accessor, group, pos); } diff --git a/src/main/java/carpet/mixins/FlowableFluid_liquidDamageDisabledMixin.java b/src/main/java/carpet/mixins/FlowableFluid_liquidDamageDisabledMixin.java index 1b345e8f..c647cabf 100644 --- a/src/main/java/carpet/mixins/FlowableFluid_liquidDamageDisabledMixin.java +++ b/src/main/java/carpet/mixins/FlowableFluid_liquidDamageDisabledMixin.java @@ -1,29 +1,29 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.fluid.FlowableFluid; -import net.minecraft.fluid.Fluid; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FlowingFluid; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Material; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(FlowableFluid.class) +@Mixin(FlowingFluid.class) public class FlowableFluid_liquidDamageDisabledMixin { @Inject( - method = "canFill", + method = "canHoldFluid", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/Material;blocksMovement()Z" + target = "Lnet/minecraft/world/level/material/Material;blocksMotion()Z" ), cancellable = true ) - private void stopBreakingBlock(BlockView world, BlockPos pos, BlockState state, Fluid fluid, CallbackInfoReturnable cir) + private void stopBreakingBlock(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid, CallbackInfoReturnable cir) { if (CarpetSettings.liquidDamageDisabled) { diff --git a/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java b/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java index 1a55a6af..f6342eca 100644 --- a/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java +++ b/src/main/java/carpet/mixins/FluidBlock_renewableBlackstoneMixin.java @@ -1,15 +1,15 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.FluidBlock; -import net.minecraft.fluid.FlowableFluid; -import net.minecraft.tag.FluidTags; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FlowingFluid; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -17,26 +17,26 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(FluidBlock.class) +@Mixin(LiquidBlock.class) public abstract class FluidBlock_renewableBlackstoneMixin { - @Shadow @Final protected FlowableFluid fluid; + @Shadow @Final protected FlowingFluid fluid; - @Shadow protected abstract void playExtinguishSound(WorldAccess world, BlockPos pos); + @Shadow protected abstract void fizz(LevelAccessor world, BlockPos pos); - @Inject(method = "receiveNeighborFluids", at = @At("TAIL"), cancellable = true) - private void receiveFluidToBlackstone(World world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) + @Inject(method = "shouldSpreadLiquid", at = @At("TAIL"), cancellable = true) + private void receiveFluidToBlackstone(Level world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) { if (CarpetSettings.renewableBlackstone) { - if (fluid.isIn(FluidTags.LAVA)) { + if (fluid.is(FluidTags.LAVA)) { for(Direction direction : Direction.values()) { if (direction != Direction.DOWN) { - BlockPos blockPos = pos.offset(direction); // offset - if (world.getBlockState(blockPos).isOf(Blocks.BLUE_ICE)) { - world.setBlockState(pos, Blocks.BLACKSTONE.getDefaultState()); - playExtinguishSound(world, pos); + BlockPos blockPos = pos.relative(direction); // offset + if (world.getBlockState(blockPos).is(Blocks.BLUE_ICE)) { + world.setBlockAndUpdate(pos, Blocks.BLACKSTONE.defaultBlockState()); + fizz(world, pos); cir.setReturnValue(false); } } diff --git a/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java b/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java index 2a7a3e8c..f438e1fa 100644 --- a/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java +++ b/src/main/java/carpet/mixins/FluidBlock_renewableDeepslateMixin.java @@ -1,30 +1,30 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.FluidBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(FluidBlock.class) +@Mixin(LiquidBlock.class) public abstract class FluidBlock_renewableDeepslateMixin { - @Shadow protected abstract void playExtinguishSound(WorldAccess world, BlockPos pos); + @Shadow protected abstract void fizz(LevelAccessor world, BlockPos pos); - @Inject(method = "receiveNeighborFluids", at = @At(value = "INVOKE",target = "Lnet/minecraft/fluid/FluidState;isStill()Z"), cancellable = true) - private void receiveFluidToDeepslate(World world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) + @Inject(method = "shouldSpreadLiquid", at = @At(value = "INVOKE",target = "Lnet/minecraft/world/level/material/FluidState;isSource()Z"), cancellable = true) + private void receiveFluidToDeepslate(Level world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) { - if(CarpetSettings.renewableDeepslate && !world.getFluidState(pos).isStill() && world.getRegistryKey() == World.OVERWORLD && pos.getY() < 16) + if(CarpetSettings.renewableDeepslate && !world.getFluidState(pos).isSource() && world.dimension() == Level.OVERWORLD && pos.getY() < 16) { - world.setBlockState(pos, Blocks.COBBLED_DEEPSLATE.getDefaultState()); - this.playExtinguishSound(world, pos); + world.setBlockAndUpdate(pos, Blocks.COBBLED_DEEPSLATE.defaultBlockState()); + this.fizz(world, pos); cir.setReturnValue(false); cir.cancel(); } diff --git a/src/main/java/carpet/mixins/ForceLoadCommand_forceLoadLimitMixin.java b/src/main/java/carpet/mixins/ForceLoadCommand_forceLoadLimitMixin.java index 57e2afdc..9ea69db7 100644 --- a/src/main/java/carpet/mixins/ForceLoadCommand_forceLoadLimitMixin.java +++ b/src/main/java/carpet/mixins/ForceLoadCommand_forceLoadLimitMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.command.ForceLoadCommand; +import net.minecraft.server.commands.ForceLoadCommand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; @@ -9,13 +9,13 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant; @Mixin(ForceLoadCommand.class) public class ForceLoadCommand_forceLoadLimitMixin { - @ModifyConstant(method = "executeChange", constant = @Constant(longValue = 256L)) + @ModifyConstant(method = "changeForceLoad", constant = @Constant(longValue = 256L)) private static long forceloadLimit(long original) { return CarpetSettings.forceloadLimit; } - @ModifyConstant(method = "executeChange", constant = @Constant(intValue = 256)) + @ModifyConstant(method = "changeForceLoad", constant = @Constant(intValue = 256)) private static int forceloadLimitError(int original) { return CarpetSettings.forceloadLimit; diff --git a/src/main/java/carpet/mixins/GuardianEntityMixin.java b/src/main/java/carpet/mixins/GuardianEntityMixin.java index 6ec860c5..516639b6 100644 --- a/src/main/java/carpet/mixins/GuardianEntityMixin.java +++ b/src/main/java/carpet/mixins/GuardianEntityMixin.java @@ -1,35 +1,35 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.EntityData; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LightningEntity; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.mob.ElderGuardianEntity; -import net.minecraft.entity.mob.GuardianEntity; -import net.minecraft.entity.mob.HostileEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.world.World; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SpawnGroupData; +import net.minecraft.world.entity.monster.ElderGuardian; +import net.minecraft.world.entity.monster.Guardian; +import net.minecraft.world.entity.monster.Monster; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; -@Mixin(GuardianEntity.class) -public abstract class GuardianEntityMixin extends HostileEntity +@Mixin(Guardian.class) +public abstract class GuardianEntityMixin extends Monster { - protected GuardianEntityMixin(EntityType entityType_1, World world_1) + protected GuardianEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } @Override - public void onStruckByLightning(ServerWorld serverWorld, LightningEntity lightningEntity) + public void thunderHit(ServerLevel serverWorld, LightningBolt lightningEntity) { // isRemoved() - if (!this.world.isClient && !this.isRemoved() && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardianEntity)) + if (!this.level.isClientSide && !this.isRemoved() && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardian)) { - ElderGuardianEntity elderGuardian = new ElderGuardianEntity(EntityType.ELDER_GUARDIAN ,this.world); - elderGuardian.refreshPositionAndAngles(this.getX(), this.getY(), this.getZ(), this.getYaw(), this.getPitch()); - elderGuardian.initialize(serverWorld ,this.world.getLocalDifficulty(elderGuardian.getBlockPos()), SpawnReason.CONVERSION, (EntityData)null, (NbtCompound)null); - elderGuardian.setAiDisabled(this.isAiDisabled()); + ElderGuardian elderGuardian = new ElderGuardian(EntityType.ELDER_GUARDIAN ,this.level); + elderGuardian.moveTo(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot()); + elderGuardian.finalizeSpawn(serverWorld ,this.level.getCurrentDifficultyAt(elderGuardian.blockPosition()), MobSpawnType.CONVERSION, (SpawnGroupData)null, (CompoundTag)null); + elderGuardian.setNoAi(this.isNoAi()); if (this.hasCustomName()) { @@ -37,12 +37,12 @@ public abstract class GuardianEntityMixin extends HostileEntity elderGuardian.setCustomNameVisible(this.isCustomNameVisible()); } - this.world.spawnEntity(elderGuardian); + this.level.addFreshEntity(elderGuardian); this.discard(); // discard remove(); } else { - super.onStruckByLightning(serverWorld, lightningEntity); + super.thunderHit(serverWorld, lightningEntity); } } } diff --git a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java index 0d0a323b..6ba594c9 100644 --- a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java @@ -1,16 +1,6 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.HopperBlock; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.block.entity.HopperBlockEntity; -import net.minecraft.block.entity.LootableContainerBlockEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.DyeColor; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -18,40 +8,50 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import carpet.helpers.HopperCounter; import carpet.utils.WoolTool; +import net.minecraft.core.BlockPos; +import net.minecraft.world.Container; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.HopperBlock; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.entity.HopperBlockEntity; +import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; +import net.minecraft.world.level.block.state.BlockState; /** * The {@link Mixin} which removes items in a hopper if it points into a wool counter, and calls {@link HopperCounter#add} */ @Mixin(HopperBlockEntity.class) -public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntity +public abstract class HopperBlockEntityMixin extends RandomizableContainerBlockEntity { protected HopperBlockEntityMixin(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { super(blockEntityType, blockPos, blockState); } - @Shadow public abstract int size(); + @Shadow public abstract int getContainerSize(); - @Shadow public abstract void setStack(int slot, ItemStack stack); + @Shadow public abstract void setItem(int slot, ItemStack stack); /** * A method to remove items from hoppers pointing into wool and count them via {@link HopperCounter#add} method */ - @Inject(method = "insert", at = @At("HEAD"), cancellable = true) - private static void onInsert(World world, BlockPos blockPos, BlockState blockState, Inventory inventory, CallbackInfoReturnable cir) + @Inject(method = "ejectItems", at = @At("HEAD"), cancellable = true) + private static void onInsert(Level world, BlockPos blockPos, BlockState blockState, Container inventory, CallbackInfoReturnable cir) { if (CarpetSettings.hopperCounters) { DyeColor wool_color = WoolTool.getWoolColorAtPosition( world, - blockPos.offset(blockState.get(HopperBlock.FACING))); // offset + blockPos.relative(blockState.getValue(HopperBlock.FACING))); // offset if (wool_color != null) { - for (int i = 0; i < inventory.size(); ++i) + for (int i = 0; i < inventory.getContainerSize(); ++i) { - if (!inventory.getStack(i).isEmpty()) + if (!inventory.getItem(i).isEmpty()) { - ItemStack itemstack = inventory.getStack(i);//.copy(); + ItemStack itemstack = inventory.getItem(i);//.copy(); HopperCounter.COUNTERS.get(wool_color).add(world.getServer(), itemstack); - inventory.setStack(i, ItemStack.EMPTY); + inventory.setItem(i, ItemStack.EMPTY); } } cir.setReturnValue(true); diff --git a/src/main/java/carpet/mixins/HopperBlock_cactusMixin.java b/src/main/java/carpet/mixins/HopperBlock_cactusMixin.java index 5eed6fd6..4394677b 100644 --- a/src/main/java/carpet/mixins/HopperBlock_cactusMixin.java +++ b/src/main/java/carpet/mixins/HopperBlock_cactusMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; import carpet.helpers.BlockRotator; -import net.minecraft.block.HopperBlock; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.HopperBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -11,16 +11,16 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(HopperBlock.class) public class HopperBlock_cactusMixin { - @Redirect(method = "getPlacementState", at = @At( + @Redirect(method = "getStateForPlacement", at = @At( value = "INVOKE", - target = "Lnet/minecraft/item/ItemPlacementContext;getSide()Lnet/minecraft/util/math/Direction;" + target = "Lnet/minecraft/world/item/context/BlockPlaceContext;getClickedFace()Lnet/minecraft/core/Direction;" )) - private Direction getOppositeOpposite(ItemPlacementContext context) + private Direction getOppositeOpposite(BlockPlaceContext context) { if (BlockRotator.flippinEligibility(context.getPlayer())) { - return context.getSide().getOpposite(); + return context.getClickedFace().getOpposite(); } - return context.getSide(); + return context.getClickedFace(); } } diff --git a/src/main/java/carpet/mixins/HorseBaseEntity_scarpetMixin.java b/src/main/java/carpet/mixins/HorseBaseEntity_scarpetMixin.java index dc08d54d..4e74292d 100644 --- a/src/main/java/carpet/mixins/HorseBaseEntity_scarpetMixin.java +++ b/src/main/java/carpet/mixins/HorseBaseEntity_scarpetMixin.java @@ -1,21 +1,21 @@ package carpet.mixins; import carpet.fakes.InventoryBearerInterface; -import net.minecraft.entity.passive.HorseBaseEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.animal.horse.AbstractHorse; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(HorseBaseEntity.class) +@Mixin(AbstractHorse.class) public class HorseBaseEntity_scarpetMixin implements InventoryBearerInterface { - @Shadow protected SimpleInventory items; + @Shadow protected SimpleContainer inventory; @Override - public Inventory getCMInventory() + public Container getCMInventory() { - return items; + return inventory; } } diff --git a/src/main/java/carpet/mixins/HuskEntityMixin.java b/src/main/java/carpet/mixins/HuskEntityMixin.java index 06dcbb76..ad5913eb 100644 --- a/src/main/java/carpet/mixins/HuskEntityMixin.java +++ b/src/main/java/carpet/mixins/HuskEntityMixin.java @@ -1,22 +1,22 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.mob.HuskEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ServerWorldAccess; -import net.minecraft.world.gen.feature.StructureFeature; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.monster.Husk; +import net.minecraft.world.level.ServerLevelAccessor; +import net.minecraft.world.level.levelgen.feature.StructureFeature; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(HuskEntity.class) +@Mixin(Husk.class) public class HuskEntityMixin { - @Redirect(method = "canSpawn", at = @At(value = "INVOKE", target="Lnet/minecraft/world/ServerWorldAccess;isSkyVisible(Lnet/minecraft/util/math/BlockPos;)Z")) - private static boolean isSkylightOrTempleVisible(ServerWorldAccess serverWorldAccess, BlockPos pos) + @Redirect(method = "checkHuskSpawnRules", at = @At(value = "INVOKE", target="Lnet/minecraft/world/level/ServerLevelAccessor;canSeeSky(Lnet/minecraft/core/BlockPos;)Z")) + private static boolean isSkylightOrTempleVisible(ServerLevelAccessor serverWorldAccess, BlockPos pos) { - return serverWorldAccess.isSkyVisible(pos) || - (CarpetSettings.huskSpawningInTemples && (((ServerWorld)serverWorldAccess).getStructureAccessor().getStructureAt(pos, StructureFeature.DESERT_PYRAMID).hasChildren())); + return serverWorldAccess.canSeeSky(pos) || + (CarpetSettings.huskSpawningInTemples && (((ServerLevel)serverWorldAccess).structureFeatureManager().getStructureAt(pos, StructureFeature.DESERT_PYRAMID).isValid())); } } diff --git a/src/main/java/carpet/mixins/InGameHudMixin.java b/src/main/java/carpet/mixins/InGameHudMixin.java index d2c70761..041a08d4 100644 --- a/src/main/java/carpet/mixins/InGameHudMixin.java +++ b/src/main/java/carpet/mixins/InGameHudMixin.java @@ -1,28 +1,28 @@ package carpet.mixins; import carpet.fakes.PlayerListHudInterface; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.hud.InGameHud; -import net.minecraft.client.gui.hud.PlayerListHud; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.components.PlayerTabOverlay; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(InGameHud.class) +@Mixin(Gui.class) public abstract class InGameHudMixin { @Shadow @Final - private MinecraftClient client; + private Minecraft minecraft; - @Shadow @Final private PlayerListHud playerListHud; + @Shadow @Final private PlayerTabOverlay tabList; - @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;isInSingleplayer()Z")) - private boolean onDraw(MinecraftClient minecraftClient) + @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;isLocalServer()Z")) + private boolean onDraw(Minecraft minecraftClient) { - return this.client.isInSingleplayer() && !((PlayerListHudInterface) playerListHud).hasFooterOrHeader(); + return this.minecraft.isLocalServer() && !((PlayerListHudInterface) tabList).hasFooterOrHeader(); } } diff --git a/src/main/java/carpet/mixins/InfestedBlockMixin.java b/src/main/java/carpet/mixins/InfestedBlockMixin.java index 9f63995e..87edd3eb 100644 --- a/src/main/java/carpet/mixins/InfestedBlockMixin.java +++ b/src/main/java/carpet/mixins/InfestedBlockMixin.java @@ -1,12 +1,12 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; -import net.minecraft.block.InfestedBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.InfestedBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -15,18 +15,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(InfestedBlock.class) public abstract class InfestedBlockMixin extends Block { - public InfestedBlockMixin(Settings block$Settings_1) + public InfestedBlockMixin(Properties block$Settings_1) { super(block$Settings_1); } - @Inject(method = "spawnSilverfish", at = @At(value = "INVOKE", shift = At.Shift.AFTER, - target = "Lnet/minecraft/entity/mob/SilverfishEntity;playSpawnEffects()V")) - private void onOnStacksDropped(ServerWorld serverWorld, BlockPos pos, CallbackInfo ci) + @Inject(method = "spawnInfestation", at = @At(value = "INVOKE", shift = At.Shift.AFTER, + target = "Lnet/minecraft/world/entity/monster/Silverfish;spawnAnim()V")) + private void onOnStacksDropped(ServerLevel serverWorld, BlockPos pos, CallbackInfo ci) { if (CarpetSettings.silverFishDropGravel) { - dropStack(serverWorld, pos, new ItemStack(Blocks.GRAVEL)); + popResource(serverWorld, pos, new ItemStack(Blocks.GRAVEL)); } } } \ No newline at end of file diff --git a/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java b/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java index f4b68577..79a10391 100644 --- a/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java +++ b/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java @@ -1,8 +1,6 @@ package carpet.mixins; import carpet.fakes.IngredientInterface; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.Ingredient; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,16 +9,18 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; @Mixin(Ingredient.class) public class Ingredient_scarpetMixin implements IngredientInterface { - @Shadow @Final private Ingredient.Entry[] entries; + @Shadow @Final private Ingredient.Value[] values; @Override public List> getRecipeStacks() { - List> res = Arrays.stream(entries).map(Ingredient.Entry::getStacks).collect(Collectors.toList()); + List> res = Arrays.stream(values).map(Ingredient.Value::getItems).collect(Collectors.toList()); return res; } } diff --git a/src/main/java/carpet/mixins/ItemDispenserBehaviour_extremeBehavioursMixin.java b/src/main/java/carpet/mixins/ItemDispenserBehaviour_extremeBehavioursMixin.java index 9ee1a237..25f9b46f 100644 --- a/src/main/java/carpet/mixins/ItemDispenserBehaviour_extremeBehavioursMixin.java +++ b/src/main/java/carpet/mixins/ItemDispenserBehaviour_extremeBehavioursMixin.java @@ -1,14 +1,14 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.block.dispenser.ItemDispenserBehavior; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; -@Mixin(ItemDispenserBehavior.class) +@Mixin(DefaultDispenseItemBehavior.class) public class ItemDispenserBehaviour_extremeBehavioursMixin { @Redirect(method = "spawnItem", expect = 3, at = @At( diff --git a/src/main/java/carpet/mixins/ItemEntityMixin.java b/src/main/java/carpet/mixins/ItemEntityMixin.java index ad4cd807..00d83547 100644 --- a/src/main/java/carpet/mixins/ItemEntityMixin.java +++ b/src/main/java/carpet/mixins/ItemEntityMixin.java @@ -2,16 +2,16 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.InventoryHelper; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.ShulkerBoxBlock; import carpet.fakes.ItemEntityInterface; -import net.minecraft.block.ShulkerBoxBlock; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.ItemEntity; -import net.minecraft.entity.LightningEntity; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -24,21 +24,21 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf { private static final int SHULKERBOX_MAX_STACK_AMOUNT = 64; - @Shadow private int itemAge; + @Shadow private int age; @Shadow private int pickupDelay; - public ItemEntityMixin(EntityType entityType_1, World world_1) { + public ItemEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } @Override - public void onStruckByLightning(ServerWorld world, LightningEntity lightning) { + public void thunderHit(ServerLevel world, LightningBolt lightning) { if (CarpetSettings.lightningKillsDropsFix) { - if (this.itemAge > 8) { //Only kill item if its older then 8 ticks - super.onStruckByLightning(world, lightning); + if (this.age > 8) { //Only kill item if its older then 8 ticks + super.thunderHit(world, lightning); } } else { - super.onStruckByLightning(world, lightning); + super.thunderHit(world, lightning); } } @@ -47,69 +47,69 @@ public abstract class ItemEntityMixin extends Entity implements ItemEntityInterf return this.pickupDelay; } - @Inject(method="(Lnet/minecraft/world/World;DDDLnet/minecraft/item/ItemStack;)V", at = @At("RETURN")) - private void removeEmptyShulkerBoxTags(World worldIn, double x, double y, double z, ItemStack stack, CallbackInfo ci) + @Inject(method="(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/item/ItemStack;)V", at = @At("RETURN")) + private void removeEmptyShulkerBoxTags(Level worldIn, double x, double y, double z, ItemStack stack, CallbackInfo ci) { if (CarpetSettings.shulkerBoxStackSize > 1 && stack.getItem() instanceof BlockItem && ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { if (InventoryHelper.cleanUpShulkerBoxTag(stack)) { - ((ItemEntity) (Object) this).setStack(stack); + ((ItemEntity) (Object) this).setItem(stack); } } } @Redirect( - method = "canMerge()Z", + method = "isMergable()Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/item/ItemStack;getMaxCount()I" + target = "Lnet/minecraft/world/item/ItemStack;getMaxStackSize()I" ) ) private int getItemStackMaxAmount(ItemStack stack) { if (CarpetSettings.shulkerBoxStackSize > 1 && stack.getItem() instanceof BlockItem && ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock) return CarpetSettings.shulkerBoxStackSize; - return stack.getMaxCount(); + return stack.getMaxStackSize(); } @Inject( - method = "tryMerge(Lnet/minecraft/entity/ItemEntity;)V", + method = "tryToMerge(Lnet/minecraft/world/entity/item/ItemEntity;)V", at = @At("HEAD"), cancellable = true ) private void tryStackShulkerBoxes(ItemEntity other, CallbackInfo ci) { ItemEntity self = (ItemEntity)(Object)this; - ItemStack selfStack = self.getStack(); + ItemStack selfStack = self.getItem(); if (CarpetSettings.shulkerBoxStackSize == 1 || !(selfStack.getItem() instanceof BlockItem) || !(((BlockItem)selfStack.getItem()).getBlock() instanceof ShulkerBoxBlock)) { return; } - ItemStack otherStack = other.getStack(); + ItemStack otherStack = other.getItem(); if (selfStack.getItem() == otherStack.getItem() && !InventoryHelper.shulkerBoxHasItems(selfStack) && !InventoryHelper.shulkerBoxHasItems(otherStack) - && selfStack.hasNbt() == otherStack.hasNbt() + && selfStack.hasTag() == otherStack.hasTag() && selfStack.getCount() + otherStack.getCount() <= CarpetSettings.shulkerBoxStackSize) { int amount = Math.min(otherStack.getCount(), CarpetSettings.shulkerBoxStackSize - selfStack.getCount()); - selfStack.increment(amount); - self.setStack(selfStack); + selfStack.grow(amount); + self.setItem(selfStack); this.pickupDelay = Math.max(((ItemEntityInterface)other).getPickupDelayCM(), this.pickupDelay); - this.itemAge = Math.min(other.getItemAge(), this.itemAge); + this.age = Math.min(other.getAge(), this.age); - otherStack.decrement(amount); + otherStack.shrink(amount); if (otherStack.isEmpty()) { other.discard(); // discard remove(); } else { - other.setStack(otherStack); + other.setItem(otherStack); } ci.cancel(); } diff --git a/src/main/java/carpet/mixins/ItemScatterer_extremeMixin.java b/src/main/java/carpet/mixins/ItemScatterer_extremeMixin.java index df45575d..bd8601da 100644 --- a/src/main/java/carpet/mixins/ItemScatterer_extremeMixin.java +++ b/src/main/java/carpet/mixins/ItemScatterer_extremeMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.util.ItemScatterer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.Containers; -@Mixin(ItemScatterer.class) +@Mixin(Containers.class) public class ItemScatterer_extremeMixin { - @Redirect(method = "spawn(Lnet/minecraft/world/World;DDDLnet/minecraft/item/ItemStack;)V", expect = 3, at = @At( + @Redirect(method = "dropItemStack(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/item/ItemStack;)V", expect = 3, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/ItemUsageContext_cactusMixin.java b/src/main/java/carpet/mixins/ItemUsageContext_cactusMixin.java index 5f9d86b1..df0ecc23 100644 --- a/src/main/java/carpet/mixins/ItemUsageContext_cactusMixin.java +++ b/src/main/java/carpet/mixins/ItemUsageContext_cactusMixin.java @@ -1,23 +1,23 @@ package carpet.mixins; import carpet.helpers.BlockRotator; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemUsageContext; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.context.UseOnContext; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(ItemUsageContext.class) +@Mixin(UseOnContext.class) public class ItemUsageContext_cactusMixin { - @Redirect(method = "getPlayerFacing", at = @At( + @Redirect(method = "getHorizontalDirection", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;getHorizontalFacing()Lnet/minecraft/util/math/Direction;" + target = "Lnet/minecraft/world/entity/player/Player;getDirection()Lnet/minecraft/core/Direction;" )) - private Direction getPlayerFacing(PlayerEntity playerEntity) + private Direction getPlayerFacing(Player playerEntity) { - Direction dir = playerEntity.getHorizontalFacing(); + Direction dir = playerEntity.getDirection(); if (BlockRotator.flippinEligibility(playerEntity)) { dir = dir.getOpposite(); diff --git a/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java b/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java index 8d902f65..2f3003e2 100644 --- a/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java +++ b/src/main/java/carpet/mixins/LavaFluid_renewableDeepslateMixin.java @@ -1,14 +1,14 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.fluid.FluidState; -import net.minecraft.fluid.LavaFluid; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.LavaFluid; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -17,15 +17,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(LavaFluid.class) public abstract class LavaFluid_renewableDeepslateMixin { - @Shadow protected abstract void playExtinguishEvent(WorldAccess world, BlockPos pos); + @Shadow protected abstract void fizz(LevelAccessor world, BlockPos pos); - @Inject(method = "flow", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;getDefaultState()Lnet/minecraft/block/BlockState;"), cancellable = true) - private void generateDeepslate(WorldAccess world, BlockPos pos, BlockState state, Direction direction, FluidState fluidState, CallbackInfo ci) + @Inject(method = "spreadTo", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/Block;defaultBlockState()Lnet/minecraft/world/level/block/state/BlockState;"), cancellable = true) + private void generateDeepslate(LevelAccessor world, BlockPos pos, BlockState state, Direction direction, FluidState fluidState, CallbackInfo ci) { - if(CarpetSettings.renewableDeepslate && ((World)world).getRegistryKey() == World.OVERWORLD && pos.getY() < 16) + if(CarpetSettings.renewableDeepslate && ((Level)world).dimension() == Level.OVERWORLD && pos.getY() < 16) { - world.setBlockState(pos, Blocks.DEEPSLATE.getDefaultState(), 3); - this.playExtinguishEvent(world, pos); + world.setBlock(pos, Blocks.DEEPSLATE.defaultBlockState(), 3); + this.fizz(world, pos); ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/LevelPropagator_resetChunkInterface.java b/src/main/java/carpet/mixins/LevelPropagator_resetChunkInterface.java index fcfe9e41..65f073e4 100644 --- a/src/main/java/carpet/mixins/LevelPropagator_resetChunkInterface.java +++ b/src/main/java/carpet/mixins/LevelPropagator_resetChunkInterface.java @@ -1,16 +1,15 @@ package carpet.mixins; +import net.minecraft.world.level.lighting.DynamicGraphMinFixedPoint; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; -import net.minecraft.world.chunk.light.LevelPropagator; - -@Mixin(LevelPropagator.class) +@Mixin(DynamicGraphMinFixedPoint.class) public interface LevelPropagator_resetChunkInterface { - @Invoker("updateLevel") + @Invoker("checkEdge") void cmInvokeUpdateLevel(long sourceId, long id, int level, boolean decrease); - @Invoker("getPropagatedLevel") + @Invoker("computeLevelFromNeighbor") int cmCallGetPropagatedLevel(long sourceId, long targetId, int level); } diff --git a/src/main/java/carpet/mixins/LightStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LightStorage_scarpetChunkCreationMixin.java index 5a035131..fd2de4c7 100644 --- a/src/main/java/carpet/mixins/LightStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LightStorage_scarpetChunkCreationMixin.java @@ -1,7 +1,11 @@ package carpet.mixins; import java.util.Arrays; - +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.lighting.DataLayerStorageMap; +import net.minecraft.world.level.lighting.LayerLightEngine; +import net.minecraft.world.level.lighting.LayerLightSectionStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -14,36 +18,31 @@ import carpet.fakes.LightStorageInterface; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.world.chunk.ChunkNibbleArray; -import net.minecraft.world.chunk.ChunkToNibbleArrayMap; -import net.minecraft.world.chunk.light.ChunkLightProvider; -import net.minecraft.world.chunk.light.LightStorage; -@Mixin(LightStorage.class) +@Mixin(LayerLightSectionStorage.class) public abstract class LightStorage_scarpetChunkCreationMixin implements LightStorageInterface { @Shadow - protected abstract ChunkNibbleArray getLightSection(final long sectionPos, final boolean cached); + protected abstract DataLayer getDataLayer(final long sectionPos, final boolean cached); @Shadow - protected abstract void removeSection(final ChunkLightProvider storage, final long blockChunkPos); + protected abstract void clearQueuedSectionBlocks(final LayerLightEngine storage, final long blockChunkPos); @Shadow @Final - protected LongSet dirtySections; + protected LongSet changedSections; @Shadow @Final - protected ChunkToNibbleArrayMap storage; + protected DataLayerStorageMap updatingSectionData; - @Shadow protected abstract boolean hasSection(final long sectionPos); + @Shadow protected abstract boolean storingLightForSection(final long sectionPos); @Shadow @Final - protected Long2ObjectMap queuedSections; + protected Long2ObjectMap queuedSections; - @Shadow protected abstract void setColumnEnabled(final long l, final boolean bl); + @Shadow protected abstract void enableLightSources(final long l, final boolean bl); @Unique private final LongSet removedChunks = new LongOpenHashSet(); @@ -64,10 +63,10 @@ public abstract class LightStorage_scarpetChunkCreationMixin implements LightSto } @Inject( - method = "updateLight(Lnet/minecraft/world/chunk/light/ChunkLightProvider;ZZ)V", + method = "markNewInconsistencies(Lnet/minecraft/world/level/lighting/LayerLightEngine;ZZ)V", at = @At("HEAD") ) - private void processData(final ChunkLightProvider lightProvider, final boolean doSkylight, final boolean skipEdgeLightPropagation, final CallbackInfo ci) + private void processData(final LayerLightEngine lightProvider, final boolean doSkylight, final boolean skipEdgeLightPropagation, final CallbackInfo ci) { // Process light removal @@ -75,18 +74,18 @@ public abstract class LightStorage_scarpetChunkCreationMixin implements LightSto { for (int y = -1; y < 17; ++y) { - final long sectionPos = ChunkSectionPos.asLong(ChunkSectionPos.unpackX(cPos), y, ChunkSectionPos.unpackZ(cPos)); + final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); this.queuedSections.remove(sectionPos); - if (this.hasSection(sectionPos)) + if (this.storingLightForSection(sectionPos)) { - this.removeSection(lightProvider, sectionPos); + this.clearQueuedSectionBlocks(lightProvider, sectionPos); - if (this.dirtySections.add(sectionPos)) - this.storage.replaceWithCopy(sectionPos); + if (this.changedSections.add(sectionPos)) + this.updatingSectionData.copyDataLayer(sectionPos); - Arrays.fill(this.getLightSection(sectionPos, true).asByteArray(), (byte) 0); + Arrays.fill(this.getDataLayer(sectionPos, true).getData(), (byte) 0); } } @@ -109,7 +108,7 @@ public abstract class LightStorage_scarpetChunkCreationMixin implements LightSto } @Override - public void processRelight(final ChunkLightProvider lightProvider, final long pos) + public void processRelight(final LayerLightEngine lightProvider, final long pos) { } } diff --git a/src/main/java/carpet/mixins/LightingProvider_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LightingProvider_scarpetChunkCreationMixin.java index 06054551..52b396d0 100644 --- a/src/main/java/carpet/mixins/LightingProvider_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LightingProvider_scarpetChunkCreationMixin.java @@ -5,37 +5,37 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import carpet.fakes.Lighting_scarpetChunkCreationInterface; -import net.minecraft.world.chunk.light.ChunkLightProvider; -import net.minecraft.world.chunk.light.LightingProvider; +import net.minecraft.world.level.lighting.LayerLightEngine; +import net.minecraft.world.level.lighting.LevelLightEngine; -@Mixin(LightingProvider.class) +@Mixin(LevelLightEngine.class) public abstract class LightingProvider_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface { @Shadow @Final - private ChunkLightProvider blockLightProvider; + private LayerLightEngine blockEngine; @Shadow @Final - private ChunkLightProvider skyLightProvider; + private LayerLightEngine skyEngine; @Override public void removeLightData(final long pos) { - if (this.blockLightProvider != null) - ((Lighting_scarpetChunkCreationInterface) this.blockLightProvider).removeLightData(pos); + if (this.blockEngine != null) + ((Lighting_scarpetChunkCreationInterface) this.blockEngine).removeLightData(pos); - if (this.skyLightProvider != null) - ((Lighting_scarpetChunkCreationInterface) this.skyLightProvider).removeLightData(pos); + if (this.skyEngine != null) + ((Lighting_scarpetChunkCreationInterface) this.skyEngine).removeLightData(pos); } @Override public void relight(final long pos) { - if (this.blockLightProvider != null) - ((Lighting_scarpetChunkCreationInterface) this.blockLightProvider).relight(pos); + if (this.blockEngine != null) + ((Lighting_scarpetChunkCreationInterface) this.blockEngine).relight(pos); - if (this.skyLightProvider != null) - ((Lighting_scarpetChunkCreationInterface) this.skyLightProvider).relight(pos); + if (this.skyEngine != null) + ((Lighting_scarpetChunkCreationInterface) this.skyEngine).relight(pos); } } diff --git a/src/main/java/carpet/mixins/LivingEntityMixin.java b/src/main/java/carpet/mixins/LivingEntityMixin.java index 22e6c578..d43f542c 100644 --- a/src/main/java/carpet/mixins/LivingEntityMixin.java +++ b/src/main/java/carpet/mixins/LivingEntityMixin.java @@ -1,11 +1,11 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.world.GameRules; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -14,14 +14,14 @@ import org.spongepowered.asm.mixin.injection.Redirect; public abstract class LivingEntityMixin extends Entity { - public LivingEntityMixin(EntityType type, World world) + public LivingEntityMixin(EntityType type, Level world) { super(type, world); } - @Redirect(method = "onDeath", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/LivingEntity;hasCustomName()Z")) + @Redirect(method = "die", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hasCustomName()Z")) private boolean shouldLogDeaths(LivingEntity livingEntity) { - return livingEntity.hasCustomName() && CarpetSettings.cleanLogs && world.getGameRules().getBoolean(GameRules.SHOW_DEATH_MESSAGES); + return livingEntity.hasCustomName() && CarpetSettings.cleanLogs && level.getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES); } } diff --git a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java index a96f0155..b96c9eb1 100644 --- a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java @@ -1,11 +1,11 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -17,9 +17,9 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(LivingEntity.class) public abstract class LivingEntity_creativeFlyMixin extends Entity { - @Shadow public float airStrafingSpeed; + @Shadow public float flyingSpeed; - public LivingEntity_creativeFlyMixin(EntityType type, World world) + public LivingEntity_creativeFlyMixin(EntityType type, Level world) { super(type, world); } @@ -27,9 +27,9 @@ public abstract class LivingEntity_creativeFlyMixin extends Entity @ModifyConstant(method = "travel", constant = @Constant(floatValue = 0.91F), expect = 2) private float drag(float original) { - if (CarpetSettings.creativeFlyDrag != 0.09 && (Object)this instanceof PlayerEntity) + if (CarpetSettings.creativeFlyDrag != 0.09 && (Object)this instanceof Player) { - PlayerEntity self = (PlayerEntity)(Object)(this); + Player self = (Player)(Object)(this); if (self.getAbilities().flying && ! onGround ) return (float)(1.0-CarpetSettings.creativeFlyDrag); } @@ -37,14 +37,14 @@ public abstract class LivingEntity_creativeFlyMixin extends Entity } - @Inject(method = "getMovementSpeed(F)F", at = @At("HEAD"), cancellable = true) + @Inject(method = "getFrictionInfluencedSpeed(F)F", at = @At("HEAD"), cancellable = true) private void flyingAltSpeed(float slipperiness, CallbackInfoReturnable cir) { - if (CarpetSettings.creativeFlySpeed != 1.0D && (Object)this instanceof PlayerEntity) + if (CarpetSettings.creativeFlySpeed != 1.0D && (Object)this instanceof Player) { - PlayerEntity self = (PlayerEntity)(Object)(this); + Player self = (Player)(Object)(this); if (self.getAbilities().flying && !onGround) - cir.setReturnValue( airStrafingSpeed* (float)CarpetSettings.creativeFlySpeed); + cir.setReturnValue( flyingSpeed* (float)CarpetSettings.creativeFlySpeed); } } } diff --git a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java index f5364c70..c7f4369e 100644 --- a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java @@ -2,13 +2,6 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.WorldInterface; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.world.GameRules; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -16,63 +9,70 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySelector; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.Level; @Mixin(LivingEntity.class) public abstract class LivingEntity_maxCollisionsMixin extends Entity { - public LivingEntity_maxCollisionsMixin(EntityType entityType_1, World world_1) + public LivingEntity_maxCollisionsMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Shadow protected abstract void pushAway(Entity entity_1); + @Shadow protected abstract void doPush(Entity entity_1); - @Inject(method = "tickCramming", cancellable = true, at = @At("HEAD")) + @Inject(method = "pushEntities", cancellable = true, at = @At("HEAD")) private void tickPushingReplacement(CallbackInfo ci) { List entities; int maxEntityCramming =-1; if (CarpetSettings.maxEntityCollisions > 0) { - maxEntityCramming = this.world.getGameRules().getInt(GameRules.MAX_ENTITY_CRAMMING); - entities = ((WorldInterface) this.world).getOtherEntitiesLimited( + maxEntityCramming = this.level.getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING); + entities = ((WorldInterface) this.level).getOtherEntitiesLimited( this, this.getBoundingBox(), - EntityPredicates.canBePushedBy(this), + EntitySelector.pushableBy(this), Math.max(CarpetSettings.maxEntityCollisions, maxEntityCramming)); } else { - entities = this.world.getOtherEntities(this, this.getBoundingBox(), EntityPredicates.canBePushedBy(this)); + entities = this.level.getEntities(this, this.getBoundingBox(), EntitySelector.pushableBy(this)); } if (!entities.isEmpty()) { - if (maxEntityCramming < 0) maxEntityCramming = this.world.getGameRules().getInt(GameRules.MAX_ENTITY_CRAMMING); + if (maxEntityCramming < 0) maxEntityCramming = this.level.getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING); if (maxEntityCramming > 0 && entities.size() > maxEntityCramming - 1 && this.random.nextInt(4) == 0) { int candidates = 0; for (Entity entity : entities) { - if (!entity.hasVehicle()) { + if (!entity.isPassenger()) { ++candidates; } } if (candidates > maxEntityCramming - 1) { - this.damage(DamageSource.CRAMMING, 6.0F); + this.hurt(DamageSource.CRAMMING, 6.0F); } } if (CarpetSettings.maxEntityCollisions > 0 && entities.size() > CarpetSettings.maxEntityCollisions) { for (Entity entity : entities.subList(0, CarpetSettings.maxEntityCollisions)) { - this.pushAway(entity); + this.doPush(entity); } } else { for (Entity entity : entities) { - this.pushAway(entity); + this.doPush(entity); } } } diff --git a/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java index 74822fd4..1cf2ca2c 100644 --- a/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java @@ -3,12 +3,12 @@ package carpet.mixins; import carpet.fakes.EntityInterface; import carpet.fakes.LivingEntityInterface; import carpet.script.EntityEventsGroup; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.world.World; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -22,24 +22,24 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_DEALS_DAMAGE; public abstract class LivingEntity_scarpetEventsMixin extends Entity implements LivingEntityInterface { - @Shadow protected abstract void jump(); + @Shadow protected abstract void jumpFromGround(); @Shadow protected boolean jumping; - public LivingEntity_scarpetEventsMixin(EntityType type, World world) + public LivingEntity_scarpetEventsMixin(EntityType type, Level world) { super(type, world); } - @Inject(method = "onDeath", at = @At("HEAD")) + @Inject(method = "die", at = @At("HEAD")) private void onDeathCall(DamageSource damageSource_1, CallbackInfo ci) { - ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, damageSource_1.name); + ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, damageSource_1.msgId); } - @Inject(method = "applyDamage", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( + @Inject(method = "actuallyHurt", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/LivingEntity;applyArmorToDamage(Lnet/minecraft/entity/damage/DamageSource;F)F", + target = "Lnet/minecraft/world/entity/LivingEntity;getDamageAfterArmorAbsorb(Lnet/minecraft/world/damagesource/DamageSource;F)F", shift = At.Shift.BEFORE )) private void entityTakingDamage(DamageSource source, float amount, CallbackInfo ci) @@ -50,7 +50,7 @@ public abstract class LivingEntity_scarpetEventsMixin extends Entity implements //{ // PLAYER_TAKES_DAMAGE.onDamage(entity, float_2, damageSource_1); //} - if (source.getAttacker() instanceof ServerPlayerEntity && PLAYER_DEALS_DAMAGE.isNeeded()) + if (source.getEntity() instanceof ServerPlayer && PLAYER_DEALS_DAMAGE.isNeeded()) { PLAYER_DEALS_DAMAGE.onDamage(this, amount, source); } @@ -59,7 +59,7 @@ public abstract class LivingEntity_scarpetEventsMixin extends Entity implements @Override public void doJumpCM() { - jump(); + jumpFromGround(); } @Override diff --git a/src/main/java/carpet/mixins/MinecraftClientMixin.java b/src/main/java/carpet/mixins/MinecraftClientMixin.java index d0a340a5..54656f79 100644 --- a/src/main/java/carpet/mixins/MinecraftClientMixin.java +++ b/src/main/java/carpet/mixins/MinecraftClientMixin.java @@ -3,21 +3,21 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.helpers.TickSpeed; import carpet.network.CarpetClient; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.world.ClientWorld; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.ClientLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(MinecraftClient.class) +@Mixin(Minecraft.class) public class MinecraftClientMixin { - @Shadow public ClientWorld world; + @Shadow public ClientLevel level; - @Inject(method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;)V", at = @At("HEAD")) + @Inject(method = "clearLevel(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At("HEAD")) private void onCloseGame(Screen screen, CallbackInfo ci) { CarpetClient.disconnect(); @@ -25,7 +25,7 @@ public class MinecraftClientMixin @Inject(at = @At("HEAD"), method = "tick") private void onClientTick(CallbackInfo info) { - if (this.world != null) { + if (this.level != null) { if (CarpetServer.minecraft_server == null) TickSpeed.tick(); if (!TickSpeed.process_entities) diff --git a/src/main/java/carpet/mixins/MinecraftClient_pausedShakeMixin.java b/src/main/java/carpet/mixins/MinecraftClient_pausedShakeMixin.java index 693ad49f..7560f254 100644 --- a/src/main/java/carpet/mixins/MinecraftClient_pausedShakeMixin.java +++ b/src/main/java/carpet/mixins/MinecraftClient_pausedShakeMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.fakes.MinecraftClientInferface; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(MinecraftClient.class) +@Mixin(Minecraft.class) public class MinecraftClient_pausedShakeMixin implements MinecraftClientInferface { - @Shadow private float pausedTickDelta; + @Shadow private float pausePartialTick; @Override public float getPausedTickDelta() { - return pausedTickDelta; + return pausePartialTick; } } diff --git a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java index 29511879..1f5dcc26 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java @@ -4,7 +4,7 @@ import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.utils.CarpetProfiler; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.WorldGenerationProgressListener; +import net.minecraft.server.level.progress.ChunkProgressListener; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -18,10 +18,10 @@ public abstract class MinecraftServer_coreMixin //to inject right before // this.tickWorlds(booleanSupplier_1); @Inject( - method = "tick", + method = "tickServer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/MinecraftServer;tickWorlds(Ljava/util/function/BooleanSupplier;)V", + target = "Lnet/minecraft/server/MinecraftServer;tickChildren(Ljava/util/function/BooleanSupplier;)V", shift = At.Shift.BEFORE, ordinal = 0 ) @@ -32,32 +32,32 @@ public abstract class MinecraftServer_coreMixin CarpetProfiler.end_current_section(token); } - @Inject(method = "loadWorld", at = @At("HEAD")) + @Inject(method = "loadLevel", at = @At("HEAD")) private void serverLoaded(CallbackInfo ci) { CarpetServer.onServerLoaded((MinecraftServer) (Object) this); } - @Inject(method = "loadWorld", at = @At("RETURN")) + @Inject(method = "loadLevel", at = @At("RETURN")) private void serverLoadedWorlds(CallbackInfo ci) { CarpetServer.onServerLoadedWorlds((MinecraftServer) (Object) this); } - @Inject(method = "shutdown", at = @At("HEAD")) + @Inject(method = "stopServer", at = @At("HEAD")) private void serverClosed(CallbackInfo ci) { CarpetServer.onServerClosed((MinecraftServer) (Object) this); } - @Inject(method = "shutdown", at = @At("TAIL")) + @Inject(method = "stopServer", at = @At("TAIL")) private void serverDoneClosed(CallbackInfo ci) { CarpetServer.onServerDoneClosing((MinecraftServer) (Object) this); } - @Inject(method = "prepareStartRegion", at = @At("RETURN")) - private void afterSpawnCreated(WorldGenerationProgressListener worldGenerationProgressListener, CallbackInfo ci) + @Inject(method = "prepareLevels", at = @At("RETURN")) + private void afterSpawnCreated(ChunkProgressListener worldGenerationProgressListener, CallbackInfo ci) { if (CarpetSettings.spawnChunksSize != 11) CarpetSettings.ChangeSpawnChunksValidator.changeSpawnSize(CarpetSettings.spawnChunksSize); diff --git a/src/main/java/carpet/mixins/MinecraftServer_pingPlayerSampleLimit.java b/src/main/java/carpet/mixins/MinecraftServer_pingPlayerSampleLimit.java index 79e2e27d..e53249c1 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_pingPlayerSampleLimit.java +++ b/src/main/java/carpet/mixins/MinecraftServer_pingPlayerSampleLimit.java @@ -11,7 +11,7 @@ import net.minecraft.server.MinecraftServer; public abstract class MinecraftServer_pingPlayerSampleLimit { - @ModifyConstant(method = "tick", constant = @Constant(intValue = 12), require = 0, allow = 1) + @ModifyConstant(method = "tickServer", constant = @Constant(intValue = 12), require = 0, allow = 1) private int modifyPlayerSampleLimit(int value) { return CarpetSettings.pingPlayerListLimit; diff --git a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java index 1b71dfa9..07828dbc 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java @@ -2,15 +2,15 @@ package carpet.mixins; import carpet.fakes.MinecraftServerInterface; import carpet.helpers.TickSpeed; -import net.minecraft.resource.ServerResourceManager; +import net.minecraft.Util; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerTask; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Util; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.util.thread.ReentrantThreadExecutor; -import net.minecraft.world.World; -import net.minecraft.world.level.storage.LevelStorage; +import net.minecraft.server.ServerResources; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.thread.ReentrantBlockableEventLoop; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -26,53 +26,53 @@ import static carpet.script.CarpetEventServer.Event.NETHER_TICK; import static carpet.script.CarpetEventServer.Event.TICK; @Mixin(MinecraftServer.class) -public abstract class MinecraftServer_scarpetMixin extends ReentrantThreadExecutor implements MinecraftServerInterface +public abstract class MinecraftServer_scarpetMixin extends ReentrantBlockableEventLoop implements MinecraftServerInterface { public MinecraftServer_scarpetMixin(String string_1) { super(string_1); } - @Shadow protected abstract void tick(BooleanSupplier booleanSupplier_1); + @Shadow protected abstract void tickServer(BooleanSupplier booleanSupplier_1); - @Shadow private long timeReference; + @Shadow private long nextTickTime; - @Shadow private long lastTimeReference; + @Shadow private long lastOverloadWarning; - @Shadow public abstract boolean runTask(); + @Shadow public abstract boolean pollTask(); - @Shadow @Final protected LevelStorage.Session session; + @Shadow @Final protected LevelStorageSource.LevelStorageAccess storageSource; - @Shadow @Final private Map, ServerWorld> worlds; + @Shadow @Final private Map, ServerLevel> levels; - @Shadow private ServerResourceManager serverResourceManager; + @Shadow private ServerResources resources; @Override public void forceTick(BooleanSupplier isAhead) { - timeReference = lastTimeReference = Util.getMeasuringTimeMs(); - tick(isAhead); - while(runTask()) {Thread.yield();} + nextTickTime = lastOverloadWarning = Util.getMillis(); + tickServer(isAhead); + while(pollTask()) {Thread.yield();} } @Override - public LevelStorage.Session getCMSession() + public LevelStorageSource.LevelStorageAccess getCMSession() { - return session; + return storageSource; } @Override - public ServerResourceManager getResourceManager() { - return serverResourceManager; + public ServerResources getResourceManager() { + return resources; } @Override - public Map, ServerWorld> getCMWorlds() + public Map, ServerLevel> getCMWorlds() { - return worlds; + return levels; } - @Inject(method = "tick", at = @At( + @Inject(method = "tickServer", at = @At( value = "CONSTANT", args = "stringValue=tallying" )) diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index 84fb6cc4..cebe1ba1 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -3,14 +3,14 @@ package carpet.mixins; import carpet.helpers.TickSpeed; import carpet.patches.CopyProfilerResult; import carpet.utils.CarpetProfiler; +import net.minecraft.Util; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerTask; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Util; -import net.minecraft.util.profiler.EmptyProfileResult; -import net.minecraft.util.profiler.ProfileResult; -import net.minecraft.util.profiler.Profiler; -import net.minecraft.util.thread.ReentrantThreadExecutor; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.profiling.EmptyProfileResults; +import net.minecraft.util.profiling.ProfileResults; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.util.thread.ReentrantBlockableEventLoop; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.spongepowered.asm.mixin.Final; @@ -25,44 +25,44 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.function.BooleanSupplier; @Mixin(MinecraftServer.class) -public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExecutor +public abstract class MinecraftServer_tickspeedMixin extends ReentrantBlockableEventLoop { @Shadow private volatile boolean running; - @Shadow private long timeReference; + @Shadow private long nextTickTime; @Shadow @Final private static Logger LOGGER; - @Shadow private Profiler profiler; + @Shadow private ProfilerFiller profiler; public MinecraftServer_tickspeedMixin(String name) { super(name); } - @Shadow protected abstract void tick(BooleanSupplier booleanSupplier_1); + @Shadow protected abstract void tickServer(BooleanSupplier booleanSupplier_1); - @Shadow protected abstract boolean shouldKeepTicking(); + @Shadow protected abstract boolean haveTime(); - @Shadow private long nextTickTimestamp; + @Shadow private long delayedTasksMaxNextTickTime; - @Shadow private volatile boolean loading; + @Shadow private volatile boolean isReady; - @Shadow private long lastTimeReference; + @Shadow private long lastOverloadWarning; - @Shadow private boolean waitingForNextTick; + @Shadow private boolean mayHaveDelayedTasks; - @Shadow public abstract Iterable getWorlds(); + @Shadow public abstract Iterable getAllLevels(); - @Shadow private int ticks; + @Shadow private int tickCount; - @Shadow protected abstract void runTasksTillTickEnd(); + @Shadow protected abstract void waitUntilNextTick(); - @Shadow protected abstract void startTickMetrics(); + @Shadow protected abstract void startMetricsRecordingTick(); - @Shadow protected abstract void endTickMetrics(); + @Shadow protected abstract void endMetricsRecordingTick(); - @Shadow private boolean needsDebugSetup; + @Shadow private boolean debugCommandProfilerDelayStart; CarpetProfiler.ProfilerToken currentSection; private float carpetMsptAccum = 0.0f; @@ -82,7 +82,7 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec // could possibly just inject that mspt selection at the beginning of the loop, but then adding all mspt's to // replace 50L will be a hassle @Inject(method = "runServer", at = @At(value = "INVOKE", shift = At.Shift.AFTER, - target = "Lnet/minecraft/server/MinecraftServer;setFavicon(Lnet/minecraft/server/ServerMetadata;)V")) + target = "Lnet/minecraft/server/MinecraftServer;updateStatusIcon(Lnet/minecraft/network/protocol/status/ServerStatus;)V")) private void modifiedRunLoop(CallbackInfo ci) { while (this.running) @@ -98,7 +98,7 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec if (TickSpeed.time_warp_start_time != 0 && TickSpeed.continueWarp()) { //making sure server won't flop after the warp or if the warp is interrupted - this.timeReference = this.lastTimeReference = Util.getMeasuringTimeMs(); + this.nextTickTime = this.lastOverloadWarning = Util.getMillis(); carpetMsptAccum = TickSpeed.mspt; } else @@ -112,41 +112,41 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec msThisTick = (long)carpetMsptAccum; // regular tick carpetMsptAccum += TickSpeed.mspt - msThisTick; - long_1 = Util.getMeasuringTimeMs() - this.timeReference; + long_1 = Util.getMillis() - this.nextTickTime; } //end tick deciding //smoothed out delay to include mcpt component. With 50L gives defaults. - if (long_1 > /*2000L*/1000L+20*TickSpeed.mspt && this.timeReference - this.lastTimeReference >= /*15000L*/10000L+100*TickSpeed.mspt) + if (long_1 > /*2000L*/1000L+20*TickSpeed.mspt && this.nextTickTime - this.lastOverloadWarning >= /*15000L*/10000L+100*TickSpeed.mspt) { long long_2 = (long)(long_1 / TickSpeed.mspt);//50L; LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", long_1, long_2); - this.timeReference += (long)(long_2 * TickSpeed.mspt);//50L; - this.lastTimeReference = this.timeReference; + this.nextTickTime += (long)(long_2 * TickSpeed.mspt);//50L; + this.lastOverloadWarning = this.nextTickTime; } - if (this.needsDebugSetup) { - this.needsDebugSetup = false; - this.profilerTimings = Pair.of(Util.getMeasuringTimeNano(), ticks); + if (this.debugCommandProfilerDelayStart) { + this.debugCommandProfilerDelayStart = false; + this.profilerTimings = Pair.of(Util.getNanos(), tickCount); //this.field_33978 = new MinecraftServer.class_6414(Util.getMeasuringTimeNano(), this.ticks); } - this.timeReference += msThisTick;//50L; + this.nextTickTime += msThisTick;//50L; //TickDurationMonitor tickDurationMonitor = TickDurationMonitor.create("Server"); //this.startMonitor(tickDurationMonitor); - this.startTickMetrics(); + this.startMetricsRecordingTick(); this.profiler.push("tick"); - this.tick(TickSpeed.time_warp_start_time != 0 ? ()->true : this::shouldKeepTicking); - this.profiler.swap("nextTickWait"); + this.tickServer(TickSpeed.time_warp_start_time != 0 ? ()->true : this::haveTime); + this.profiler.popPush("nextTickWait"); if (TickSpeed.time_warp_start_time != 0) // clearing all hanging tasks no matter what when warping { while(this.runEveryTask()) {Thread.yield();} } - this.waitingForNextTick = true; - this.nextTickTimestamp = Math.max(Util.getMeasuringTimeMs() + /*50L*/ msThisTick, this.timeReference); + this.mayHaveDelayedTasks = true; + this.delayedTasksMaxNextTickTime = Math.max(Util.getMillis() + /*50L*/ msThisTick, this.nextTickTime); // run all tasks (this will not do a lot when warping), but that's fine since we already run them - this.runTasksTillTickEnd(); + this.waitUntilNextTick(); this.profiler.pop(); - this.endTickMetrics(); - this.loading = true; + this.endMetricsRecordingTick(); + this.isReady = true; } } @@ -154,20 +154,20 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec // just because profilerTimings class is public Pair profilerTimings = null; /// overworld around profiler timings - @Inject(method = "isDebugRunning", at = @At("HEAD"), cancellable = true) + @Inject(method = "isTimeProfilerRunning", at = @At("HEAD"), cancellable = true) public void isCMDebugRunning(CallbackInfoReturnable cir) { - cir.setReturnValue(needsDebugSetup || profilerTimings != null); + cir.setReturnValue(debugCommandProfilerDelayStart || profilerTimings != null); } - @Inject(method = "stopDebug", at = @At("HEAD"), cancellable = true) - public void stopCMDebug(CallbackInfoReturnable cir) + @Inject(method = "stopTimeProfiler", at = @At("HEAD"), cancellable = true) + public void stopCMDebug(CallbackInfoReturnable cir) { if (this.profilerTimings == null) { - cir.setReturnValue(EmptyProfileResult.INSTANCE); + cir.setReturnValue(EmptyProfileResults.EMPTY); } else { - ProfileResult profileResult = new CopyProfilerResult( + ProfileResults profileResult = new CopyProfilerResult( profilerTimings.getRight(), profilerTimings.getLeft(), - this.ticks, Util.getMeasuringTimeNano() + this.tickCount, Util.getNanos() ); this.profilerTimings = null; cir.setReturnValue(profileResult); @@ -176,12 +176,12 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec private boolean runEveryTask() { - if (super.runTask()) { + if (super.pollTask()) { return true; } else { if (true) { // unconditionally this time - for(ServerWorld serverlevel : getWorlds()) { - if (serverlevel.getChunkManager().executeQueuedTasks()) { + for(ServerLevel serverlevel : getAllLevels()) { + if (serverlevel.getChunkSource().pollTask()) { return true; } } @@ -191,9 +191,9 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec } } - @Inject(method = "tick", at = @At( + @Inject(method = "tickServer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/MinecraftServer;saveAll(ZZZ)Z", // save + target = "Lnet/minecraft/server/MinecraftServer;saveEverything(ZZZ)Z", // save shift = At.Shift.BEFORE )) private void startAutosave(BooleanSupplier booleanSupplier_1, CallbackInfo ci) @@ -201,9 +201,9 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec currentSection = CarpetProfiler.start_section(null, "Autosave", CarpetProfiler.TYPE.GENERAL); } - @Inject(method = "tick", at = @At( + @Inject(method = "tickServer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/MinecraftServer;saveAll(ZZZ)Z", + target = "Lnet/minecraft/server/MinecraftServer;saveEverything(ZZZ)Z", shift = At.Shift.AFTER )) private void finishAutosave(BooleanSupplier booleanSupplier_1, CallbackInfo ci) @@ -211,9 +211,9 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec CarpetProfiler.end_current_section(currentSection); } - @Inject(method = "tickWorlds", at = @At( + @Inject(method = "tickChildren", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/MinecraftServer;getNetworkIo()Lnet/minecraft/server/ServerNetworkIo;", + target = "Lnet/minecraft/server/MinecraftServer;getConnection()Lnet/minecraft/server/network/ServerConnectionListener;", shift = At.Shift.BEFORE )) private void startNetwork(BooleanSupplier booleanSupplier_1, CallbackInfo ci) @@ -221,9 +221,9 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec currentSection = CarpetProfiler.start_section(null, "Network", CarpetProfiler.TYPE.GENERAL); } - @Inject(method = "tickWorlds", at = @At( + @Inject(method = "tickChildren", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/PlayerManager;updatePlayerLatency()V", + target = "Lnet/minecraft/server/players/PlayerList;tick()V", shift = At.Shift.AFTER )) private void finishNetwork(BooleanSupplier booleanSupplier_1, CallbackInfo ci) @@ -231,14 +231,14 @@ public abstract class MinecraftServer_tickspeedMixin extends ReentrantThreadExec CarpetProfiler.end_current_section(currentSection); } - @Inject(method = "runTasksTillTickEnd", at = @At("HEAD")) + @Inject(method = "waitUntilNextTick", at = @At("HEAD")) private void startAsync(CallbackInfo ci) { currentSection = CarpetProfiler.start_section(null, "Async Tasks", CarpetProfiler.TYPE.GENERAL); } - @Inject(method = "runTasksTillTickEnd", at = @At( + @Inject(method = "waitUntilNextTick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/MinecraftServer;runTasks(Ljava/util/function/BooleanSupplier;)V", + target = "Lnet/minecraft/server/MinecraftServer;managedBlock(Ljava/util/function/BooleanSupplier;)V", shift = At.Shift.BEFORE )) private void stopAsync(CallbackInfo ci) diff --git a/src/main/java/carpet/mixins/MinecraftServer_updateSuppressionCrashFixMixin.java b/src/main/java/carpet/mixins/MinecraftServer_updateSuppressionCrashFixMixin.java index 67d42b8e..e4c03283 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_updateSuppressionCrashFixMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_updateSuppressionCrashFixMixin.java @@ -4,11 +4,11 @@ import carpet.CarpetSettings; import carpet.helpers.ThrowableSuppression; import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; +import net.minecraft.ReportedException; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.BaseText; -import net.minecraft.util.crash.CrashException; -import net.minecraft.util.math.BlockPos; +import net.minecraft.server.level.ServerLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -19,21 +19,21 @@ import java.util.function.BooleanSupplier; public class MinecraftServer_updateSuppressionCrashFixMixin { @Redirect( - method = "tickWorlds", + method = "tickChildren", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;tick(Ljava/util/function/BooleanSupplier;)V" + target = "Lnet/minecraft/server/level/ServerLevel;tick(Ljava/util/function/BooleanSupplier;)V" ), require = 0 ) - private void fixUpdateSuppressionCrashTick(ServerWorld serverWorld, BooleanSupplier shouldKeepTicking){ + private void fixUpdateSuppressionCrashTick(ServerLevel serverWorld, BooleanSupplier shouldKeepTicking){ if (!CarpetSettings.updateSuppressionCrashFix) { serverWorld.tick(shouldKeepTicking); return; } try { serverWorld.tick(shouldKeepTicking); - } catch (CrashException e) { + } catch (ReportedException e) { if (!(e.getCause() instanceof ThrowableSuppression throwableSuppression)) throw e; logUpdateSuppression(throwableSuppression.pos); } catch (ThrowableSuppression e) { @@ -45,7 +45,7 @@ public class MinecraftServer_updateSuppressionCrashFixMixin { private void logUpdateSuppression(BlockPos pos) { if(LoggerRegistry.__updateSuppressedCrashes) { LoggerRegistry.getLogger("updateSuppressedCrashes").log(() -> { - return new BaseText[]{Messenger.c( + return new BaseComponent[]{Messenger.c( "w Server crash prevented in: ", "m world tick ", "w - at: ", diff --git a/src/main/java/carpet/mixins/MobEntityMixin.java b/src/main/java/carpet/mixins/MobEntityMixin.java index 2d8a5fff..c58f3606 100644 --- a/src/main/java/carpet/mixins/MobEntityMixin.java +++ b/src/main/java/carpet/mixins/MobEntityMixin.java @@ -1,22 +1,22 @@ package carpet.mixins; import carpet.fakes.MobEntityInterface; -import net.minecraft.entity.ai.goal.Goal; -import net.minecraft.entity.ai.goal.GoalSelector; -import net.minecraft.entity.mob.MobEntity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.HashMap; import java.util.Map; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; -@Mixin(MobEntity.class) +@Mixin(Mob.class) public abstract class MobEntityMixin implements MobEntityInterface { @Shadow @Final protected GoalSelector targetSelector; @Shadow @Final protected GoalSelector goalSelector; - @Shadow private boolean persistent; + @Shadow private boolean persistenceRequired; public final Map temporaryTasks = new HashMap<>(); @Override @@ -34,6 +34,6 @@ public abstract class MobEntityMixin implements MobEntityInterface @Override public void setPersistence(boolean what) { - persistent = what; + persistenceRequired = what; } } diff --git a/src/main/java/carpet/mixins/MobEntity_extremeMixin.java b/src/main/java/carpet/mixins/MobEntity_extremeMixin.java index 9c528136..f9e42b80 100644 --- a/src/main/java/carpet/mixins/MobEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/MobEntity_extremeMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.mob.MobEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.Mob; -@Mixin(MobEntity.class) +@Mixin(Mob.class) public class MobEntity_extremeMixin { - @Redirect(method = "initialize", expect = 1, at = @At( + @Redirect(method = "finalizeSpawn", expect = 1, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java b/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java index ead8ed9c..c34677d0 100644 --- a/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java +++ b/src/main/java/carpet/mixins/NoiseChunkGenerator_husksSpawnMixin.java @@ -2,42 +2,41 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.CustomSpawnLists; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.util.collection.Pool; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.gen.StructureAccessor; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.chunk.NoiseChunkGenerator; -import net.minecraft.world.gen.chunk.StructuresConfig; -//import net.minecraft.world.gen.feature.Feature; -import net.minecraft.world.gen.feature.StructureFeature; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.util.random.WeightedRandomList; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.StructureFeatureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.StructureSettings; +import net.minecraft.world.level.levelgen.feature.StructureFeature; -@Mixin(NoiseChunkGenerator.class) +@Mixin(NoiseBasedChunkGenerator.class) // todo rename mixin after 1.15 is gone public abstract class NoiseChunkGenerator_husksSpawnMixin extends ChunkGenerator { - public NoiseChunkGenerator_husksSpawnMixin(BiomeSource biomeSource, StructuresConfig structuresConfig) + public NoiseChunkGenerator_husksSpawnMixin(BiomeSource biomeSource, StructureSettings structuresConfig) { super(biomeSource, structuresConfig); } - @Inject(method = "getEntitySpawnList", at = @At("HEAD"), cancellable = true) - private void isInsidePyramid(Biome biome, StructureAccessor accessor, SpawnGroup group, BlockPos pos, CallbackInfoReturnable> cir) + @Inject(method = "getMobsAt", at = @At("HEAD"), cancellable = true) + private void isInsidePyramid(Biome biome, StructureFeatureManager accessor, MobCategory group, BlockPos pos, CallbackInfoReturnable> cir) { - if (group == SpawnGroup.MONSTER) + if (group == MobCategory.MONSTER) { if (CarpetSettings.huskSpawningInTemples) { - if (accessor.getStructureAt(pos, StructureFeature.DESERT_PYRAMID).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.DESERT_PYRAMID).isValid()) { cir.setReturnValue(CustomSpawnLists.PYRAMID_SPAWNS); return; @@ -45,7 +44,7 @@ public abstract class NoiseChunkGenerator_husksSpawnMixin extends ChunkGenerator } if (CarpetSettings.shulkerSpawningInEndCities) { - if (accessor.getStructureAt(pos, StructureFeature.END_CITY).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.END_CITY).isValid()) { cir.setReturnValue(CustomSpawnLists.SHULKER_SPAWNS); return; @@ -53,7 +52,7 @@ public abstract class NoiseChunkGenerator_husksSpawnMixin extends ChunkGenerator } if (CarpetSettings.piglinsSpawningInBastions) { - if (accessor.getStructureAt(pos, StructureFeature.BASTION_REMNANT).hasChildren()) + if (accessor.getStructureAt(pos, StructureFeature.BASTION_REMNANT).isValid()) { cir.setReturnValue(CustomSpawnLists.BASTION_SPAWNS); } diff --git a/src/main/java/carpet/mixins/NoiseColumnSamplerMixin_scarpetMixin.java b/src/main/java/carpet/mixins/NoiseColumnSamplerMixin_scarpetMixin.java index 53697d8c..46488650 100644 --- a/src/main/java/carpet/mixins/NoiseColumnSamplerMixin_scarpetMixin.java +++ b/src/main/java/carpet/mixins/NoiseColumnSamplerMixin_scarpetMixin.java @@ -2,247 +2,247 @@ package carpet.mixins; import carpet.fakes.NoiseColumnSamplerInterface; import carpet.script.exception.InternalExpressionException; -import net.minecraft.util.math.noise.DoublePerlinNoiseSampler; -import net.minecraft.util.math.noise.InterpolatedNoiseSampler; -import net.minecraft.util.math.noise.SimplexNoiseSampler; -import net.minecraft.world.biome.source.BiomeCoords; -import net.minecraft.world.biome.source.util.MultiNoiseUtil; -import net.minecraft.world.biome.source.util.TerrainNoisePoint; -import net.minecraft.world.gen.NoiseColumnSampler; -import net.minecraft.world.gen.NoiseHelper; -import net.minecraft.world.gen.chunk.Blender; -import net.minecraft.world.gen.chunk.GenerationShapeConfig; +import net.minecraft.core.QuartPos; +import net.minecraft.world.level.biome.Climate; +import net.minecraft.world.level.levelgen.NoiseSampler; +import net.minecraft.world.level.levelgen.NoiseSettings; +import net.minecraft.world.level.levelgen.TerrainInfo; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.synth.BlendedNoise; +import net.minecraft.world.level.levelgen.synth.NoiseUtils; +import net.minecraft.world.level.levelgen.synth.NormalNoise; +import net.minecraft.world.level.levelgen.synth.SimplexNoise; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(NoiseColumnSampler.class) +@Mixin(NoiseSampler.class) public abstract class NoiseColumnSamplerMixin_scarpetMixin implements NoiseColumnSamplerInterface { @Shadow @Final - private InterpolatedNoiseSampler terrainNoise; + private BlendedNoise blendedNoise; @Shadow @Final @Nullable - private SimplexNoiseSampler islandNoise; + private SimplexNoise islandNoise; @Shadow @Final - private DoublePerlinNoiseSampler aquiferBarrierNoise; + private NormalNoise barrierNoise; @Shadow @Final - private DoublePerlinNoiseSampler aquiferFluidLevelFloodednessNoise; + private NormalNoise fluidLevelFloodednessNoise; @Shadow @Final - private DoublePerlinNoiseSampler aquiferFluidLevelSpreadNoise; + private NormalNoise fluidLevelSpreadNoise; @Shadow @Final - private DoublePerlinNoiseSampler aquiferLavaNoise; + private NormalNoise lavaNoise; @Shadow @Final - private DoublePerlinNoiseSampler pillarRarenessNoise; + private NormalNoise pillarRarenessModulator; @Shadow @Final - private DoublePerlinNoiseSampler pillarThicknessNoise; + private NormalNoise pillarThicknessModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti2dElevationNoise; + private NormalNoise spaghetti2DElevationModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti2dModulatorNoise; + private NormalNoise spaghetti2DRarityModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti2dThicknessNoise; + private NormalNoise spaghetti2DThicknessModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti3dFirstNoise; + private NormalNoise spaghetti3DNoiseSource1; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti3dSecondNoise; + private NormalNoise spaghetti3DNoiseSource2; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti3dRarityNoise; + private NormalNoise spaghetti3DRarityModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghetti3dThicknessNoise; + private NormalNoise spaghetti3DThicknessModulator; @Shadow @Final - private DoublePerlinNoiseSampler spaghettiRoughnessModulatorNoise; + private NormalNoise spaghettiRoughnessModulator; @Shadow @Final - private DoublePerlinNoiseSampler caveCheeseNoise; + private NormalNoise cheeseNoiseSource; @Shadow @Final - private DoublePerlinNoiseSampler oreGapNoise; + private NormalNoise gapNoise; @Shadow @Final - private GenerationShapeConfig config; + private NoiseSettings noiseSettings; @Shadow - protected abstract double method_38409(double d, double e, double f); + protected abstract double sampleJaggedNoise(double d, double e, double f); @Shadow - protected abstract double sampleCaveLayerNoise(int x, int y, int z); + protected abstract double getLayerizedCaverns(int x, int y, int z); @Shadow - protected abstract double samplePillarNoise(int x, int y, int z); + protected abstract double getPillars(int x, int y, int z); @Shadow - protected abstract double sampleSpaghetti2dNoise(int x, int y, int z); + protected abstract double getSpaghetti2D(int x, int y, int z); @Shadow - protected abstract double sampleSpaghetti3dNoise(int x, int y, int z); + protected abstract double getSpaghetti3D(int x, int y, int z); @Shadow - protected abstract double sampleSpaghettiRoughnessNoise(int x, int y, int z); + protected abstract double spaghettiRoughness(int x, int y, int z); @Shadow - protected abstract double sampleCaveEntranceNoise(int x, int y, int z); + protected abstract double getBigEntrances(int x, int y, int z); @Shadow - public abstract double sampleShiftNoise(int x, int y, int z); + public abstract double getOffset(int x, int y, int z); @Shadow - private static double sample(DoublePerlinNoiseSampler sampler, double x, double y, double z, double invertedScale) { + private static double sampleWithRarity(NormalNoise sampler, double x, double y, double z, double invertedScale) { throw new AssertionError(); } @Shadow - public abstract MultiNoiseUtil.NoiseValuePoint sample(int i, int j, int k); + public abstract Climate.TargetPoint sample(int i, int j, int k); @Shadow - public abstract TerrainNoisePoint createTerrainNoisePoint(int x, int z, float continentalness, float weirdness, float erosion, Blender blender); + public abstract TerrainInfo terrainInfo(int x, int z, float continentalness, float weirdness, float erosion, Blender blender); @Override public double getNoiseSample(String name, int x, int y, int z) { - MultiNoiseUtil.NoiseValuePoint noiseValuePoint = this.sample(x, y, z); - TerrainNoisePoint terrainNoisePoint = createTerrainNoisePoint( + Climate.TargetPoint noiseValuePoint = this.sample(x, y, z); + TerrainInfo terrainNoisePoint = terrainInfo( x, z, - MultiNoiseUtil.method_38666(noiseValuePoint.continentalnessNoise()), - MultiNoiseUtil.method_38666(noiseValuePoint.weirdnessNoise()), - MultiNoiseUtil.method_38666(noiseValuePoint.erosionNoise()), - Blender.getNoBlending() + Climate.unquantizeCoord(noiseValuePoint.continentalness()), + Climate.unquantizeCoord(noiseValuePoint.weirdness()), + Climate.unquantizeCoord(noiseValuePoint.erosion()), + Blender.empty() ); switch (name) { case "temperature" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.temperatureNoise()); + return Climate.unquantizeCoord(noiseValuePoint.temperature()); } case "humidity" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.humidityNoise()); + return Climate.unquantizeCoord(noiseValuePoint.humidity()); } case "continentalness" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.continentalnessNoise()); + return Climate.unquantizeCoord(noiseValuePoint.continentalness()); } case "erosion" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.erosionNoise()); + return Climate.unquantizeCoord(noiseValuePoint.erosion()); } case "weirdness" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.weirdnessNoise()); + return Climate.unquantizeCoord(noiseValuePoint.weirdness()); } case "depth" -> { - return MultiNoiseUtil.method_38666(noiseValuePoint.depth()); + return Climate.unquantizeCoord(noiseValuePoint.depth()); } case "shiftX" -> { - return x + this.sampleShiftNoise(x, 0, z); + return x + this.getOffset(x, 0, z); } case "shiftY" -> { - return y + this.sampleShiftNoise(y, z, x); + return y + this.getOffset(y, z, x); } case "shiftZ" -> { - return z + this.sampleShiftNoise(z, x, 0); + return z + this.getOffset(z, x, 0); } case "terrain" -> { - return this.terrainNoise.calculateNoise(x, y, z); + return this.blendedNoise.calculateNoise(x, y, z); } case "island" -> { - return this.islandNoise == null ? 0 : this.islandNoise.sample(x, y, z); + return this.islandNoise == null ? 0 : this.islandNoise.getValue(x, y, z); } case "jagged" -> { - return this.method_38409(terrainNoisePoint.peaks(), x, z); + return this.sampleJaggedNoise(terrainNoisePoint.jaggedness(), x, z); } case "aquiferBarrier" -> { - return this.aquiferBarrierNoise.sample(x, y, z); + return this.barrierNoise.getValue(x, y, z); } case "aquiferFluidLevelFloodedness" -> { - return this.aquiferFluidLevelFloodednessNoise.sample(x, y, z); + return this.fluidLevelFloodednessNoise.getValue(x, y, z); } case "aquiferFluidLevelSpread" -> { - return this.aquiferFluidLevelSpreadNoise.sample(x, y, z); + return this.fluidLevelSpreadNoise.getValue(x, y, z); } case "aquiferLava" -> { - return this.aquiferLavaNoise.sample(x, y, z); + return this.lavaNoise.getValue(x, y, z); } case "pillar" -> { - return this.samplePillarNoise(x, y, z); + return this.getPillars(x, y, z); } case "pillarRareness" -> { - return NoiseHelper.lerpFromProgress(this.pillarRarenessNoise, x, y, z, 0.0D, 2.0D); + return NoiseUtils.sampleNoiseAndMapToRange(this.pillarRarenessModulator, x, y, z, 0.0D, 2.0D); } case "pillarThickness" -> { - return NoiseHelper.lerpFromProgress(this.pillarThicknessNoise, x, y, z, 0.0D, 1.1D); + return NoiseUtils.sampleNoiseAndMapToRange(this.pillarThicknessModulator, x, y, z, 0.0D, 1.1D); } case "spaghetti2d" -> { - return this.sampleSpaghetti2dNoise(x, y, z); + return this.getSpaghetti2D(x, y, z); } case "spaghetti2dElevation" -> { - return NoiseHelper.lerpFromProgress(this.spaghetti2dElevationNoise, x, 0.0, z, this.config.minimumBlockY(), 8.0); + return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti2DElevationModulator, x, 0.0, z, this.noiseSettings.getMinCellY(), 8.0); } case "spaghetti2dModulator" -> { - return this.spaghetti2dModulatorNoise.sample(x * 2, y, z * 2); + return this.spaghetti2DRarityModulator.getValue(x * 2, y, z * 2); } case "spaghetti2dThickness" -> { - return NoiseHelper.lerpFromProgress(this.spaghetti2dThicknessNoise, x * 2, y, z * 2, 0.6, 1.3); + return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti2DThicknessModulator, x * 2, y, z * 2, 0.6, 1.3); } case "spaghetti3d" -> { - return this.sampleSpaghetti3dNoise(x, y, z); + return this.getSpaghetti3D(x, y, z); } case "spaghetti3dFirst" -> { - double d = this.spaghetti3dRarityNoise.sample(x * 2, y, z * 2); - double e = CaveScalerMixin_scarpetMixin.invokeScaleTunnels(d); - return sample(this.spaghetti3dFirstNoise, x, y, z, e); + double d = this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); + double e = CaveScalerMixin_scarpetMixin.invokeGetSpaghettiRarity3D(d); + return sampleWithRarity(this.spaghetti3DNoiseSource1, x, y, z, e); } case "spaghetti3dSecond" -> { - double d = this.spaghetti3dRarityNoise.sample(x * 2, y, z * 2); - double e = CaveScalerMixin_scarpetMixin.invokeScaleTunnels(d); - return sample(this.spaghetti3dSecondNoise, x, y, z, e); + double d = this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); + double e = CaveScalerMixin_scarpetMixin.invokeGetSpaghettiRarity3D(d); + return sampleWithRarity(this.spaghetti3DNoiseSource2, x, y, z, e); } case "spaghetti3dRarity" -> { - return this.spaghetti3dRarityNoise.sample(x * 2, y, z * 2); + return this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); } case "spaghetti3dThickness" -> { - return NoiseHelper.lerpFromProgress(this.spaghetti3dThicknessNoise, x, y, z, 0.065, 0.088); + return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti3DThicknessModulator, x, y, z, 0.065, 0.088); } case "spaghettiRoughness" -> { - return this.sampleSpaghettiRoughnessNoise(x, y, z); + return this.spaghettiRoughness(x, y, z); } case "spaghettiRoughnessModulator" -> { - return NoiseHelper.lerpFromProgress(this.spaghettiRoughnessModulatorNoise, x, y, z, 0.0, 0.1); + return NoiseUtils.sampleNoiseAndMapToRange(this.spaghettiRoughnessModulator, x, y, z, 0.0, 0.1); } case "caveEntrance" -> { - return this.sampleCaveEntranceNoise( - BiomeCoords.toBlock(x), - BiomeCoords.toBlock(y), - BiomeCoords.toBlock(z) + return this.getBigEntrances( + QuartPos.toBlock(x), + QuartPos.toBlock(y), + QuartPos.toBlock(z) ); } case "caveLayer" -> { // scaling them by 4 because it's sampled in normal coords - return this.sampleCaveLayerNoise( - BiomeCoords.toBlock(x), - BiomeCoords.toBlock(y), - BiomeCoords.toBlock(z) + return this.getLayerizedCaverns( + QuartPos.toBlock(x), + QuartPos.toBlock(y), + QuartPos.toBlock(z) ); } case "caveCheese" -> { // same reason as above - return this.caveCheeseNoise.sample( - BiomeCoords.toBlock(x), - BiomeCoords.toBlock(y) / 1.5, - BiomeCoords.toBlock(z) + return this.cheeseNoiseSource.getValue( + QuartPos.toBlock(x), + QuartPos.toBlock(y) / 1.5, + QuartPos.toBlock(z) ); } case "terrainPeaks" -> { - return terrainNoisePoint.peaks(); + return terrainNoisePoint.jaggedness(); } case "terrainOffset" -> { return terrainNoisePoint.offset(); @@ -251,7 +251,7 @@ public abstract class NoiseColumnSamplerMixin_scarpetMixin implements NoiseColum return terrainNoisePoint.factor(); } case "oreGap" -> { - return this.oreGapNoise.sample(x, y, z); + return this.gapNoise.getValue(x, y, z); } } throw new InternalExpressionException("Unknown noise type: " + name); diff --git a/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java b/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java index 014e1d32..ce8ba9a8 100644 --- a/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java +++ b/src/main/java/carpet/mixins/PerfCommand_permissionMixin.java @@ -1,8 +1,8 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.dedicated.command.PerfCommand; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.server.commands.PerfCommand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -12,10 +12,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; public class PerfCommand_permissionMixin { @SuppressWarnings("UnresolvedMixinReference") - @Inject(method = "method_37340(Lnet/minecraft/server/command/ServerCommandSource;)Z", at = @At("HEAD"), cancellable = true) - private static void canRun(ServerCommandSource source, CallbackInfoReturnable cir) + @Inject(method = "lambda$register$0(Lnet/minecraft/commands/CommandSourceStack;)Z", at = @At("HEAD"), cancellable = true) + private static void canRun(CommandSourceStack source, CallbackInfoReturnable cir) { - cir.setReturnValue(source.hasPermissionLevel(CarpetSettings.perfPermissionLevel)); + cir.setReturnValue(source.hasPermission(CarpetSettings.perfPermissionLevel)); } } diff --git a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java index ed77613f..d881b612 100644 --- a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java +++ b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java @@ -1,31 +1,31 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.item.ItemStack; -import net.minecraft.item.MiningToolItem; -import net.minecraft.item.PickaxeItem; -import net.minecraft.item.ToolMaterial; -import net.minecraft.tag.Tag; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.DiggerItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.PickaxeItem; +import net.minecraft.world.item.Tier; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; import org.spongepowered.asm.mixin.Mixin; //import org.spongepowered.asm.mixin.injection.At; //import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(PickaxeItem.class) -public class PickaxeItem_missingToolsMixin extends MiningToolItem +public class PickaxeItem_missingToolsMixin extends DiggerItem { - protected PickaxeItem_missingToolsMixin(float attackDamage, float attackSpeed, ToolMaterial material, Tag tag, Settings settings) { + protected PickaxeItem_missingToolsMixin(float attackDamage, float attackSpeed, Tier material, Tag tag, Properties settings) { super(attackDamage, attackSpeed, material, tag, settings); } @Override - public float getMiningSpeedMultiplier(ItemStack stack, BlockState state) { + public float getDestroySpeed(ItemStack stack, BlockState state) { Material material = state.getMaterial(); if (CarpetSettings.missingTools && material == Material.GLASS) - return miningSpeed; - return super.getMiningSpeedMultiplier(stack, state); + return speed; + return super.getDestroySpeed(stack, state); } } diff --git a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableBEMixin.java similarity index 54% rename from src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java rename to src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableBEMixin.java index 801e9693..c7a36cd1 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableBEMixin.java @@ -2,33 +2,33 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.PistonBlockEntityInterface; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.PistonBlockEntity; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher; -import net.minecraft.client.render.block.entity.BlockEntityRenderer; -import net.minecraft.client.render.block.entity.BlockEntityRendererFactory; -import net.minecraft.client.render.block.entity.PistonBlockEntityRenderer; -import net.minecraft.client.util.math.MatrixStack; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; +import net.minecraft.client.renderer.blockentity.PistonHeadRenderer; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; -@Mixin(PistonBlockEntityRenderer.class) -public abstract class PistonBlockEntityRenderer_movableTEMixin implements BlockEntityRenderer +@Mixin(PistonHeadRenderer.class) +public abstract class PistonBlockEntityRenderer_movableBEMixin implements BlockEntityRenderer { BlockEntityRenderDispatcher dispatcher; @Inject(method = "", at = @At("TAIL")) - private void onInitCM(BlockEntityRendererFactory.Context arguments, CallbackInfo ci) + private void onInitCM(BlockEntityRendererProvider.Context arguments, CallbackInfo ci) { - dispatcher = arguments.getRenderDispatcher(); + dispatcher = arguments.getBlockEntityRenderDispatcher(); } @Inject(method = "render", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/render/block/entity/PistonBlockEntityRenderer;renderModel(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/world/World;ZI)V", ordinal = 3)) - private void updateRenderBool(PistonBlockEntity pistonBlockEntity_1, float float_1, MatrixStack matrixStack_1, VertexConsumerProvider layeredVertexConsumerStorage_1, int int_1, int int_2, CallbackInfo ci) + target = "Lnet/minecraft/client/renderer/blockentity/PistonHeadRenderer;renderBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/level/Level;ZI)V", ordinal = 3)) + private void updateRenderBool(PistonMovingBlockEntity pistonBlockEntity_1, float float_1, PoseStack matrixStack_1, MultiBufferSource layeredVertexConsumerStorage_1, int int_1, int int_2, CallbackInfo ci) //private void updateRenderBool(PistonBlockEntity pistonBlockEntity_1, double double_1, double double_2, double double_3, float float_1, class_4587 class_4587_1, class_4597 class_4597_1, int int_1, CallbackInfo ci) { if (!((PistonBlockEntityInterface) pistonBlockEntity_1).isRenderModeSet()) @@ -37,7 +37,7 @@ public abstract class PistonBlockEntityRenderer_movableTEMixin implements BlockE @Inject(method = "render", at = @At("RETURN"), locals = LocalCapture.NO_CAPTURE) - private void endMethod3576(PistonBlockEntity pistonBlockEntity_1, float partialTicks, MatrixStack matrixStack_1, VertexConsumerProvider layeredVertexConsumerStorage_1, int int_1, int init_2, CallbackInfo ci) + private void endMethod3576(PistonMovingBlockEntity pistonBlockEntity_1, float partialTicks, PoseStack matrixStack_1, MultiBufferSource layeredVertexConsumerStorage_1, int int_1, int init_2, CallbackInfo ci) { if (((PistonBlockEntityInterface) pistonBlockEntity_1).getRenderCarriedBlockEntity()) { @@ -47,9 +47,9 @@ public abstract class PistonBlockEntityRenderer_movableTEMixin implements BlockE // maybe ??? carriedBlockEntity.setPos(pistonBlockEntity_1.getPos()); //((BlockEntityRenderDispatcherInterface) BlockEntityRenderDispatcher.INSTANCE).renderBlockEntityOffset(carriedBlockEntity, float_1, int_1, BlockRenderLayer.field_20799, bufferBuilder_1, pistonBlockEntity_1.getRenderOffsetX(float_1), pistonBlockEntity_1.getRenderOffsetY(float_1), pistonBlockEntity_1.getRenderOffsetZ(float_1)); matrixStack_1.translate( - pistonBlockEntity_1.getRenderOffsetX(partialTicks), - pistonBlockEntity_1.getRenderOffsetY(partialTicks), - pistonBlockEntity_1.getRenderOffsetZ(partialTicks) + pistonBlockEntity_1.getXOff(partialTicks), + pistonBlockEntity_1.getYOff(partialTicks), + pistonBlockEntity_1.getZOff(partialTicks) ); dispatcher.render(carriedBlockEntity, partialTicks, matrixStack_1, layeredVertexConsumerStorage_1); diff --git a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntity_movableBEMixin.java similarity index 56% rename from src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java rename to src/main/java/carpet/mixins/PistonBlockEntity_movableBEMixin.java index a3f7a8a8..47b3435c 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntity_movableBEMixin.java @@ -4,16 +4,16 @@ import carpet.CarpetSettings; import carpet.fakes.BlockEntityInterface; import carpet.fakes.PistonBlockEntityInterface; import carpet.fakes.WorldInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockEntityProvider; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.block.entity.PistonBlockEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -22,19 +22,19 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(PistonBlockEntity.class) -public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity implements PistonBlockEntityInterface +@Mixin(PistonMovingBlockEntity.class) +public abstract class PistonBlockEntity_movableBEMixin extends BlockEntity implements PistonBlockEntityInterface { @Shadow - private boolean source; + private boolean isSourcePiston; @Shadow - private BlockState pushedBlock; + private BlockState movedState; private BlockEntity carriedBlockEntity; private boolean renderCarriedBlockEntity = false; private boolean renderSet = false; - public PistonBlockEntity_movableTEMixin(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { + public PistonBlockEntity_movableBEMixin(BlockEntityType blockEntityType, BlockPos blockPos, BlockState blockState) { super(blockEntityType, blockPos, blockState); } @@ -48,9 +48,9 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple } @Override - public void setWorld(World world) { - super.setWorld(world); - if (carriedBlockEntity != null) carriedBlockEntity.setWorld(world); + public void setLevel(Level world) { + super.setLevel(world); + if (carriedBlockEntity != null) carriedBlockEntity.setLevel(world); } public void setCarriedBlockEntity(BlockEntity blockEntity) @@ -58,9 +58,9 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple this.carriedBlockEntity = blockEntity; if (this.carriedBlockEntity != null) { - ((BlockEntityInterface)carriedBlockEntity).setCMPos(pos); + ((BlockEntityInterface)carriedBlockEntity).setCMPos(worldPosition); // this might be little dangerous since pos is final for a hashing reason? - if (world != null) carriedBlockEntity.setWorld(world); + if (level != null) carriedBlockEntity.setLevel(level); } // this.carriedBlockEntity.setPos(this.pos); } @@ -85,23 +85,23 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple * @author 2No2Name */ @Redirect(method = "tick", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z")) + target = "Lnet/minecraft/world/level/Level;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z")) private static boolean movableTEsetBlockState0( - World world, BlockPos blockPos_1, BlockState blockAState_2, int int_1, - World world2, BlockPos blockPos, BlockState blockState, PistonBlockEntity pistonBlockEntity) + Level world, BlockPos blockPos_1, BlockState blockAState_2, int int_1, + Level world2, BlockPos blockPos, BlockState blockState, PistonMovingBlockEntity pistonBlockEntity) { if (!CarpetSettings.movableBlockEntities) - return world.setBlockState(blockPos_1, blockAState_2, int_1); + return world.setBlock(blockPos_1, blockAState_2, int_1); else return ((WorldInterface) (world)).setBlockStateWithBlockEntity(blockPos_1, blockAState_2, ((PistonBlockEntityInterface)pistonBlockEntity).getCarriedBlockEntity(), int_1); } - @Redirect(method = "finish", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z")) - private boolean movableTEsetBlockState1(World world, BlockPos blockPos_1, BlockState blockState_2, int int_1) + @Redirect(method = "finalTick", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/Level;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z")) + private boolean movableTEsetBlockState1(Level world, BlockPos blockPos_1, BlockState blockState_2, int int_1) { if (!CarpetSettings.movableBlockEntities) - return world.setBlockState(blockPos_1, blockState_2, int_1); + return world.setBlock(blockPos_1, blockState_2, int_1); else { boolean ret = ((WorldInterface) (world)).setBlockStateWithBlockEntity(blockPos_1, blockState_2, this.carriedBlockEntity, int_1); @@ -110,44 +110,44 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple } } - @Inject(method = "finish", at = @At(value = "RETURN")) + @Inject(method = "finalTick", at = @At(value = "RETURN")) private void finishHandleBroken(CallbackInfo cir) { //Handle TNT Explosions or other ways the moving Block is broken //Also /setblock will cause this to be called, and drop e.g. a moving chest's contents. // This is MC-40380 (BlockEntities that aren't Inventories drop stuff when setblock is called ) - if (CarpetSettings.movableBlockEntities && this.carriedBlockEntity != null && !this.world.isClient && this.world.getBlockState(this.pos).getBlock() == Blocks.AIR) + if (CarpetSettings.movableBlockEntities && this.carriedBlockEntity != null && !this.level.isClientSide && this.level.getBlockState(this.worldPosition).getBlock() == Blocks.AIR) { BlockState blockState_2; - if (this.source) - blockState_2 = Blocks.AIR.getDefaultState(); + if (this.isSourcePiston) + blockState_2 = Blocks.AIR.defaultBlockState(); else - blockState_2 = Block.postProcessState(this.pushedBlock, this.world, this.pos); - ((WorldInterface) (this.world)).setBlockStateWithBlockEntity(this.pos, blockState_2, this.carriedBlockEntity, 3); - this.world.breakBlock(this.pos, false, null); + blockState_2 = Block.updateFromNeighbourShapes(this.movedState, this.level, this.worldPosition); + ((WorldInterface) (this.level)).setBlockStateWithBlockEntity(this.worldPosition, blockState_2, this.carriedBlockEntity, 3); + this.level.destroyBlock(this.worldPosition, false, null); } } - @Inject(method = "readNbt", at = @At(value = "TAIL")) - private void onFromTag(NbtCompound NbtCompound_1, CallbackInfo ci) + @Inject(method = "load", at = @At(value = "TAIL")) + private void onFromTag(CompoundTag NbtCompound_1, CallbackInfo ci) { if (CarpetSettings.movableBlockEntities && NbtCompound_1.contains("carriedTileEntityCM", 10)) { - if (this.pushedBlock.getBlock() instanceof BlockEntityProvider) - this.carriedBlockEntity = ((BlockEntityProvider) (this.pushedBlock.getBlock())).createBlockEntity(pos, pushedBlock);// this.world); + if (this.movedState.getBlock() instanceof EntityBlock) + this.carriedBlockEntity = ((EntityBlock) (this.movedState.getBlock())).newBlockEntity(worldPosition, movedState);// this.world); if (carriedBlockEntity != null) //Can actually be null, as BlockPistonMoving.createNewTileEntity(...) returns null - this.carriedBlockEntity.readNbt(NbtCompound_1.getCompound("carriedTileEntityCM")); + this.carriedBlockEntity.load(NbtCompound_1.getCompound("carriedTileEntityCM")); setCarriedBlockEntity(carriedBlockEntity); } } - @Inject(method = "writeNbt", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) - private void onToTag(NbtCompound NbtCompound_1, CallbackInfo ci) + @Inject(method = "saveAdditional", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) + private void onToTag(CompoundTag NbtCompound_1, CallbackInfo ci) { if (CarpetSettings.movableBlockEntities && this.carriedBlockEntity != null) { //Leave name "carriedTileEntityCM" instead of "carriedBlockEntityCM" for upgrade compatibility with 1.13.2 movable TE - NbtCompound_1.put("carriedTileEntityCM", this.carriedBlockEntity.createNbt()); + NbtCompound_1.put("carriedTileEntityCM", this.carriedBlockEntity.saveWithoutMetadata()); } } } diff --git a/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java b/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java index bf08598f..2256a91d 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntity_playerHandlingMixin.java @@ -2,16 +2,16 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.patches.EntityPlayerMPFake; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.entity.PistonBlockEntity; -import net.minecraft.block.piston.PistonBehavior; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.PushReaction; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -19,54 +19,54 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(PistonBlockEntity.class) +@Mixin(PistonMovingBlockEntity.class) public abstract class PistonBlockEntity_playerHandlingMixin { - @Shadow private BlockState pushedBlock; + @Shadow private BlockState movedState; @Shadow public abstract Direction getMovementDirection(); - @Inject(method = "moveEntity", at = @At("HEAD"), cancellable = true) + @Inject(method = "moveEntityByPiston", at = @At("HEAD"), cancellable = true) private static void dontPushSpectators(Direction direction, Entity entity, double d, Direction direction2, CallbackInfo ci) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) ci.cancel(); + if (CarpetSettings.creativeNoClip && entity instanceof Player && (((Player) entity).isCreative()) && ((Player) entity).getAbilities().flying) ci.cancel(); } - @Redirect(method = "pushEntities", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;setVelocity(DDD)V")) + @Redirect(method = "moveCollidedEntities", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;setDeltaMovement(DDD)V")) private static void ignoreAccel(Entity entity, double x, double y, double z) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) return; - entity.setVelocity(x,y,z); + if (CarpetSettings.creativeNoClip && entity instanceof Player && (((Player) entity).isCreative()) && ((Player) entity).getAbilities().flying) return; + entity.setDeltaMovement(x,y,z); } - @Redirect(method = "pushEntities", at = @At( + @Redirect(method = "moveCollidedEntities", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/Entity;getPistonBehavior()Lnet/minecraft/block/piston/PistonBehavior;" + target = "Lnet/minecraft/world/entity/Entity;getPistonPushReaction()Lnet/minecraft/world/level/material/PushReaction;" )) - private static PistonBehavior moveFakePlayers(Entity entity, - World world, BlockPos blockPos, float ff, PistonBlockEntity pistonBlockEntity) + private static PushReaction moveFakePlayers(Entity entity, + Level world, BlockPos blockPos, float ff, PistonMovingBlockEntity pistonBlockEntity) { - if (entity instanceof EntityPlayerMPFake && pistonBlockEntity.getPushedBlock().isOf(Blocks.SLIME_BLOCK)) + if (entity instanceof EntityPlayerMPFake && pistonBlockEntity.getMovedState().is(Blocks.SLIME_BLOCK)) { - Vec3d vec3d = entity.getVelocity(); + Vec3 vec3d = entity.getDeltaMovement(); double e = vec3d.x; double f = vec3d.y; double g = vec3d.z; Direction direction = pistonBlockEntity.getMovementDirection(); switch(direction.getAxis()) { case X: - e = (double)direction.getOffsetX(); + e = (double)direction.getStepX(); break; case Y: - f = (double)direction.getOffsetY(); + f = (double)direction.getStepY(); break; case Z: - g = (double)direction.getOffsetZ(); + g = (double)direction.getStepZ(); } - entity.setVelocity(e, f, g); + entity.setDeltaMovement(e, f, g); } - return entity.getPistonBehavior(); + return entity.getPistonPushReaction(); } } diff --git a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlock_movableBEMixin.java similarity index 58% rename from src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java rename to src/main/java/carpet/mixins/PistonBlock_movableBEMixin.java index 23ea423a..2e315c60 100644 --- a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlock_movableBEMixin.java @@ -3,13 +3,19 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.PistonBlockEntityInterface; import com.google.common.collect.Lists; -import net.minecraft.block.*; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.piston.PistonBehavior; -import net.minecraft.block.piston.PistonHandler; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.CommandBlock; +import net.minecraft.world.level.block.DirectionalBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.piston.MovingPistonBlock; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.PushReaction; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -20,18 +26,18 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.List; import java.util.Map; -@Mixin(PistonBlock.class) -public abstract class PistonBlock_movableTEMixin extends FacingBlock +@Mixin(PistonBaseBlock.class) +public abstract class PistonBlock_movableBEMixin extends DirectionalBlock { - protected PistonBlock_movableTEMixin(Settings block$Settings_1) + protected PistonBlock_movableBEMixin(Properties block$Settings_1) { super(block$Settings_1); } private ThreadLocal> list1_BlockEntities = new ThreadLocal<>(); //Unneccessary ThreadLocal if client and server use different PistonBlock instances - @Inject(method = "isMovable", cancellable = true, at = @At(value = "RETURN", ordinal = 3, shift = At.Shift.BEFORE)) - private static void movableCMD(BlockState blockState_1, World world_1, BlockPos blockPos_1, + @Inject(method = "isPushable", cancellable = true, at = @At(value = "RETURN", ordinal = 3, shift = At.Shift.BEFORE)) + private static void movableCMD(BlockState blockState_1, Level world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, Direction direction_2, CallbackInfoReturnable cir) { Block block_1 = blockState_1.getBlock(); @@ -50,7 +56,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock block != Blocks.SPAWNER; } - @Redirect(method = "isMovable", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;hasBlockEntity()Z")) + @Redirect(method = "isPushable", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;hasBlockEntity()Z")) private static boolean ifHasBlockEntity(BlockState blockState) { if (!blockState.hasBlockEntity()) @@ -63,20 +69,20 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock } } - @Redirect(method = "isMovable", at = @At( + @Redirect(method = "isPushable", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/BlockState;getPistonBehavior()Lnet/minecraft/block/piston/PistonBehavior;" + target = "Lnet/minecraft/world/level/block/state/BlockState;getPistonPushReaction()Lnet/minecraft/world/level/material/PushReaction;" )) - private static PistonBehavior moveGrindstones(BlockState blockState) + private static PushReaction moveGrindstones(BlockState blockState) { - if (CarpetSettings.movableBlockEntities && blockState.getBlock() == Blocks.GRINDSTONE) return PistonBehavior.NORMAL; - return blockState.getPistonBehavior(); + if (CarpetSettings.movableBlockEntities && blockState.getBlock() == Blocks.GRINDSTONE) return PushReaction.NORMAL; + return blockState.getPistonPushReaction(); } - @Inject(method = "move", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, + @Inject(method = "moveBlocks", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, target = "Ljava/util/List;size()I", ordinal = 4),locals = LocalCapture.CAPTURE_FAILHARD) - private void onMove(World world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, - CallbackInfoReturnable cir, BlockPos blockPos_2, PistonHandler pistonHandler_1, Map map_1, + private void onMove(Level world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, + CallbackInfoReturnable cir, BlockPos blockPos_2, PistonStructureResolver pistonHandler_1, Map map_1, List list_1, List list_2, List list_3, BlockState[] blockStates_1, Direction direction_2, int int_2) { @@ -94,37 +100,37 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock //hopefully this call won't have any side effects in the future, such as dropping all the BlockEntity's items //we want to place this same(!) BlockEntity object into the world later when the movement stops again world_1.removeBlockEntity(blockpos); - blockEntity.markDirty(); + blockEntity.setChanged(); } } } } - @Inject(method = "move", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Lnet/minecraft/world/World;addBlockEntity(Lnet/minecraft/block/entity/BlockEntity;)V", ordinal = 0), + @Inject(method = "moveBlocks", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, + target = "Lnet/minecraft/world/level/Level;setBlockEntity(Lnet/minecraft/world/level/block/entity/BlockEntity;)V", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD) - private void setBlockEntityWithCarried(World world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, - CallbackInfoReturnable cir, BlockPos blockPos_2, PistonHandler pistonHandler_1, Map map_1, List list_1, + private void setBlockEntityWithCarried(Level world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, + CallbackInfoReturnable cir, BlockPos blockPos_2, PistonStructureResolver pistonHandler_1, Map map_1, List list_1, List list_2, List list_3, BlockState[] blockStates_1, Direction direction_2, int int_2, int int_3, BlockPos blockPos_4, BlockState blockState9, BlockState blockState4) { - BlockEntity blockEntityPiston = PistonExtensionBlock.createBlockEntityPiston(blockPos_4, blockState4, (BlockState) list_2.get(int_3), + BlockEntity blockEntityPiston = MovingPistonBlock.newMovingBlockEntity(blockPos_4, blockState4, (BlockState) list_2.get(int_3), direction_1, boolean_1, false); if (CarpetSettings.movableBlockEntities) ((PistonBlockEntityInterface) blockEntityPiston).setCarriedBlockEntity(list1_BlockEntities.get().get(int_3)); - world_1.addBlockEntity(blockEntityPiston); + world_1.setBlockEntity(blockEntityPiston); //world_1.setBlockEntity(blockPos_4, blockEntityPiston); } - @Redirect(method = "move", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/World;addBlockEntity(Lnet/minecraft/block/entity/BlockEntity;)V", + @Redirect(method = "moveBlocks", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/Level;setBlockEntity(Lnet/minecraft/world/level/block/entity/BlockEntity;)V", ordinal = 0)) - private void dontDoAnything(World world, BlockEntity blockEntity) + private void dontDoAnything(Level world, BlockEntity blockEntity) { } - @Redirect(method = "move", at = @At(value = "INVOKE", - target = "Lnet/minecraft/block/PistonExtensionBlock;createBlockEntityPiston(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/Direction;ZZ)Lnet/minecraft/block/entity/BlockEntity;", + @Redirect(method = "moveBlocks", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/block/piston/MovingPistonBlock;newMovingBlockEntity(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/Direction;ZZ)Lnet/minecraft/world/level/block/entity/BlockEntity;", ordinal = 0)) private BlockEntity returnNull(BlockPos blockPos, BlockState blockState, BlockState blockState2, Direction direction, boolean bl, boolean bl2) { diff --git a/src/main/java/carpet/mixins/PistonBlock_qcMixin.java b/src/main/java/carpet/mixins/PistonBlock_qcMixin.java index e54a10df..3d5eccc0 100644 --- a/src/main/java/carpet/mixins/PistonBlock_qcMixin.java +++ b/src/main/java/carpet/mixins/PistonBlock_qcMixin.java @@ -1,23 +1,23 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.PistonBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(PistonBlock.class) +@Mixin(PistonBaseBlock.class) public class PistonBlock_qcMixin { - @Inject(method = "shouldExtend", cancellable = true, at = @At( + @Inject(method = "getNeighborSignal", cancellable = true, at = @At( value = "INVOKE", - target = "Lnet/minecraft/util/math/BlockPos;up()Lnet/minecraft/util/math/BlockPos;" // up + target = "Lnet/minecraft/core/BlockPos;above()Lnet/minecraft/core/BlockPos;" )) - private void cancelUpCheck(World world_1, BlockPos blockPos_1, Direction direction_1, CallbackInfoReturnable cir) + private void cancelUpCheck(Level world_1, BlockPos blockPos_1, Direction direction_1, CallbackInfoReturnable cir) { if (!CarpetSettings.quasiConnectivity) { diff --git a/src/main/java/carpet/mixins/PistonBlock_rotatorBlockMixin.java b/src/main/java/carpet/mixins/PistonBlock_rotatorBlockMixin.java index 17ed7a29..1a69f671 100644 --- a/src/main/java/carpet/mixins/PistonBlock_rotatorBlockMixin.java +++ b/src/main/java/carpet/mixins/PistonBlock_rotatorBlockMixin.java @@ -1,21 +1,21 @@ package carpet.mixins; import carpet.fakes.PistonBlockInterface; -import net.minecraft.block.PistonBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(PistonBlock.class) +@Mixin(PistonBaseBlock.class) public abstract class PistonBlock_rotatorBlockMixin implements PistonBlockInterface { - @Shadow protected abstract boolean shouldExtend(World world_1, BlockPos blockPos_1, Direction direction_1); + @Shadow protected abstract boolean getNeighborSignal(Level world_1, BlockPos blockPos_1, Direction direction_1); @Override - public boolean publicShouldExtend(World world_1, BlockPos blockPos_1, Direction direction_1) + public boolean publicShouldExtend(Level world_1, BlockPos blockPos_1, Direction direction_1) { - return shouldExtend(world_1, blockPos_1,direction_1); + return getNeighborSignal(world_1, blockPos_1,direction_1); } } diff --git a/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java b/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java index a251f251..3dbf3f5f 100644 --- a/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java +++ b/src/main/java/carpet/mixins/PistonHandler_customStickyMixin.java @@ -1,17 +1,6 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.ChainBlock; -import net.minecraft.block.ChestBlock; -import net.minecraft.block.EndRodBlock; -import net.minecraft.block.enums.ChestType; -import net.minecraft.block.piston.PistonHandler; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,8 +11,19 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.ChainBlock; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.EndRodBlock; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.ChestType; -@Mixin(PistonHandler.class) +@Mixin(PistonStructureResolver.class) public abstract class PistonHandler_customStickyMixin { /* @@ -36,22 +36,22 @@ public abstract class PistonHandler_customStickyMixin * * These also support other custom sticky block with non-standard rules, like chains. */ - @Shadow @Final private World world; - @Shadow @Final private Direction motionDirection; - @Shadow protected abstract boolean tryMove(BlockPos blockPos_1, Direction direction_1); - @Shadow private static boolean isBlockSticky(BlockState block_1) { return false; } - @Shadow private static boolean isAdjacentBlockStuck(BlockState block, BlockState block2) {return false;} - @Shadow protected abstract boolean tryMoveAdjacentBlock(BlockPos pos); + @Shadow @Final private Level level; + @Shadow @Final private Direction pushDirection; + @Shadow protected abstract boolean addBlockLine(BlockPos blockPos_1, Direction direction_1); + @Shadow private static boolean isSticky(BlockState block_1) { return false; } + @Shadow private static boolean canStickToEachOther(BlockState block, BlockState block2) {return false;} + @Shadow protected abstract boolean addBranchingBlocks(BlockPos pos); // collects information about sticking block when backtracking. private BlockPos currentPos; private BlockState currentState; - @Redirect(method = "tryMove", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;", ordinal = 0)) - private BlockState redirectGetBlockState_1_A(World world, BlockPos pos) { + @Redirect(method = "addBlockLine", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", ordinal = 0)) + private BlockState redirectGetBlockState_1_A(Level world, BlockPos pos) { return currentState = world.getBlockState(pos); } - @Redirect(method = "tryMove", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/BlockState;", ordinal = 1)) - private BlockState redirectGetBlockState_1_B(World world, BlockPos pos) { + @Redirect(method = "addBlockLine", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;", ordinal = 1)) + private BlockState redirectGetBlockState_1_B(Level world, BlockPos pos) { currentPos = pos; return currentState = world.getBlockState(pos); } @@ -60,15 +60,15 @@ public abstract class PistonHandler_customStickyMixin * Makes backwards stickiness work with sticky non-slimeblocks as well (chests, chains). * @author 2No2Name, gnembon */ - @Redirect(method = "tryMove", at = @At( + @Redirect(method = "addBlockLine", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/BlockState;)Z", + target = "Lnet/minecraft/world/level/block/piston/PistonStructureResolver;isSticky(Lnet/minecraft/world/level/block/state/BlockState;)Z", ordinal = 0 ) ) private boolean redirectIsStickyBlock(BlockState blockState) { // applies to both MBE chests as well as sticky chains - return blockCanBePulled(blockState) || isBlockSticky(blockState); + return blockCanBePulled(blockState) || isSticky(blockState); } /** @@ -83,14 +83,14 @@ public abstract class PistonHandler_customStickyMixin Block block = blockState.getBlock(); if (block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST) //Make chests be sticky on the side to - return getDirectionToOtherChestHalf(blockState) == motionDirection.getOpposite(); + return getDirectionToOtherChestHalf(blockState) == pushDirection.getOpposite(); //example how you could make sticky pistons have a sticky side: //if(block == Blocks.STICKY_PISTON) // return blockState.get(FacingBlock.FACING) == motionDirection; } if (CarpetSettings.doChainStone && blockState.getBlock() == Blocks.CHAIN) { - return isChainOnAxis(currentState, motionDirection); + return isChainOnAxis(currentState, pushDirection); } @@ -103,26 +103,26 @@ public abstract class PistonHandler_customStickyMixin * @param next: canidate block to decide if needs to be dragged along as well. * @return true if we should keep dragging blocks behind */ - @Redirect(method = "tryMove", at = @At( + @Redirect(method = "addBlockLine", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z") + target = "Lnet/minecraft/world/level/block/piston/PistonStructureResolver;canStickToEachOther(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;)Z") ) private boolean isDraggingPreviousBlockBehind(BlockState previous, BlockState next) { if (CarpetSettings.doChainStone) { - if (previous.getBlock() == Blocks.CHAIN && isChainOnAxis(previous, motionDirection)) + if (previous.getBlock() == Blocks.CHAIN && isChainOnAxis(previous, pushDirection)) { - if ( (next.getBlock() == Blocks.CHAIN && isChainOnAxis(next, motionDirection)) + if ( (next.getBlock() == Blocks.CHAIN && isChainOnAxis(next, pushDirection)) || CarpetSettings.chainStoneStickToAll - || isEndRodOnAxis(next, motionDirection.getAxis()) - || Block.sideCoversSmallSquare(world, currentPos, motionDirection)) + || isEndRodOnAxis(next, pushDirection.getAxis()) + || Block.canSupportCenter(level, currentPos, pushDirection)) { return true; } } } - return isAdjacentBlockStuck(previous, next); + return canStickToEachOther(previous, next); } @@ -131,7 +131,7 @@ public abstract class PistonHandler_customStickyMixin * This runs in U style structures with something in the middle on retraction. * @author 2No2Name */ - @Inject(method = "tryMove", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( + @Inject(method = "addBlockLine", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( value = "INVOKE", target = "Ljava/util/List;get(I)Ljava/lang/Object;", shift = At.Shift.AFTER @@ -146,8 +146,8 @@ public abstract class PistonHandler_customStickyMixin } } } - @Shadow @Final private List movedBlocks; - @Inject(method = "calculatePush", at = @At(value = "INVOKE", target = "Ljava/util/List;get(I)Ljava/lang/Object;", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true) + @Shadow @Final private List toPush; + @Inject(method = "resolve", at = @At(value = "INVOKE", target = "Ljava/util/List;get(I)Ljava/lang/Object;", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true) /** * Handles blocks besides the slimeblock that are sticky. * Supports blocks that are sticky on one side, (double chests now, 2no2name) @@ -157,7 +157,7 @@ public abstract class PistonHandler_customStickyMixin private void stickToStickySide(CallbackInfoReturnable cir, int int_1){ if (CarpetSettings.movableBlockEntities) { - if (!stickToStickySide(this.movedBlocks.get(int_1))) + if (!stickToStickySide(this.toPush.get(int_1))) { cir.setReturnValue(false); } @@ -165,11 +165,11 @@ public abstract class PistonHandler_customStickyMixin if (CarpetSettings.doChainStone) { - BlockPos pos = this.movedBlocks.get(int_1); - BlockState chainState = world.getBlockState(pos); + BlockPos pos = this.toPush.get(int_1); + BlockState chainState = level.getBlockState(pos); // chain is sideways - if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, motionDirection) - && !this.tryMoveAdjacentBlock(pos)) + if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, pushDirection) + && !this.addBranchingBlocks(pos)) { cir.setReturnValue(false); } @@ -184,7 +184,7 @@ public abstract class PistonHandler_customStickyMixin */ private boolean stickToStickySide(BlockPos blockPos_1) { - BlockState blockState_1 = this.world.getBlockState(blockPos_1); + BlockState blockState_1 = this.level.getBlockState(blockPos_1); Block block = blockState_1.getBlock(); Direction stickyDirection = null; if(block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST) { @@ -196,7 +196,7 @@ public abstract class PistonHandler_customStickyMixin // stickyDirection = blockState_1.get(FacingBlock.FACING); //} - return stickyDirection == null || this.tryMove(blockPos_1.offset(stickyDirection), stickyDirection); //offset + return stickyDirection == null || this.addBlockLine(blockPos_1.relative(stickyDirection), stickyDirection); //offset } @@ -204,9 +204,9 @@ public abstract class PistonHandler_customStickyMixin * This never seems to run * @author gnembon */ - @Inject(method = "tryMove", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at= @At( + @Inject(method = "addBlockLine", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at= @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isBlockSticky(Lnet/minecraft/block/BlockState;)Z", + target = "Lnet/minecraft/world/level/block/piston/PistonStructureResolver;isSticky(Lnet/minecraft/world/level/block/state/BlockState;)Z", ordinal = 1, shift = At.Shift.BEFORE ) @@ -216,8 +216,8 @@ public abstract class PistonHandler_customStickyMixin { if (CarpetSettings.doChainStone) { - BlockState chainState = world.getBlockState(blockPos3); - if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, motionDirection) && !tryMoveAdjacentBlock(blockPos3)) + BlockState chainState = level.getBlockState(blockPos3); + if (chainState.getBlock() == Blocks.CHAIN && !isChainOnAxis(chainState, pushDirection) && !addBranchingBlocks(blockPos3)) { cir.setReturnValue(false); } @@ -228,9 +228,9 @@ public abstract class PistonHandler_customStickyMixin /** * Custom movement of blocks stuck to the sides of blocks other than slimeblocks like chains */ - @Inject(method = "tryMoveAdjacentBlock", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( + @Inject(method = "addBranchingBlocks", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z", + target = "Lnet/minecraft/world/level/block/piston/PistonStructureResolver;canStickToEachOther(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;)Z", shift = At.Shift.BEFORE )) private void otherSideStickyCases(BlockPos pos, CallbackInfoReturnable cir, @@ -241,13 +241,13 @@ public abstract class PistonHandler_customStickyMixin if (blockState.getBlock() == Blocks.CHAIN && isChainOnAxis(blockState, direction) && !blockState2.isAir()) { Block otherBlock = blockState2.getBlock(); - if ((otherBlock == Blocks.CHAIN && (blockState.get(ChainBlock.AXIS) == blockState2.get(ChainBlock.AXIS))) + if ((otherBlock == Blocks.CHAIN && (blockState.getValue(ChainBlock.AXIS) == blockState2.getValue(ChainBlock.AXIS))) || CarpetSettings.chainStoneStickToAll - || isEndRodOnAxis(blockState2, blockState.get(ChainBlock.AXIS)) + || isEndRodOnAxis(blockState2, blockState.getValue(ChainBlock.AXIS)) || otherBlock == Blocks.HONEY_BLOCK - || Block.sideCoversSmallSquare(world, blockPos, direction.getOpposite())) + || Block.canSupportCenter(level, blockPos, direction.getOpposite())) { - if (!tryMove(blockPos, direction)) + if (!addBlockLine(blockPos, direction)) { cir.setReturnValue(false); } @@ -264,13 +264,13 @@ public abstract class PistonHandler_customStickyMixin * @param block2 * @return */ - @Redirect(method = "tryMoveAdjacentBlock", at = @At( + @Redirect(method = "addBranchingBlocks", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/piston/PistonHandler;isAdjacentBlockStuck(Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)Z") + target = "Lnet/minecraft/world/level/block/piston/PistonStructureResolver;canStickToEachOther(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;)Z") ) private boolean isStuckSlimeStone(BlockState block, BlockState block2) { - return isBlockSticky(block2) && isAdjacentBlockStuck(block, block2); + return isSticky(block2) && canStickToEachOther(block, block2); } @@ -284,11 +284,11 @@ public abstract class PistonHandler_customStickyMixin { ChestType chestType; try{ - chestType = blockState.get(ChestBlock.CHEST_TYPE); + chestType = blockState.getValue(ChestBlock.TYPE); }catch(IllegalArgumentException e){return null;} if(chestType == ChestType.SINGLE) return null; - return ChestBlock.getFacing(blockState); + return ChestBlock.getConnectedDirection(blockState); } @@ -296,7 +296,7 @@ public abstract class PistonHandler_customStickyMixin { Direction.Axis axis; try { - axis = state.get(ChainBlock.AXIS); + axis = state.getValue(ChainBlock.AXIS); }catch(IllegalArgumentException e){return false;} return stickDirection.getAxis() == axis; } @@ -306,7 +306,7 @@ public abstract class PistonHandler_customStickyMixin if (state.getBlock() != Blocks.END_ROD) return false; Direction facing; try { - facing = state.get(EndRodBlock.FACING); + facing = state.getValue(EndRodBlock.FACING); }catch(IllegalArgumentException e){return false;} return stickAxis == facing.getAxis(); } diff --git a/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java b/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java index ebd7316d..9a8a5c47 100644 --- a/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java +++ b/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java @@ -1,15 +1,15 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.piston.PistonHandler; +import net.minecraft.world.level.block.piston.PistonStructureResolver; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; -@Mixin(value = PistonHandler.class, priority = 420) // piston push limit is important for carpet +@Mixin(value = PistonStructureResolver.class, priority = 420) // piston push limit is important for carpet public class PistonHandler_pushLimitMixin { - @ModifyConstant(method = "tryMove", constant = @Constant(intValue = 12), expect = 3) + @ModifyConstant(method = "addBlockLine", constant = @Constant(intValue = 12), expect = 3) private int pushLimit(int original) { return CarpetSettings.pushLimit; diff --git a/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java b/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java index c7393008..3dab4629 100644 --- a/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java +++ b/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; import carpet.fakes.PlacedFeatureInterface; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.gen.feature.PlacedFeature; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.function.Supplier; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.placement.PlacedFeature; @Mixin(PlacedFeature.class) public class PlacedFeature_scarpetMixin implements PlacedFeatureInterface { diff --git a/src/main/java/carpet/mixins/PlayerActionC2SPacketMixin.java b/src/main/java/carpet/mixins/PlayerActionC2SPacketMixin.java index b68ab767..9ad21549 100644 --- a/src/main/java/carpet/mixins/PlayerActionC2SPacketMixin.java +++ b/src/main/java/carpet/mixins/PlayerActionC2SPacketMixin.java @@ -1,12 +1,12 @@ package carpet.mixins; -import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(PlayerActionC2SPacket.class) +@Mixin(ServerboundPlayerActionPacket.class) public interface PlayerActionC2SPacketMixin { @Accessor("pos") @@ -16,5 +16,5 @@ public interface PlayerActionC2SPacketMixin void setDirection(Direction direction); @Accessor("action") - void setAction(PlayerActionC2SPacket.Action action); + void setAction(ServerboundPlayerActionPacket.Action action); } diff --git a/src/main/java/carpet/mixins/PlayerEntityMixin_portalDelayMixin.java b/src/main/java/carpet/mixins/PlayerEntityMixin_portalDelayMixin.java index b0102cb6..fce0ce41 100644 --- a/src/main/java/carpet/mixins/PlayerEntityMixin_portalDelayMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntityMixin_portalDelayMixin.java @@ -1,8 +1,8 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.player.PlayerAbilities; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.world.entity.player.Abilities; +import net.minecraft.world.entity.player.Player; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -10,12 +10,12 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.At; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntityMixin_portalDelayMixin { - @Final @Shadow public PlayerAbilities abilities; + @Final @Shadow public Abilities abilities; - @Inject(method = "getMaxNetherPortalTime()I", at = @At("HEAD"), cancellable = true) + @Inject(method = "getPortalWaitTime()I", at = @At("HEAD"), cancellable = true) private void onMaxNetherPortalTime(CallbackInfoReturnable cir) { if(CarpetSettings.portalCreativeDelay != 1 && this.abilities.invulnerable) cir.setReturnValue(CarpetSettings.portalCreativeDelay); else if(CarpetSettings.portalSurvivalDelay != 80 && !this.abilities.invulnerable) cir.setReturnValue(CarpetSettings.portalSurvivalDelay); diff --git a/src/main/java/carpet/mixins/PlayerEntity_antiCheatDisabled.java b/src/main/java/carpet/mixins/PlayerEntity_antiCheatDisabled.java index fd50bb93..be00f9d7 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_antiCheatDisabled.java +++ b/src/main/java/carpet/mixins/PlayerEntity_antiCheatDisabled.java @@ -2,31 +2,31 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.CarpetSettings; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ElytraItem; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ElytraItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_antiCheatDisabled { - @Shadow public abstract ItemStack getEquippedStack(EquipmentSlot equipmentSlot_1); + @Shadow public abstract ItemStack getItemBySlot(EquipmentSlot equipmentSlot_1); @Shadow public abstract void startFallFlying(); - @Inject(method = "checkFallFlying", at = @At("HEAD"), cancellable = true) + @Inject(method = "tryToStartFallFlying", at = @At("HEAD"), cancellable = true) private void allowDeploys(CallbackInfoReturnable cir) { - if (CarpetSettings.antiCheatDisabled && CarpetServer.minecraft_server != null && CarpetServer.minecraft_server.isDedicated()) + if (CarpetSettings.antiCheatDisabled && CarpetServer.minecraft_server != null && CarpetServer.minecraft_server.isDedicatedServer()) { - ItemStack itemStack_1 = getEquippedStack(EquipmentSlot.CHEST); - if (itemStack_1.getItem() == Items.ELYTRA && ElytraItem.isUsable(itemStack_1)) { + ItemStack itemStack_1 = getItemBySlot(EquipmentSlot.CHEST); + if (itemStack_1.getItem() == Items.ELYTRA && ElytraItem.isFlyEnabled(itemStack_1)) { startFallFlying(); cir.setReturnValue(true); } diff --git a/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java index d0e51b81..5a41f3f7 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_creativeNoClipMixin.java @@ -1,46 +1,46 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_creativeNoClipMixin extends LivingEntity { - protected PlayerEntity_creativeNoClipMixin(EntityType type, World world) + protected PlayerEntity_creativeNoClipMixin(EntityType type, Level world) { super(type, world); } @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;isSpectator()Z") + target = "Lnet/minecraft/world/entity/player/Player;isSpectator()Z") ) - private boolean canClipTroughWorld(PlayerEntity playerEntity) + private boolean canClipTroughWorld(Player playerEntity) { return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } - @Redirect(method = "tickMovement", at = @At( + @Redirect(method = "aiStep", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;isSpectator()Z") + target = "Lnet/minecraft/world/entity/player/Player;isSpectator()Z") ) - private boolean collidesWithEntities(PlayerEntity playerEntity) + private boolean collidesWithEntities(Player playerEntity) { return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } - @Redirect(method = "updatePose", at = @At( + @Redirect(method = "updatePlayerPose", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;isSpectator()Z") + target = "Lnet/minecraft/world/entity/player/Player;isSpectator()Z") ) - private boolean spectatorsDontPose(PlayerEntity playerEntity) + private boolean spectatorsDontPose(Player playerEntity) { return playerEntity.isSpectator() || (CarpetSettings.creativeNoClip && playerEntity.isCreative() && playerEntity.getAbilities().flying); } diff --git a/src/main/java/carpet/mixins/PlayerEntity_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerEntity_fakePlayersMixin.java index 915557c8..71891f05 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_fakePlayersMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; import carpet.patches.EntityPlayerMPFake; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_fakePlayersMixin { /** @@ -17,12 +17,12 @@ public abstract class PlayerEntity_fakePlayersMixin method = "attack", at = @At( value = "FIELD", - target = "Lnet/minecraft/entity/Entity;velocityModified:Z", + target = "Lnet/minecraft/world/entity/Entity;hurtMarked:Z", ordinal = 0 ) ) private boolean velocityModifiedAndNotCarpetFakePlayer(Entity target) { - return target.velocityModified && !(target instanceof EntityPlayerMPFake); + return target.hurtMarked && !(target instanceof EntityPlayerMPFake); } } diff --git a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java index 48118e7c..82e5ce6c 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.player.PlayerAbilities; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.world.World; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Abilities; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -17,70 +17,70 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_parrotMixin extends LivingEntity { - @Shadow @Final public PlayerAbilities abilities; + @Shadow @Final public Abilities abilities; - @Shadow protected abstract void dropShoulderEntities(); + @Shadow protected abstract void removeEntitiesOnShoulder(); - @Shadow public abstract NbtCompound getShoulderEntityLeft(); + @Shadow public abstract CompoundTag getShoulderEntityLeft(); - @Shadow protected abstract void setShoulderEntityLeft(NbtCompound NbtCompound_1); + @Shadow protected abstract void setShoulderEntityLeft(CompoundTag NbtCompound_1); - @Shadow protected abstract void setShoulderEntityRight(NbtCompound NbtCompound_1); + @Shadow protected abstract void setShoulderEntityRight(CompoundTag NbtCompound_1); - @Shadow public abstract NbtCompound getShoulderEntityRight(); + @Shadow public abstract CompoundTag getShoulderEntityRight(); - @Shadow protected abstract void dropShoulderEntity(NbtCompound entityNbt); + @Shadow protected abstract void respawnEntityOnShoulder(CompoundTag entityNbt); - protected PlayerEntity_parrotMixin(EntityType entityType_1, World world_1) + protected PlayerEntity_parrotMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Redirect(method = "tickMovement", at = @At(value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;dropShoulderEntities()V")) - private void cancelDropShoulderEntities1(PlayerEntity playerEntity) + @Redirect(method = "aiStep", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/player/Player;removeEntitiesOnShoulder()V")) + private void cancelDropShoulderEntities1(Player playerEntity) { } - @Inject(method = "tickMovement", at = @At(value = "INVOKE", shift = At.Shift.AFTER, ordinal = 1, - target = "Lnet/minecraft/entity/player/PlayerEntity;updateShoulderEntity(Lnet/minecraft/nbt/NbtCompound;)V")) + @Inject(method = "aiStep", at = @At(value = "INVOKE", shift = At.Shift.AFTER, ordinal = 1, + target = "Lnet/minecraft/world/entity/player/Player;playShoulderEntityAmbientSound(Lnet/minecraft/nbt/CompoundTag;)V")) private void onTickMovement(CallbackInfo ci) { boolean parrots_will_drop = !CarpetSettings.persistentParrots || this.abilities.invulnerable; - if (!this.world.isClient && ((parrots_will_drop && this.fallDistance > 0.5F) || this.isTouchingWater() || this.abilities.flying || isSleeping())) + if (!this.level.isClientSide && ((parrots_will_drop && this.fallDistance > 0.5F) || this.isInWater() || this.abilities.flying || isSleeping())) { - this.dropShoulderEntities(); + this.removeEntitiesOnShoulder(); } } - @Redirect(method = "damage", at = @At(value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;dropShoulderEntities()V")) - private void cancelDropShoulderEntities2(PlayerEntity playerEntity) + @Redirect(method = "hurt", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/player/Player;removeEntitiesOnShoulder()V")) + private void cancelDropShoulderEntities2(Player playerEntity) { } protected void dismount_left() { - dropShoulderEntity(this.getShoulderEntityLeft()); - this.setShoulderEntityLeft(new NbtCompound()); + respawnEntityOnShoulder(this.getShoulderEntityLeft()); + this.setShoulderEntityLeft(new CompoundTag()); } protected void dismount_right() { - dropShoulderEntity(this.getShoulderEntityRight()); - this.setShoulderEntityRight(new NbtCompound()); + respawnEntityOnShoulder(this.getShoulderEntityRight()); + this.setShoulderEntityRight(new CompoundTag()); } - @Inject(method = "damage", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Lnet/minecraft/entity/player/PlayerEntity;dropShoulderEntities()V")) + @Inject(method = "hurt", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, + target = "Lnet/minecraft/world/entity/player/Player;removeEntitiesOnShoulder()V")) private void onDamage(DamageSource damageSource_1, float float_1, CallbackInfoReturnable cir) { - if (CarpetSettings.persistentParrots && !this.isSneaking()) + if (CarpetSettings.persistentParrots && !this.isShiftKeyDown()) { if (this.random.nextFloat() < ((float_1)/15.0) ) { diff --git a/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java index 999105bb..621ac1d2 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_scarpetEventsMixin.java @@ -2,15 +2,15 @@ package carpet.mixins; import carpet.fakes.EntityInterface; import carpet.script.EntityEventsGroup; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.world.World; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -24,17 +24,17 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_INTERACTS_WITH_ENTITY import static carpet.script.CarpetEventServer.Event.PLAYER_TAKES_DAMAGE; import static carpet.script.CarpetEventServer.Event.PLAYER_COLLIDES_WITH_ENTITY; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_scarpetEventsMixin extends LivingEntity { - protected PlayerEntity_scarpetEventsMixin(EntityType type, World world) + protected PlayerEntity_scarpetEventsMixin(EntityType type, Level world) { super(type, world); } - @Inject(method = "applyDamage", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( + @Inject(method = "actuallyHurt", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;applyArmorToDamage(Lnet/minecraft/entity/damage/DamageSource;F)F" + target = "Lnet/minecraft/world/entity/player/Player;getDamageAfterArmorAbsorb(Lnet/minecraft/world/damagesource/DamageSource;F)F" )) private void playerTakingDamage(DamageSource source, float amount, CallbackInfo ci) { @@ -44,36 +44,36 @@ public abstract class PlayerEntity_scarpetEventsMixin extends LivingEntity { PLAYER_TAKES_DAMAGE.onDamage(this, amount, source); } - if (source.getAttacker() instanceof ServerPlayerEntity && PLAYER_DEALS_DAMAGE.isNeeded()) + if (source.getEntity() instanceof ServerPlayer && PLAYER_DEALS_DAMAGE.isNeeded()) { PLAYER_DEALS_DAMAGE.onDamage(this, amount, source); } } - @Inject(method = "collideWithEntity", at = @At("HEAD")) + @Inject(method = "touch", at = @At("HEAD")) private void onEntityCollision(Entity entity, CallbackInfo ci) { - if (PLAYER_COLLIDES_WITH_ENTITY.isNeeded() && !world.isClient) + if (PLAYER_COLLIDES_WITH_ENTITY.isNeeded() && !level.isClientSide) { - PLAYER_COLLIDES_WITH_ENTITY.onEntityHandAction((ServerPlayerEntity)(Object)this, entity, null); + PLAYER_COLLIDES_WITH_ENTITY.onEntityHandAction((ServerPlayer)(Object)this, entity, null); } } - @Inject(method = "interact", at = @At("HEAD")) - private void doInteract(Entity entity, Hand hand, CallbackInfoReturnable cir) + @Inject(method = "interactOn", at = @At("HEAD")) + private void doInteract(Entity entity, InteractionHand hand, CallbackInfoReturnable cir) { - if (!world.isClient && PLAYER_INTERACTS_WITH_ENTITY.isNeeded()) + if (!level.isClientSide && PLAYER_INTERACTS_WITH_ENTITY.isNeeded()) { - PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction((ServerPlayerEntity) (Object)this, entity, hand); + PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction((ServerPlayer) (Object)this, entity, hand); } } @Inject(method = "attack", at = @At("HEAD")) private void onAttack(Entity target, CallbackInfo ci) { - if (!world.isClient && PLAYER_ATTACKS_ENTITY.isNeeded() && target.isAttackable()) + if (!level.isClientSide && PLAYER_ATTACKS_ENTITY.isNeeded() && target.isAttackable()) { - PLAYER_ATTACKS_ENTITY.onEntityHandAction((ServerPlayerEntity) (Object)this, target, null); + PLAYER_ATTACKS_ENTITY.onEntityHandAction((ServerPlayer) (Object)this, target, null); } } } diff --git a/src/main/java/carpet/mixins/PlayerEntity_xpNoCooldownMixin.java b/src/main/java/carpet/mixins/PlayerEntity_xpNoCooldownMixin.java index 4aa0b8d6..9ace2e5c 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_xpNoCooldownMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_xpNoCooldownMixin.java @@ -1,26 +1,26 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.List; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; -@Mixin(PlayerEntity.class) +@Mixin(Player.class) public abstract class PlayerEntity_xpNoCooldownMixin { @Shadow - protected abstract void collideWithEntity(Entity entity); + protected abstract void touch(Entity entity); - @Redirect(method = "tickMovement",at = @At(value = "INVOKE", target = "java/util/List.add(Ljava/lang/Object;)Z")) + @Redirect(method = "aiStep",at = @At(value = "INVOKE", target = "java/util/List.add(Ljava/lang/Object;)Z")) public boolean processXpOrbCollisions(List instance, Object e) { Entity entity = (Entity) e; if (CarpetSettings.xpNoCooldown) { - this.collideWithEntity(entity); + this.touch(entity); return true; } return instance.add(entity); diff --git a/src/main/java/carpet/mixins/PlayerInventory_scarpetEventMixin.java b/src/main/java/carpet/mixins/PlayerInventory_scarpetEventMixin.java index 24f2e4ee..8ccec7ed 100644 --- a/src/main/java/carpet/mixins/PlayerInventory_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/PlayerInventory_scarpetEventMixin.java @@ -1,10 +1,5 @@ package carpet.mixins; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.server.network.ServerPlayerEntity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -13,27 +8,33 @@ import org.spongepowered.asm.mixin.injection.Redirect; import static carpet.script.CarpetEventServer.Event.PLAYER_PICKS_UP_ITEM; -@Mixin(PlayerInventory.class) +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; + +@Mixin(Inventory.class) public abstract class PlayerInventory_scarpetEventMixin { - @Shadow @Final public PlayerEntity player; + @Shadow @Final public Player player; - @Redirect(method = "insertStack(Lnet/minecraft/item/ItemStack;)Z", at = @At( + @Redirect(method = "add(Lnet/minecraft/world/item/ItemStack;)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerInventory;insertStack(ILnet/minecraft/item/ItemStack;)Z" + target = "Lnet/minecraft/world/entity/player/Inventory;add(ILnet/minecraft/world/item/ItemStack;)Z" )) - private boolean onItemAcquired(PlayerInventory playerInventory, int slot, ItemStack stack) + private boolean onItemAcquired(Inventory playerInventory, int slot, ItemStack stack) { - if (!PLAYER_PICKS_UP_ITEM.isNeeded() || !(player instanceof ServerPlayerEntity)) - return playerInventory.insertStack(-1, stack); + if (!PLAYER_PICKS_UP_ITEM.isNeeded() || !(player instanceof ServerPlayer)) + return playerInventory.add(-1, stack); Item item = stack.getItem(); int count = stack.getCount(); - boolean res = playerInventory.insertStack(-1, stack); + boolean res = playerInventory.add(-1, stack); if (count != stack.getCount()) // res returns false for larger item adding to a almost full ineventory { ItemStack diffStack = new ItemStack(item, count - stack.getCount()); - diffStack.setNbt(stack.getNbt()); - PLAYER_PICKS_UP_ITEM.onItemAction((ServerPlayerEntity) player, null, diffStack); + diffStack.setTag(stack.getTag()); + PLAYER_PICKS_UP_ITEM.onItemAction((ServerPlayer) player, null, diffStack); } return res; } diff --git a/src/main/java/carpet/mixins/PlayerListHeaderS2CPacketMixin.java b/src/main/java/carpet/mixins/PlayerListHeaderS2CPacketMixin.java index 16b5d07c..a9764646 100644 --- a/src/main/java/carpet/mixins/PlayerListHeaderS2CPacketMixin.java +++ b/src/main/java/carpet/mixins/PlayerListHeaderS2CPacketMixin.java @@ -1,16 +1,16 @@ package carpet.mixins; -import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundTabListPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(PlayerListHeaderS2CPacket.class) +@Mixin(ClientboundTabListPacket.class) public interface PlayerListHeaderS2CPacketMixin { @Accessor("header") - void setHeader(Text header); + void setHeader(Component header); @Accessor("footer") - void setFooter(Text footer); + void setFooter(Component footer); } \ No newline at end of file diff --git a/src/main/java/carpet/mixins/PlayerListHudMixin.java b/src/main/java/carpet/mixins/PlayerListHudMixin.java index c70267ec..899e4f50 100644 --- a/src/main/java/carpet/mixins/PlayerListHudMixin.java +++ b/src/main/java/carpet/mixins/PlayerListHudMixin.java @@ -1,16 +1,16 @@ package carpet.mixins; import carpet.fakes.PlayerListHudInterface; -import net.minecraft.client.gui.hud.PlayerListHud; -import net.minecraft.text.Text; +import net.minecraft.client.gui.components.PlayerTabOverlay; +import net.minecraft.network.chat.Component; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(PlayerListHud.class) +@Mixin(PlayerTabOverlay.class) public abstract class PlayerListHudMixin implements PlayerListHudInterface { - @Shadow private Text footer; + @Shadow private Component footer; - @Shadow private Text header; + @Shadow private Component header; public boolean hasFooterOrHeader() { diff --git a/src/main/java/carpet/mixins/PlayerManager_coreMixin.java b/src/main/java/carpet/mixins/PlayerManager_coreMixin.java index de999990..b670629b 100644 --- a/src/main/java/carpet/mixins/PlayerManager_coreMixin.java +++ b/src/main/java/carpet/mixins/PlayerManager_coreMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; import carpet.CarpetServer; -import net.minecraft.network.ClientConnection; +import net.minecraft.network.Connection; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.PlayerManager; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -14,13 +14,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static carpet.script.CarpetEventServer.Event.PLAYER_CONNECTS; -@Mixin(PlayerManager.class) +@Mixin(PlayerList.class) public class PlayerManager_coreMixin { @Shadow @Final private MinecraftServer server; - @Inject(method = "onPlayerConnect", at = @At("RETURN")) - private void onPlayerConnected(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) + @Inject(method = "placeNewPlayer", at = @At("RETURN")) + private void onPlayerConnected(Connection connection, ServerPlayer player, CallbackInfo ci) { CarpetServer.onPlayerLoggedIn(player); PLAYER_CONNECTS.onPlayerEvent(player); diff --git a/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java index c585ee07..2d0333ce 100644 --- a/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerManager_fakePlayersMixin.java @@ -1,11 +1,11 @@ package carpet.mixins; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.ClientConnection; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.Connection; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.PlayerManager; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -16,15 +16,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import carpet.patches.NetHandlerPlayServerFake; import carpet.patches.EntityPlayerMPFake; -@Mixin(PlayerManager.class) +@Mixin(PlayerList.class) public abstract class PlayerManager_fakePlayersMixin { @Shadow @Final private MinecraftServer server; - @Inject(method = "loadPlayerData", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) - private void fixStartingPos(ServerPlayerEntity serverPlayerEntity_1, CallbackInfoReturnable cir) + @Inject(method = "load", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) + private void fixStartingPos(ServerPlayer serverPlayerEntity_1, CallbackInfoReturnable cir) { if (serverPlayerEntity_1 instanceof EntityPlayerMPFake) { @@ -32,8 +32,8 @@ public abstract class PlayerManager_fakePlayersMixin } } - @Redirect(method = "onPlayerConnect", at = @At(value = "NEW", target = "net/minecraft/server/network/ServerPlayNetworkHandler")) - private ServerPlayNetworkHandler replaceNetworkHandler(MinecraftServer server, ClientConnection clientConnection, ServerPlayerEntity playerIn) + @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "net/minecraft/server/network/ServerGamePacketListenerImpl")) + private ServerGamePacketListenerImpl replaceNetworkHandler(MinecraftServer server, Connection clientConnection, ServerPlayer playerIn) { if (playerIn instanceof EntityPlayerMPFake fake) { @@ -41,7 +41,7 @@ public abstract class PlayerManager_fakePlayersMixin } else { - return new ServerPlayNetworkHandler(this.server, clientConnection, playerIn); + return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn); } } } \ No newline at end of file diff --git a/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java index 2c63ef02..9da79636 100644 --- a/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerManager_scarpetEventsMixin.java @@ -2,8 +2,8 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.fakes.ServerPlayerEntityInterface; -import net.minecraft.server.PlayerManager; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -12,26 +12,25 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import static carpet.script.CarpetEventServer.Event.PLAYER_RESPAWNS; -@Mixin(PlayerManager.class) +@Mixin(PlayerList.class) public class PlayerManager_scarpetEventsMixin { - @Inject(method = "respawnPlayer", at = @At("HEAD")) - private void onRespawn(ServerPlayerEntity player, boolean olive, CallbackInfoReturnable cir) + @Inject(method = "respawn", at = @At("HEAD")) + private void onRespawn(ServerPlayer player, boolean olive, CallbackInfoReturnable cir) { PLAYER_RESPAWNS.onPlayerEvent(player); } - @Inject(method = "respawnPlayer", at = @At( + @Inject(method = "respawn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;onSpawn()V" - //target = "Lnet/minecraft/server/network/ServerPlayerEntity;method_34225()V" + target = "Lnet/minecraft/server/level/ServerPlayer;initInventoryMenu()V" )) - private void invalidatePreviousInstance(ServerPlayerEntity player, boolean alive, CallbackInfoReturnable cir) + private void invalidatePreviousInstance(ServerPlayer player, boolean alive, CallbackInfoReturnable cir) { ((ServerPlayerEntityInterface)player).invalidateEntityObjectReference(); } - @Inject(method = "onDataPacksReloaded", at = @At("HEAD")) + @Inject(method = "reloadResources", at = @At("HEAD")) private void reloadCommands(CallbackInfo ci) { CarpetServer.scriptServer.reAddCommands(); diff --git a/src/main/java/carpet/mixins/PointOfInterest_scarpetMixin.java b/src/main/java/carpet/mixins/PointOfInterest_scarpetMixin.java index 94025f75..43d2053c 100644 --- a/src/main/java/carpet/mixins/PointOfInterest_scarpetMixin.java +++ b/src/main/java/carpet/mixins/PointOfInterest_scarpetMixin.java @@ -1,16 +1,16 @@ package carpet.mixins; -import net.minecraft.world.poi.PointOfInterest; +import net.minecraft.world.entity.ai.village.poi.PoiRecord; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; -@Mixin(PointOfInterest.class) +@Mixin(PoiRecord.class) public interface PointOfInterest_scarpetMixin { @Accessor("freeTickets") int getFreeTickets(); @Invoker - boolean callReserveTicket(); + boolean callAcquireTicket(); } diff --git a/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java b/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java index ed54cd83..fe3e678f 100644 --- a/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java +++ b/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.PoweredRailBlock; +import net.minecraft.world.level.block.PoweredRailBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; @@ -9,7 +9,7 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant; @Mixin(PoweredRailBlock.class) public class PoweredRailBlock_powerLimitMixin { - @ModifyConstant(method = "isPoweredByOtherRails(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;ZI)Z", + @ModifyConstant(method = "findPoweredRailSignal(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;ZI)Z", constant = @Constant(intValue = 8)) private int powerLimit(int original) { diff --git a/src/main/java/carpet/mixins/ProjectileEntityMixin.java b/src/main/java/carpet/mixins/ProjectileEntityMixin.java index 8f49d861..e375524d 100644 --- a/src/main/java/carpet/mixins/ProjectileEntityMixin.java +++ b/src/main/java/carpet/mixins/ProjectileEntityMixin.java @@ -2,28 +2,28 @@ package carpet.mixins; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.TrajectoryLogHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.projectile.PersistentProjectileEntity; -import net.minecraft.entity.projectile.ProjectileEntity; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.EntityHitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(PersistentProjectileEntity.class) +@Mixin(AbstractArrow.class) public abstract class ProjectileEntityMixin extends Entity { private TrajectoryLogHelper logHelper; - public ProjectileEntityMixin(EntityType entityType_1, World world_1) { super(entityType_1, world_1); } + public ProjectileEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Inject(method = "(Lnet/minecraft/entity/EntityType;Lnet/minecraft/world/World;)V", at = @At("RETURN")) - private void addLogger(EntityType entityType_1, World world_1, CallbackInfo ci) + @Inject(method = "(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V", at = @At("RETURN")) + private void addLogger(EntityType entityType_1, Level world_1, CallbackInfo ci) { - if (LoggerRegistry.__projectiles && !world_1.isClient) + if (LoggerRegistry.__projectiles && !world_1.isClientSide) logHelper = new TrajectoryLogHelper("projectiles"); } @@ -31,11 +31,11 @@ public abstract class ProjectileEntityMixin extends Entity private void tickCheck(CallbackInfo ci) { if (LoggerRegistry.__projectiles && logHelper != null) - logHelper.onTick(getX(), getY(), getZ(), getVelocity()); + logHelper.onTick(getX(), getY(), getZ(), getDeltaMovement()); } // todo should be moved on one place this is acceessed from - @Inject(method = "onEntityHit", at = @At("RETURN")) + @Inject(method = "onHitEntity", at = @At("RETURN")) private void removeOnEntity(EntityHitResult entityHitResult, CallbackInfo ci) { if (LoggerRegistry.__projectiles && logHelper != null) @@ -45,7 +45,7 @@ public abstract class ProjectileEntityMixin extends Entity } } - @Inject(method = "onBlockHit", at = @At("RETURN")) + @Inject(method = "onHitBlock", at = @At("RETURN")) private void removeOnBlock(BlockHitResult blockHitResult, CallbackInfo ci) { if (LoggerRegistry.__projectiles && logHelper != null) diff --git a/src/main/java/carpet/mixins/ProjectileEntity_extremeMixin.java b/src/main/java/carpet/mixins/ProjectileEntity_extremeMixin.java index c08dd633..287ee2cc 100644 --- a/src/main/java/carpet/mixins/ProjectileEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/ProjectileEntity_extremeMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.projectile.PersistentProjectileEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.projectile.AbstractArrow; -@Mixin(PersistentProjectileEntity.class) +@Mixin(AbstractArrow.class) public class ProjectileEntity_extremeMixin { // calculates damage - @Redirect(method = "applyEnchantmentEffects", expect = 1, at = @At( + @Redirect(method = "setEnchantmentEffectsFromEntity", expect = 1, at = @At( value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/Projectile_extremeMixin.java b/src/main/java/carpet/mixins/Projectile_extremeMixin.java index 820e66a9..1b0b606f 100644 --- a/src/main/java/carpet/mixins/Projectile_extremeMixin.java +++ b/src/main/java/carpet/mixins/Projectile_extremeMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.projectile.ProjectileEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.projectile.Projectile; -@Mixin(ProjectileEntity.class) +@Mixin(Projectile.class) public class Projectile_extremeMixin { - @Redirect(method = "setVelocity", expect = 3, at = @At( + @Redirect(method = "shoot", expect = 3, at = @At( //TODO make sure it's correct after mojmap value = "INVOKE", target = "Ljava/util/Random;nextGaussian()D" )) diff --git a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java index 167ca616..52530628 100644 --- a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java @@ -2,11 +2,6 @@ package carpet.mixins; import carpet.fakes.RecipeManagerInterface; import com.google.common.collect.Lists; -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeManager; -import net.minecraft.recipe.RecipeType; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -14,21 +9,26 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.item.crafting.RecipeType; @Mixin(RecipeManager.class) public class RecipeManager_scarpetMixin implements RecipeManagerInterface { - @Shadow private Map, Map>> recipes; + @Shadow private Map, Map>> recipes; @Override - public List> getAllMatching(RecipeType type, Identifier output) + public List> getAllMatching(RecipeType type, ResourceLocation output) { - Map> typeRecipes = recipes.get(type); + Map> typeRecipes = recipes.get(type); // happens when mods add recipe to the registry without updating recipe manager if (typeRecipes == null) return Collections.emptyList(); if (typeRecipes.containsKey(output)) return Collections.singletonList(typeRecipes.get(output)); return Lists.newArrayList(typeRecipes.values().stream().filter( - r -> Registry.ITEM.getId(r.getOutput().getItem()).equals(output)).collect(Collectors.toList())); + r -> Registry.ITEM.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); } } diff --git a/src/main/java/carpet/mixins/RedstoneWireBlockMixin.java b/src/main/java/carpet/mixins/RedstoneWireBlockMixin.java index ec670661..8a602999 100644 --- a/src/main/java/carpet/mixins/RedstoneWireBlockMixin.java +++ b/src/main/java/carpet/mixins/RedstoneWireBlockMixin.java @@ -4,12 +4,6 @@ import carpet.CarpetSettings; import carpet.fakes.RedstoneWireBlockInterface; import carpet.helpers.RedstoneWireTurbo; import com.google.common.collect.Sets; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.RedstoneWireBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -23,24 +17,31 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Iterator; import java.util.Set; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.RedStoneWireBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; -import static net.minecraft.block.RedstoneWireBlock.POWER; +import static net.minecraft.world.level.block.RedStoneWireBlock.POWER; -@Mixin(RedstoneWireBlock.class) +@Mixin(RedStoneWireBlock.class) public abstract class RedstoneWireBlockMixin implements RedstoneWireBlockInterface { @Shadow - private void update(World world_1, BlockPos blockPos_1, BlockState blockState_1) { } + private void updatePowerStrength(Level world_1, BlockPos blockPos_1, BlockState blockState_1) { } @Shadow - private int getReceivedRedstonePower(World world, BlockPos pos) { return 0; } + private int calculateTargetStrength(Level world, BlockPos pos) { return 0; } @Override - @Accessor("wiresGivePower") + @Accessor("shouldSignal") public abstract void setWiresGivePower(boolean wiresGivePower); @Override - @Accessor("wiresGivePower") + @Accessor("shouldSignal") public abstract boolean getWiresGivePower(); // = @@ -48,27 +49,27 @@ public abstract class RedstoneWireBlockMixin implements RedstoneWireBlockInterfa private RedstoneWireTurbo wireTurbo = null; @Inject(method = "", at = @At("RETURN")) - private void onRedstoneWireBlockCTOR(Block.Settings settings, CallbackInfo ci) { + private void onRedstoneWireBlockCTOR(BlockBehaviour.Properties settings, CallbackInfo ci) { //noinspection ConstantConditions - wireTurbo = new RedstoneWireTurbo((RedstoneWireBlock) (Object) this); + wireTurbo = new RedstoneWireTurbo((RedStoneWireBlock) (Object) this); } // = - public void fastUpdate(World world, BlockPos pos, BlockState state, BlockPos source) { + public void fastUpdate(Level world, BlockPos pos, BlockState state, BlockPos source) { // [CM] fastRedstoneDust -- update based on carpet rule if (CarpetSettings.fastRedstoneDust) { wireTurbo.updateSurroundingRedstone(world, pos, state, source); return; } - update(world, pos, state); + updatePowerStrength(world, pos, state); } /** * @author theosib, soykaf, gnembon */ - @Inject(method = "update", at = @At("HEAD"), cancellable = true) - private void updateLogicAlternative(World world, BlockPos pos, BlockState state, CallbackInfo cir) { + @Inject(method = "updatePowerStrength", at = @At("HEAD"), cancellable = true) + private void updateLogicAlternative(Level world, BlockPos pos, BlockState state, CallbackInfo cir) { if (CarpetSettings.fastRedstoneDust) { updateLogicPublic(world, pos, state); cir.cancel(); @@ -76,13 +77,13 @@ public abstract class RedstoneWireBlockMixin implements RedstoneWireBlockInterfa } @Override - public BlockState updateLogicPublic(World world_1, BlockPos blockPos_1, BlockState blockState_1) { - int i = this.getReceivedRedstonePower(world_1, blockPos_1); + public BlockState updateLogicPublic(Level world_1, BlockPos blockPos_1, BlockState blockState_1) { + int i = this.calculateTargetStrength(world_1, blockPos_1); BlockState blockState = blockState_1; - if (blockState_1.get(POWER) != i) { - blockState_1 = blockState_1.with(POWER, i); + if (blockState_1.getValue(POWER) != i) { + blockState_1 = blockState_1.setValue(POWER, i); if (world_1.getBlockState(blockPos_1) == blockState) { - world_1.setBlockState(blockPos_1, blockState_1, 2); + world_1.setBlock(blockPos_1, blockState_1, 2); } if (!CarpetSettings.fastRedstoneDust) { @@ -93,14 +94,14 @@ public abstract class RedstoneWireBlockMixin implements RedstoneWireBlockInterfa for (int var8 = 0; var8 < var7; ++var8) { Direction direction = var6[var8]; - set.add(blockPos_1.offset(direction)); + set.add(blockPos_1.relative(direction)); } Iterator var10 = set.iterator(); while (var10.hasNext()) { BlockPos blockPos = (BlockPos) var10.next(); - world_1.updateNeighborsAlways(blockPos, blockState_1.getBlock()); + world_1.updateNeighborsAt(blockPos, blockState_1.getBlock()); } } } @@ -110,24 +111,24 @@ public abstract class RedstoneWireBlockMixin implements RedstoneWireBlockInterfa // = - @Redirect(method = "onBlockAdded", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/RedstoneWireBlock;update(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)V")) - private void redirectOnBlockAddedUpdate(RedstoneWireBlock self, World world_1, BlockPos blockPos_1, BlockState blockState_1) { + @Redirect(method = "onPlace", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/RedStoneWireBlock;updatePowerStrength(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) + private void redirectOnBlockAddedUpdate(RedStoneWireBlock self, Level world_1, BlockPos blockPos_1, BlockState blockState_1) { fastUpdate(world_1, blockPos_1, blockState_1, null); } - @Redirect(method = "onStateReplaced", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/RedstoneWireBlock;update(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)V")) - private void redirectOnStateReplacedUpdate(RedstoneWireBlock self, World world_1, BlockPos blockPos_1, BlockState blockState_1) { + @Redirect(method = "onRemove", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/RedStoneWireBlock;updatePowerStrength(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) + private void redirectOnStateReplacedUpdate(RedStoneWireBlock self, Level world_1, BlockPos blockPos_1, BlockState blockState_1) { fastUpdate(world_1, blockPos_1, blockState_1, null); } - @Redirect(method = "neighborUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/RedstoneWireBlock;update(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)V")) + @Redirect(method = "neighborChanged", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/RedStoneWireBlock;updatePowerStrength(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) private void redirectNeighborUpdateUpdate( - RedstoneWireBlock self, - World world_1, + RedStoneWireBlock self, + Level world_1, BlockPos blockPos_1, BlockState blockState_1, BlockState blockState_2, - World world_2, + Level world_2, BlockPos blockPos_2, Block block_1, BlockPos blockPos_3, diff --git a/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java b/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java index ef5a8644..8123732b 100644 --- a/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java +++ b/src/main/java/carpet/mixins/ReloadCommand_reloadAppsMixin.java @@ -2,8 +2,8 @@ package carpet.mixins; import carpet.CarpetServer; import com.mojang.brigadier.context.CommandContext; -import net.minecraft.server.command.ReloadCommand; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.server.commands.ReloadCommand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -14,8 +14,8 @@ public class ReloadCommand_reloadAppsMixin { //method_13530(Lcom/mojang/brigadier/context/CommandContext;)I // internal of register. @SuppressWarnings("UnresolvedMixinReference") - @Inject(method = "method_13530", at = @At("TAIL")) - private static void onReload(CommandContext context, CallbackInfoReturnable cir) + @Inject(method = "lambda$register$2", at = @At("TAIL")) + private static void onReload(CommandContext context, CallbackInfoReturnable cir) { // can't fetch here the reference to the server CarpetServer.onReload(context.getSource().getServer()); diff --git a/src/main/java/carpet/mixins/RenderTickCounter_tickSpeedMixin.java b/src/main/java/carpet/mixins/RenderTickCounter_tickSpeedMixin.java index 7eae7f22..038d54fa 100644 --- a/src/main/java/carpet/mixins/RenderTickCounter_tickSpeedMixin.java +++ b/src/main/java/carpet/mixins/RenderTickCounter_tickSpeedMixin.java @@ -1,19 +1,19 @@ package carpet.mixins; import carpet.helpers.TickSpeed; +import net.minecraft.client.Timer; import carpet.CarpetSettings; -import net.minecraft.client.render.RenderTickCounter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(RenderTickCounter.class) +@Mixin(Timer.class) public class RenderTickCounter_tickSpeedMixin { - @Redirect(method = "beginRenderTick", at = @At( + @Redirect(method = "advanceTime", at = @At( value = "FIELD", - target = "Lnet/minecraft/client/render/RenderTickCounter;tickTime:F" + target = "Lnet/minecraft/client/Timer;msPerTick:F" )) - private float adjustTickSpeed(RenderTickCounter counter) { + private float adjustTickSpeed(Timer counter) { if (CarpetSettings.smoothClientAnimations && TickSpeed.process_entities) { return Math.max(50.0f, TickSpeed.mspt); diff --git a/src/main/java/carpet/mixins/SaplingBlockMixin.java b/src/main/java/carpet/mixins/SaplingBlockMixin.java index 5b1b8425..58a7085a 100644 --- a/src/main/java/carpet/mixins/SaplingBlockMixin.java +++ b/src/main/java/carpet/mixins/SaplingBlockMixin.java @@ -2,30 +2,30 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.BlockSaplingHelper; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.SaplingBlock; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.biome.Biome; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SaplingBlock; +import net.minecraft.world.level.block.state.BlockState; @Mixin(SaplingBlock.class) public abstract class SaplingBlockMixin { - @Inject(method = "generate", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Lnet/minecraft/block/sapling/SaplingGenerator;generate(Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/gen/chunk/ChunkGenerator;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Ljava/util/Random;)Z"), + @Inject(method = "advanceTree", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, + target = "Lnet/minecraft/world/level/block/grower/AbstractTreeGrower;growTree(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkGenerator;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Ljava/util/Random;)Z"), cancellable = true) - private void onGenerate(ServerWorld serverWorld_1, BlockPos blockPos_1, BlockState blockState_1, Random random_1, CallbackInfo ci) + private void onGenerate(ServerLevel serverWorld_1, BlockPos blockPos_1, BlockState blockState_1, Random random_1, CallbackInfo ci) { - if(CarpetSettings.desertShrubs && serverWorld_1.getBiome(blockPos_1).getCategory() == Biome.Category.DESERT && !BlockSaplingHelper.hasWater(serverWorld_1, blockPos_1)) + if(CarpetSettings.desertShrubs && serverWorld_1.getBiome(blockPos_1).getBiomeCategory() == Biome.BiomeCategory.DESERT && !BlockSaplingHelper.hasWater(serverWorld_1, blockPos_1)) { - serverWorld_1.setBlockState(blockPos_1, Blocks.DEAD_BUSH.getDefaultState(), 3); + serverWorld_1.setBlock(blockPos_1, Blocks.DEAD_BUSH.defaultBlockState(), 3); ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java b/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java index 78cd63dc..fc1bc655 100644 --- a/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ScoreboardObjective_scarpetMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; -import net.minecraft.scoreboard.ScoreboardCriterion; -import net.minecraft.scoreboard.ScoreboardObjective; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(ScoreboardObjective.class) +@Mixin(Objective.class) public interface ScoreboardObjective_scarpetMixin { - @Mutable @Accessor("criterion") - void setCriterion(ScoreboardCriterion criterion); + @Mutable @Accessor("criteria") + void setCriterion(ObjectiveCriteria criterion); } diff --git a/src/main/java/carpet/mixins/Scoreboard_scarpetMixin.java b/src/main/java/carpet/mixins/Scoreboard_scarpetMixin.java index 646e2ee7..5ac2eaff 100644 --- a/src/main/java/carpet/mixins/Scoreboard_scarpetMixin.java +++ b/src/main/java/carpet/mixins/Scoreboard_scarpetMixin.java @@ -1,16 +1,16 @@ package carpet.mixins; -import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.scoreboard.ScoreboardCriterion; -import net.minecraft.scoreboard.ScoreboardObjective; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import java.util.List; import java.util.Map; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; @Mixin(Scoreboard.class) public interface Scoreboard_scarpetMixin { - @Accessor("objectivesByCriterion") - Map> getObjectivesByCriterion(); + @Accessor("objectivesByCriteria") + Map> getObjectivesByCriterion(); } diff --git a/src/main/java/carpet/mixins/ScreenHandlerSubclasses_scarpetMixin.java b/src/main/java/carpet/mixins/ScreenHandlerSubclasses_scarpetMixin.java index b1227cec..81c21334 100644 --- a/src/main/java/carpet/mixins/ScreenHandlerSubclasses_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ScreenHandlerSubclasses_scarpetMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; import carpet.fakes.ScreenHandlerInterface; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.screen.EnchantmentScreenHandler; -import net.minecraft.screen.LecternScreenHandler; -import net.minecraft.screen.LoomScreenHandler; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerType; -import net.minecraft.screen.StonecutterScreenHandler; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.EnchantmentMenu; +import net.minecraft.world.inventory.LecternMenu; +import net.minecraft.world.inventory.LoomMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.inventory.StonecutterMenu; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -15,14 +15,14 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; //classes that override onButtonClick -@Mixin({EnchantmentScreenHandler.class, LecternScreenHandler.class, LoomScreenHandler.class, StonecutterScreenHandler.class}) -public abstract class ScreenHandlerSubclasses_scarpetMixin extends ScreenHandler { - protected ScreenHandlerSubclasses_scarpetMixin(ScreenHandlerType type, int syncId) { +@Mixin({EnchantmentMenu.class, LecternMenu.class, LoomMenu.class, StonecutterMenu.class}) +public abstract class ScreenHandlerSubclasses_scarpetMixin extends AbstractContainerMenu { + protected ScreenHandlerSubclasses_scarpetMixin(MenuType type, int syncId) { super(type, syncId); } - @Inject(method = "onButtonClick", at = @At("HEAD"), cancellable = true) - private void buttonClickCallback(PlayerEntity player, int id, CallbackInfoReturnable cir) { + @Inject(method = "clickMenuButton", at = @At("HEAD"), cancellable = true) + private void buttonClickCallback(Player player, int id, CallbackInfoReturnable cir) { if(((ScreenHandlerInterface) this).callButtonClickListener(id,player)) cir.cancel(); } diff --git a/src/main/java/carpet/mixins/ScreenHandler_scarpetMixin.java b/src/main/java/carpet/mixins/ScreenHandler_scarpetMixin.java index e56515a1..b43d9ae0 100644 --- a/src/main/java/carpet/mixins/ScreenHandler_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ScreenHandler_scarpetMixin.java @@ -3,13 +3,6 @@ package carpet.mixins; import carpet.fakes.ScreenHandlerInterface; import carpet.script.value.ScreenValue; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.recipe.Recipe; -import net.minecraft.screen.Property; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerListener; -import net.minecraft.screen.slot.SlotActionType; -import net.minecraft.server.network.ServerPlayerEntity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -18,31 +11,38 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.ContainerListener; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.item.crafting.Recipe; -@Mixin(ScreenHandler.class) +@Mixin(AbstractContainerMenu.class) public abstract class ScreenHandler_scarpetMixin implements ScreenHandlerInterface { - @Shadow @Final private List listeners; - @Shadow public abstract void syncState(); - @Shadow @Final private List properties; + @Shadow @Final private List containerListeners; + @Shadow public abstract void sendAllDataToRemote(); + @Shadow @Final private List dataSlots; - @Inject(method = "internalOnSlotClick", at = @At("HEAD"), cancellable = true) - private void callSlotClickListener(int slotIndex, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { - if(!(player instanceof ServerPlayerEntity serverPlayerEntity)) return; - for(ScreenHandlerListener screenHandlerListener : this.listeners) { + @Inject(method = "doClick", at = @At("HEAD"), cancellable = true) + private void callSlotClickListener(int slotIndex, int button, ClickType actionType, Player player, CallbackInfo ci) { + if(!(player instanceof ServerPlayer serverPlayerEntity)) return; + for(ContainerListener screenHandlerListener : this.containerListeners) { if(screenHandlerListener instanceof ScreenValue.ScarpetScreenHandlerListener scarpetScreenHandlerListener) { if(scarpetScreenHandlerListener.onSlotClick(serverPlayerEntity, actionType, slotIndex, button)) { ci.cancel(); - syncState(); + sendAllDataToRemote(); } } } } - @Inject(method = "close", at = @At("HEAD"), cancellable = true) - private void callCloseListener(PlayerEntity player, CallbackInfo ci) { - if(!(player instanceof ServerPlayerEntity serverPlayerEntity)) return; - for(ScreenHandlerListener screenHandlerListener : this.listeners) { + @Inject(method = "removed", at = @At("HEAD"), cancellable = true) + private void callCloseListener(Player player, CallbackInfo ci) { + if(!(player instanceof ServerPlayer serverPlayerEntity)) return; + for(ContainerListener screenHandlerListener : this.containerListeners) { if(screenHandlerListener instanceof ScreenValue.ScarpetScreenHandlerListener scarpetScreenHandlerListener) { scarpetScreenHandlerListener.onClose(serverPlayerEntity); } @@ -50,9 +50,9 @@ public abstract class ScreenHandler_scarpetMixin implements ScreenHandlerInterfa } @Override - public boolean callButtonClickListener(int button, PlayerEntity player) { - if(!(player instanceof ServerPlayerEntity serverPlayerEntity)) return false; - for(ScreenHandlerListener screenHandlerListener : listeners) { + public boolean callButtonClickListener(int button, Player player) { + if(!(player instanceof ServerPlayer serverPlayerEntity)) return false; + for(ContainerListener screenHandlerListener : containerListeners) { if(screenHandlerListener instanceof ScreenValue.ScarpetScreenHandlerListener scarpetScreenHandlerListener) { if(scarpetScreenHandlerListener.onButtonClick(serverPlayerEntity, button)) return true; @@ -62,8 +62,8 @@ public abstract class ScreenHandler_scarpetMixin implements ScreenHandlerInterfa } @Override - public boolean callSelectRecipeListener(ServerPlayerEntity player, Recipe recipe, boolean craftAll) { - for(ScreenHandlerListener screenHandlerListener : listeners) { + public boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, boolean craftAll) { + for(ContainerListener screenHandlerListener : containerListeners) { if(screenHandlerListener instanceof ScreenValue.ScarpetScreenHandlerListener scarpetScreenHandlerListener) { if(scarpetScreenHandlerListener.onSelectRecipe(player, recipe, craftAll)) return true; @@ -73,7 +73,7 @@ public abstract class ScreenHandler_scarpetMixin implements ScreenHandlerInterfa } @Override - public Property getProperty(int index) { - return this.properties.get(index); + public DataSlot getProperty(int index) { + return this.dataSlots.get(index); } } \ No newline at end of file diff --git a/src/main/java/carpet/mixins/ScreenHandler_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/ScreenHandler_stackableSBoxesMixin.java index 87e55966..874db190 100644 --- a/src/main/java/carpet/mixins/ScreenHandler_stackableSBoxesMixin.java +++ b/src/main/java/carpet/mixins/ScreenHandler_stackableSBoxesMixin.java @@ -2,21 +2,21 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.InventoryHelper; -import net.minecraft.block.ShulkerBoxBlock; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.ShulkerBoxBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(ScreenHandler.class) +@Mixin(AbstractContainerMenu.class) public class ScreenHandler_stackableSBoxesMixin { - @Redirect(method = "internalOnSlotClick", at = @At( + @Redirect(method = "doClick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/screen/slot/Slot;getMaxItemCount(Lnet/minecraft/item/ItemStack;)I" + target = "Lnet/minecraft/world/inventory/Slot;getMaxStackSize(Lnet/minecraft/world/item/ItemStack;)I" )) private int getMaxCountForSboxesInScreenHander(Slot slot, ItemStack stack) { @@ -28,6 +28,6 @@ public class ScreenHandler_stackableSBoxesMixin { return CarpetSettings.shulkerBoxStackSize; } - return slot.getMaxItemCount(stack); + return slot.getMaxStackSize(stack); } } diff --git a/src/main/java/carpet/mixins/ServerChunkManagerMixin.java b/src/main/java/carpet/mixins/ServerChunkManagerMixin.java index 921856a8..93e940c1 100644 --- a/src/main/java/carpet/mixins/ServerChunkManagerMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkManagerMixin.java @@ -2,13 +2,6 @@ package carpet.mixins; import carpet.fakes.ServerChunkManagerInterface; import carpet.utils.SpawnReporter; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.server.world.ChunkTicketManager; -import net.minecraft.server.world.ServerChunkManager; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; -import net.minecraft.world.WorldProperties; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -20,29 +13,36 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.HashMap; import java.util.HashSet; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.LevelData; -@Mixin(ServerChunkManager.class) +@Mixin(ServerChunkCache.class) public abstract class ServerChunkManagerMixin implements ServerChunkManagerInterface { - @Shadow @Final private ServerWorld world; + @Shadow @Final private ServerLevel level; - @Shadow @Final private ChunkTicketManager ticketManager; + @Shadow @Final private DistanceManager distanceManager; @Override // shared between scarpet and spawnChunks setting - public ChunkTicketManager getCMTicketManager() + public DistanceManager getCMTicketManager() { - return ticketManager; + return distanceManager; } @Redirect(method = "tickChunks", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ChunkTicketManager;getTickedChunkCount()I" + target = "Lnet/minecraft/server/level/DistanceManager;getNaturalSpawnChunkCount()I" )) //this runs once per world spawning cycle. Allows to grab mob counts and count spawn ticks - private int setupTracking(ChunkTicketManager chunkTicketManager) + private int setupTracking(DistanceManager chunkTicketManager) { - int j = chunkTicketManager.getTickedChunkCount(); - RegistryKey dim = this.world.getRegistryKey(); // getDimensionType; + int j = chunkTicketManager.getNaturalSpawnChunkCount(); + ResourceKey dim = this.level.dimension(); // getDimensionType; //((WorldInterface)world).getPrecookedMobs().clear(); not needed because mobs are compared with predefined BBs SpawnReporter.chunkCounts.put(dim, j); @@ -51,7 +51,7 @@ public abstract class ServerChunkManagerMixin implements ServerChunkManagerInter //local spawns now need to be tracked globally cause each calll is just for chunk SpawnReporter.local_spawns = new HashMap<>(); SpawnReporter.first_chunk_marker = new HashSet<>(); - for (SpawnGroup cat : SpawnGroup.values()) + for (MobCategory cat : MobCategory.values()) { Pair key = Pair.of(dim, cat); SpawnReporter.overall_spawn_ticks.put(key, @@ -66,18 +66,18 @@ public abstract class ServerChunkManagerMixin implements ServerChunkManagerInter @Inject(method = "tickChunks", at = @At("RETURN")) private void onFinishSpawnWorldCycle(CallbackInfo ci) { - WorldProperties levelProperties_1 = this.world.getLevelProperties(); // levelProperies class - boolean boolean_3 = levelProperties_1.getTime() % 400L == 0L; + LevelData levelProperties_1 = this.level.getLevelData(); // levelProperies class + boolean boolean_3 = levelProperties_1.getGameTime() % 400L == 0L; if (SpawnReporter.track_spawns > 0L && SpawnReporter.local_spawns != null) { - for (SpawnGroup cat: SpawnGroup.values()) + for (MobCategory cat: MobCategory.values()) { - RegistryKey dim = world.getRegistryKey(); // getDimensionType; + ResourceKey dim = level.dimension(); // getDimensionType; Pair key = Pair.of(dim, cat); int spawnTries = SpawnReporter.spawn_tries.get(cat); if (!SpawnReporter.local_spawns.containsKey(cat)) { - if (!cat.isRare() || boolean_3) // isAnimal + if (!cat.isPersistent() || boolean_3) // isAnimal { // fill mobcaps for that category so spawn got cancelled SpawnReporter.spawn_ticks_full.put(key, diff --git a/src/main/java/carpet/mixins/ServerChunkManager_tickMixin.java b/src/main/java/carpet/mixins/ServerChunkManager_tickMixin.java index 26fd34ac..ddb5ad8c 100644 --- a/src/main/java/carpet/mixins/ServerChunkManager_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkManager_tickMixin.java @@ -3,12 +3,6 @@ package carpet.mixins; import carpet.fakes.ThreadedAnvilChunkStorageInterface; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ServerChunkManager; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.server.world.ThreadedAnvilChunkStorage; -import net.minecraft.world.chunk.WorldChunk; - import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -20,24 +14,28 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Collections; import java.util.List; import java.util.Optional; - +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.chunk.LevelChunk; import com.google.common.collect.Lists; -@Mixin(ServerChunkManager.class) +@Mixin(ServerChunkCache.class) public abstract class ServerChunkManager_tickMixin { - @Shadow @Final private ServerWorld world; + @Shadow @Final private ServerLevel level; @Shadow @Final - public ThreadedAnvilChunkStorage threadedAnvilChunkStorage; + public ChunkMap chunkMap; CarpetProfiler.ProfilerToken currentSection; @Inject(method = "tickChunks", at = @At("HEAD")) private void startSpawningSection(CallbackInfo ci) { - currentSection = CarpetProfiler.start_section(world, "Spawning and Random Ticks", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section(level, "Spawning and Random Ticks", CarpetProfiler.TYPE.GENERAL); } @Inject(method = "tickChunks", at = @At("RETURN")) @@ -52,22 +50,22 @@ public abstract class ServerChunkManager_tickMixin //// Tick freeze @Redirect(method = "tickChunks", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;isDebugWorld()Z" + target = "Lnet/minecraft/server/level/ServerLevel;isDebug()Z" )) - private boolean skipChunkTicking(ServerWorld serverWorld) + private boolean skipChunkTicking(ServerLevel serverWorld) { - boolean debug = serverWorld.isDebugWorld(); + boolean debug = serverWorld.isDebug(); if (!TickSpeed.process_entities) { // simplified chunk tick iteration assuming world is frozen otherwise as suggested by Hadron67 // to be kept in sync with the original injection source if (!debug){ - List holders = Lists.newArrayList(((ThreadedAnvilChunkStorageInterface)threadedAnvilChunkStorage).getChunksCM()); + List holders = Lists.newArrayList(((ThreadedAnvilChunkStorageInterface)chunkMap).getChunksCM()); Collections.shuffle(holders); for (ChunkHolder holder: holders){ - Optional optional = holder.getTickingFuture().getNow(ChunkHolder.UNLOADED_WORLD_CHUNK).left(); + Optional optional = holder.getTickingChunkFuture().getNow(ChunkHolder.UNLOADED_LEVEL_CHUNK).left(); if (optional.isPresent()){ - holder.flushUpdates(optional.get()); + holder.broadcastChanges(optional.get()); } } } diff --git a/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java b/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java index bdf7327e..aa76162b 100644 --- a/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerEntityManager_scarpetMixin.java @@ -2,22 +2,22 @@ package carpet.mixins; import carpet.script.CarpetEventServer; import carpet.script.CarpetScriptServer; -import net.minecraft.entity.Entity; -import net.minecraft.server.world.ServerEntityManager; -import net.minecraft.world.entity.EntityLike; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.entity.EntityAccess; +import net.minecraft.world.level.entity.PersistentEntitySectionManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(ServerEntityManager.class) +@Mixin(PersistentEntitySectionManager.class) public class ServerEntityManager_scarpetMixin { - @Inject(method = "addEntity(Lnet/minecraft/world/entity/EntityLike;Z)Z", at = @At( + @Inject(method = "addEntity(Lnet/minecraft/world/level/entity/EntityAccess;Z)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/entity/EntityTrackingStatus;shouldTick()Z" + target = "Lnet/minecraft/world/level/entity/Visibility;isTicking()Z" )) - private void handleAddedEntity(EntityLike entityLike, boolean existing, CallbackInfoReturnable cir) + private void handleAddedEntity(EntityAccess entityLike, boolean existing, CallbackInfoReturnable cir) { Entity entity = (Entity)entityLike; CarpetEventServer.Event event = CarpetEventServer.Event.ENTITY_HANDLER.get(entity.getType()); @@ -30,7 +30,7 @@ public class ServerEntityManager_scarpetMixin } else { - CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getTranslationKey()); + CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getDescriptionId()); } event = CarpetEventServer.Event.ENTITY_LOAD.get(entity.getType()); @@ -43,7 +43,7 @@ public class ServerEntityManager_scarpetMixin } else { - CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getTranslationKey()); + CarpetScriptServer.LOG.error("Failed to handle entity type " + entity.getType().getDescriptionId()); } } diff --git a/src/main/java/carpet/mixins/ServerLightingProvider_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ServerLightingProvider_scarpetChunkCreationMixin.java index 1b6525dd..fd3bab2c 100644 --- a/src/main/java/carpet/mixins/ServerLightingProvider_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ServerLightingProvider_scarpetChunkCreationMixin.java @@ -2,7 +2,15 @@ package carpet.mixins; import java.util.concurrent.CompletableFuture; import java.util.function.IntSupplier; - +import net.minecraft.Util; +import net.minecraft.core.SectionPos; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.server.level.ThreadedLevelLightEngine.TaskType; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LightChunkGetter; +import net.minecraft.world.level.lighting.LevelLightEngine; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,74 +19,65 @@ import org.spongepowered.asm.mixin.gen.Invoker; import carpet.fakes.Lighting_scarpetChunkCreationInterface; import carpet.fakes.ServerLightingProviderInterface; import carpet.fakes.ThreadedAnvilChunkStorageInterface; -import net.minecraft.server.world.ServerLightingProvider; -import net.minecraft.server.world.ServerLightingProvider.Stage; -import net.minecraft.server.world.ThreadedAnvilChunkStorage; -import net.minecraft.util.Util; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkProvider; -import net.minecraft.world.chunk.light.LightingProvider; -@Mixin(ServerLightingProvider.class) -public abstract class ServerLightingProvider_scarpetChunkCreationMixin extends LightingProvider implements ServerLightingProviderInterface +@Mixin(ThreadedLevelLightEngine.class) +public abstract class ServerLightingProvider_scarpetChunkCreationMixin extends LevelLightEngine implements ServerLightingProviderInterface { - private ServerLightingProvider_scarpetChunkCreationMixin(final ChunkProvider chunkProvider, final boolean hasBlockLight, final boolean hasSkyLight) + private ServerLightingProvider_scarpetChunkCreationMixin(final LightChunkGetter chunkProvider, final boolean hasBlockLight, final boolean hasSkyLight) { super(chunkProvider, hasBlockLight, hasSkyLight); } @Shadow - protected abstract void enqueue(final int x, final int z, final IntSupplier completedLevelSupplier, final Stage stage, final Runnable task); + protected abstract void addTask(final int x, final int z, final IntSupplier completedLevelSupplier, final TaskType stage, final Runnable task); @Shadow @Final - private ThreadedAnvilChunkStorage chunkStorage; + private ChunkMap chunkMap; @Override @Invoker("updateChunkStatus") public abstract void invokeUpdateChunkStatus(ChunkPos pos); @Override - public void removeLightData(final Chunk chunk) + public void removeLightData(final ChunkAccess chunk) { final ChunkPos pos = chunk.getPos(); - chunk.setLightOn(false); + chunk.setLightCorrect(false); - this.enqueue(pos.x, pos.z, () -> 0, ServerLightingProvider.Stage.PRE_UPDATE, Util.debugRunnable(() -> { - super.setColumnEnabled(pos, false); - ((Lighting_scarpetChunkCreationInterface) this).removeLightData(ChunkSectionPos.withZeroY(ChunkSectionPos.asLong(pos.x, 0, pos.z))); + this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { + super.enableLightSources(pos, false); + ((Lighting_scarpetChunkCreationInterface) this).removeLightData(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z))); }, () -> "Remove light data " + pos )); } @Override - public CompletableFuture relight(final Chunk chunk) + public CompletableFuture relight(final ChunkAccess chunk) { final ChunkPos pos = chunk.getPos(); - this.enqueue(pos.x, pos.z, () -> 0, ServerLightingProvider.Stage.PRE_UPDATE, Util.debugRunnable(() -> { - super.setColumnEnabled(pos, true); + this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { + super.enableLightSources(pos, true); - chunk.getLightSourcesStream().forEach( - blockPos -> super.addLightSource(blockPos, chunk.getLuminance(blockPos)) + chunk.getLights().forEach( + blockPos -> super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos)) ); - ((Lighting_scarpetChunkCreationInterface) this).relight(ChunkSectionPos.withZeroY(ChunkSectionPos.asLong(pos.x, 0, pos.z))); + ((Lighting_scarpetChunkCreationInterface) this).relight(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z))); }, () -> "Relight chunk " + pos )); return CompletableFuture.runAsync( - Util.debugRunnable(() -> { - chunk.setLightOn(true); - ((ThreadedAnvilChunkStorageInterface) this.chunkStorage).releaseRelightTicket(pos); + Util.name(() -> { + chunk.setLightCorrect(true); + ((ThreadedAnvilChunkStorageInterface) this.chunkMap).releaseRelightTicket(pos); }, () -> "Release relight ticket " + pos ), - runnable -> this.enqueue(pos.x, pos.z, () -> 0, ServerLightingProvider.Stage.POST_UPDATE, runnable) + runnable -> this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.POST_UPDATE, runnable) ); } } diff --git a/src/main/java/carpet/mixins/ServerLightingProvider_scarpetMixin.java b/src/main/java/carpet/mixins/ServerLightingProvider_scarpetMixin.java index f86675d8..7ba1d418 100644 --- a/src/main/java/carpet/mixins/ServerLightingProvider_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerLightingProvider_scarpetMixin.java @@ -1,30 +1,30 @@ package carpet.mixins; import carpet.fakes.ServerLightingProviderInterface; -import net.minecraft.server.world.ServerLightingProvider; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.world.LightType; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkNibbleArray; -import net.minecraft.world.chunk.ChunkProvider; -import net.minecraft.world.chunk.light.LightingProvider; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.chunk.LightChunkGetter; +import net.minecraft.world.level.lighting.LevelLightEngine; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(ServerLightingProvider.class) -public abstract class ServerLightingProvider_scarpetMixin extends LightingProvider implements ServerLightingProviderInterface +@Mixin(ThreadedLevelLightEngine.class) +public abstract class ServerLightingProvider_scarpetMixin extends LevelLightEngine implements ServerLightingProviderInterface { @Shadow public abstract void checkBlock(BlockPos pos); - public ServerLightingProvider_scarpetMixin(ChunkProvider chunkProvider, boolean hasBlockLight, boolean hasSkyLight) + public ServerLightingProvider_scarpetMixin(LightChunkGetter chunkProvider, boolean hasBlockLight, boolean hasSkyLight) { super(chunkProvider, hasBlockLight, hasSkyLight); } @Override - public void resetLight(Chunk chunk, ChunkPos pos) + public void resetLight(ChunkAccess chunk, ChunkPos pos) { //super.setRetainData(pos, false); //super.setLightEnabled(pos, false); @@ -34,17 +34,17 @@ public abstract class ServerLightingProvider_scarpetMixin extends LightingProvid //ChunkPos pos = new ChunkPos(x, z); int j; for(j = -1; j < 17; ++j) { // skip some recomp - super.enqueueSectionData(LightType.BLOCK, ChunkSectionPos.from(pos, j), new ChunkNibbleArray(), false); - super.enqueueSectionData(LightType.SKY, ChunkSectionPos.from(pos, j), new ChunkNibbleArray(), false); + super.queueSectionData(LightLayer.BLOCK, SectionPos.of(pos, j), new DataLayer(), false); + super.queueSectionData(LightLayer.SKY, SectionPos.of(pos, j), new DataLayer(), false); } for(j = 0; j < 16; ++j) { - super.setSectionStatus(ChunkSectionPos.from(pos, j), true); + super.updateSectionStatus(SectionPos.of(pos, j), true); } - super.setColumnEnabled(pos, true); + super.enableLightSources(pos, true); - chunk.getLightSourcesStream().forEach((blockPos) -> { - super.addLightSource(blockPos, chunk.getLuminance(blockPos)); + chunk.getLights().forEach((blockPos) -> { + super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos)); }); } diff --git a/src/main/java/carpet/mixins/ServerMetadata_motdMixin.java b/src/main/java/carpet/mixins/ServerMetadata_motdMixin.java index 666b729f..1aff6cad 100644 --- a/src/main/java/carpet/mixins/ServerMetadata_motdMixin.java +++ b/src/main/java/carpet/mixins/ServerMetadata_motdMixin.java @@ -1,23 +1,23 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.ServerMetadata; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.protocol.status.ServerStatus; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(ServerMetadata.class) +@Mixin(ServerStatus.class) public class ServerMetadata_motdMixin { @Inject(method = "getDescription", at = @At("HEAD"), cancellable = true) - private void getDescriptionAlternative(CallbackInfoReturnable cir) + private void getDescriptionAlternative(CallbackInfoReturnable cir) { if (!CarpetSettings.customMOTD.equals("_")) { - cir.setReturnValue(new LiteralText(CarpetSettings.customMOTD)); + cir.setReturnValue(new TextComponent(CarpetSettings.customMOTD)); cir.cancel(); } } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java index 7a6cbec6..6dc1c8bc 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java @@ -2,29 +2,29 @@ package carpet.mixins; import carpet.network.CarpetClient; import carpet.network.ServerNetworkHandler; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.c2s.play.CustomPayloadC2SPacket; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.Identifier; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ServerPlayNetworkHandler.class) +@Mixin(ServerGamePacketListenerImpl.class) public class ServerPlayNetworkHandlerMixin { - @Shadow public ServerPlayerEntity player; + @Shadow public ServerPlayer player; - @Inject(method = "onCustomPayload", at = @At("HEAD"), cancellable = true) - private void onCustomCarpetPayload(CustomPayloadC2SPacket packet, CallbackInfo ci) + @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) + private void onCustomCarpetPayload(ServerboundCustomPayloadPacket packet, CallbackInfo ci) { - Identifier channel = packet.getChannel(); + ResourceLocation channel = packet.getIdentifier(); if (CarpetClient.CARPET_CHANNEL.equals(channel)) { - ServerNetworkHandler.handleData(new PacketByteBuf(packet.getData().copy()), player); + ServerNetworkHandler.handleData(new FriendlyByteBuf(packet.getData().copy()), player); ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_antiCheatDisabledMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_antiCheatDisabledMixin.java index b7a616e8..2e8301d1 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_antiCheatDisabledMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_antiCheatDisabledMixin.java @@ -1,8 +1,8 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -10,41 +10,41 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ServerPlayNetworkHandler.class) +@Mixin(ServerGamePacketListenerImpl.class) public abstract class ServerPlayNetworkHandler_antiCheatDisabledMixin { - @Shadow private int floatingTicks; + @Shadow private int aboveGroundTickCount; - @Shadow private int vehicleFloatingTicks; + @Shadow private int aboveGroundVehicleTickCount; - @Shadow protected abstract boolean isHost(); + @Shadow protected abstract boolean isSingleplayerOwner(); @Inject(method = "tick", at = @At("HEAD")) private void restrictFloatingBits(CallbackInfo ci) { if (CarpetSettings.antiCheatDisabled) { - if (floatingTicks > 70) floatingTicks--; - if (vehicleFloatingTicks > 70) vehicleFloatingTicks--; + if (aboveGroundTickCount > 70) aboveGroundTickCount--; + if (aboveGroundVehicleTickCount > 70) aboveGroundVehicleTickCount--; } } - @Redirect(method = "onVehicleMove", at = @At( + @Redirect(method = "handleMoveVehicle", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;isHost()Z" + target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;isSingleplayerOwner()Z" )) - private boolean isServerTrusting(ServerPlayNetworkHandler serverPlayNetworkHandler) + private boolean isServerTrusting(ServerGamePacketListenerImpl serverPlayNetworkHandler) { - return isHost() || CarpetSettings.antiCheatDisabled; + return isSingleplayerOwner() || CarpetSettings.antiCheatDisabled; } - @Redirect(method = "onPlayerMove", require = 0, // don't crash with immersive portals, + @Redirect(method = "handleMovePlayer", require = 0, // don't crash with immersive portals, at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;isInTeleportationState()Z")) - private boolean relaxMoveRestrictions(ServerPlayerEntity serverPlayerEntity) + target = "Lnet/minecraft/server/level/ServerPlayer;isChangingDimension()Z")) + private boolean relaxMoveRestrictions(ServerPlayer serverPlayerEntity) { - return CarpetSettings.antiCheatDisabled || serverPlayerEntity.isInTeleportationState(); + return CarpetSettings.antiCheatDisabled || serverPlayerEntity.isChangingDimension(); } } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_coreMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_coreMixin.java index 313990f2..b7919f57 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_coreMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_coreMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; import carpet.CarpetServer; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -12,14 +12,14 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static carpet.script.CarpetEventServer.Event.PLAYER_DISCONNECTS; -@Mixin(ServerPlayNetworkHandler.class) +@Mixin(ServerGamePacketListenerImpl.class) public class ServerPlayNetworkHandler_coreMixin { @Shadow - public ServerPlayerEntity player; + public ServerPlayer player; - @Inject(method = "onDisconnected", at = @At("HEAD")) - private void onPlayerDisconnect(Text reason, CallbackInfo ci) { + @Inject(method = "onDisconnect", at = @At("HEAD")) + private void onPlayerDisconnect(Component reason, CallbackInfo ci) { CarpetServer.onPlayerLoggedOut(this.player); - if (PLAYER_DISCONNECTS.isNeeded()) PLAYER_DISCONNECTS.onPlayerMessage(player, reason.asString()); + if (PLAYER_DISCONNECTS.isNeeded()) PLAYER_DISCONNECTS.onPlayerMessage(player, reason.getContents()); } } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_interactionUpdatesMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_interactionUpdatesMixin.java index 5009f83d..85b5188a 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_interactionUpdatesMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_interactionUpdatesMixin.java @@ -1,78 +1,78 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInteractBlockC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInteractItemC2SPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ServerPlayNetworkHandler.class) +@Mixin(ServerGamePacketListenerImpl.class) public class ServerPlayNetworkHandler_interactionUpdatesMixin { - @Inject(method = "onPlayerInteractBlock", at = @At( + @Inject(method = "handleUseItemOn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;interactBlock(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;Lnet/minecraft/util/hit/BlockHitResult;)Lnet/minecraft/util/ActionResult;", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;useItemOn(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;", shift = At.Shift.BEFORE )) - private void beforeBlockInteracted(PlayerInteractBlockC2SPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) + private void beforeBlockInteracted(ServerboundUseItemOnPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); } - @Inject(method = "onPlayerInteractBlock", at = @At( + @Inject(method = "handleUseItemOn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;interactBlock(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;Lnet/minecraft/util/hit/BlockHitResult;)Lnet/minecraft/util/ActionResult;", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;useItemOn(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;", shift = At.Shift.AFTER )) - private void afterBlockInteracted(PlayerInteractBlockC2SPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) + private void afterBlockInteracted(ServerboundUseItemOnPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(false); } - @Inject(method = "onPlayerInteractItem", at = @At( + @Inject(method = "handleUseItem", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;interactItem(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;)Lnet/minecraft/util/ActionResult;", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;useItem(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResult;", shift = At.Shift.BEFORE )) - private void beforeItemInteracted(PlayerInteractItemC2SPacket packet, CallbackInfo ci) + private void beforeItemInteracted(ServerboundUseItemPacket packet, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); } - @Inject(method = "onPlayerInteractItem", at = @At( + @Inject(method = "handleUseItem", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;interactItem(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;)Lnet/minecraft/util/ActionResult;", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;useItem(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResult;", shift = At.Shift.AFTER )) - private void afterItemInteracted(PlayerInteractItemC2SPacket packet, CallbackInfo ci) + private void afterItemInteracted(ServerboundUseItemPacket packet, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(false); } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;processBlockBreakingAction(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/network/packet/c2s/play/PlayerActionC2SPacket$Action;Lnet/minecraft/util/math/Direction;I)V", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;handleBlockBreakAction(Lnet/minecraft/core/BlockPos;Lnet/minecraft/network/protocol/game/ServerboundPlayerActionPacket$Action;Lnet/minecraft/core/Direction;I)V", shift = At.Shift.BEFORE )) - private void beforeBlockBroken(PlayerActionC2SPacket packet, CallbackInfo ci) + private void beforeBlockBroken(ServerboundPlayerActionPacket packet, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target ="Lnet/minecraft/server/network/ServerPlayerInteractionManager;processBlockBreakingAction(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/network/packet/c2s/play/PlayerActionC2SPacket$Action;Lnet/minecraft/util/math/Direction;I)V", + target ="Lnet/minecraft/server/level/ServerPlayerGameMode;handleBlockBreakAction(Lnet/minecraft/core/BlockPos;Lnet/minecraft/network/protocol/game/ServerboundPlayerActionPacket$Action;Lnet/minecraft/core/Direction;I)V", shift = At.Shift.AFTER )) - private void afterBlockBroken(PlayerActionC2SPacket packet, CallbackInfo ci) + private void afterBlockBroken(ServerboundPlayerActionPacket packet, CallbackInfo ci) { if (!CarpetSettings.interactionUpdates) CarpetSettings.impendingFillSkipUpdates.set(false); diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java index 49f81043..630155c7 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java @@ -1,21 +1,5 @@ package carpet.mixins; -import net.minecraft.item.ItemStack; -import net.minecraft.network.packet.c2s.play.ButtonClickC2SPacket; -import net.minecraft.network.packet.c2s.play.CraftRequestC2SPacket; -import net.minecraft.network.packet.c2s.play.HandSwingC2SPacket; -import net.minecraft.network.packet.c2s.play.UpdateSelectedSlotC2SPacket; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInputC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInteractBlockC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerInteractItemC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -45,167 +29,183 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_SWITCHES_SLOT; import static carpet.script.CarpetEventServer.Event.PLAYER_USES_ITEM; import static carpet.script.CarpetEventServer.Event.PLAYER_WAKES_UP; +import net.minecraft.network.protocol.game.ServerboundContainerButtonClickPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlaceRecipePacket; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.BlockHitResult; -@Mixin(ServerPlayNetworkHandler.class) + +@Mixin(ServerGamePacketListenerImpl.class) public class ServerPlayNetworkHandler_scarpetEventsMixin { - @Shadow public ServerPlayerEntity player; + @Shadow public ServerPlayer player; - @Inject(method = "onPlayerInput", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateInput(FFZZ)V")) - private void checkMoves(PlayerInputC2SPacket p, CallbackInfo ci) + @Inject(method = "handlePlayerInput", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;setPlayerInput(FFZZ)V")) + private void checkMoves(ServerboundPlayerInputPacket p, CallbackInfo ci) { - if (PLAYER_RIDES.isNeeded() && (p.getSideways() != 0.0F || p.getForward() != 0.0F || p.isJumping() || p.isSneaking())) + if (PLAYER_RIDES.isNeeded() && (p.getXxa() != 0.0F || p.getZza() != 0.0F || p.isJumping() || p.isShiftKeyDown())) { - PLAYER_RIDES.onMountControls(player, p.getSideways(), p.getForward(), p.isJumping(), p.isSneaking()); + PLAYER_RIDES.onMountControls(player, p.getXxa(), p.getZza(), p.isJumping(), p.isShiftKeyDown()); } } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", // dropSelectedItem + target = "Lnet/minecraft/server/level/ServerPlayer;drop(Z)Z", // dropSelectedItem ordinal = 0, shift = At.Shift.BEFORE )) - private void onQItem(PlayerActionC2SPacket playerActionC2SPacket_1, CallbackInfo ci) + private void onQItem(ServerboundPlayerActionPacket playerActionC2SPacket_1, CallbackInfo ci) { PLAYER_DROPS_ITEM.onPlayerEvent(player); } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;getStackInHand(Lnet/minecraft/util/Hand;)Lnet/minecraft/item/ItemStack;", + target = "Lnet/minecraft/server/level/ServerPlayer;getItemInHand(Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/item/ItemStack;", ordinal = 0, shift = At.Shift.BEFORE )) - private void onHandSwap(PlayerActionC2SPacket playerActionC2SPacket_1, CallbackInfo ci) + private void onHandSwap(ServerboundPlayerActionPacket playerActionC2SPacket_1, CallbackInfo ci) { PLAYER_SWAPS_HANDS.onPlayerEvent(player); } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;dropSelectedItem(Z)Z", // dropSelectedItem + target = "Lnet/minecraft/server/level/ServerPlayer;drop(Z)Z", // dropSelectedItem ordinal = 1, shift = At.Shift.BEFORE )) - private void onCtrlQItem(PlayerActionC2SPacket playerActionC2SPacket_1, CallbackInfo ci) + private void onCtrlQItem(ServerboundPlayerActionPacket playerActionC2SPacket_1, CallbackInfo ci) { PLAYER_DROPS_STACK.onPlayerEvent(player); } - @Inject(method = "onPlayerMove", at = @At( + @Inject(method = "handleMovePlayer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;jump()V" + target = "Lnet/minecraft/server/level/ServerPlayer;jumpFromGround()V" )) - private void onJump(PlayerMoveC2SPacket playerMoveC2SPacket_1, CallbackInfo ci) + private void onJump(ServerboundMovePlayerPacket playerMoveC2SPacket_1, CallbackInfo ci) { PLAYER_JUMPS.onPlayerEvent(player); } - @Inject(method = "onPlayerAction", at = @At( + @Inject(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;processBlockBreakingAction(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/network/packet/c2s/play/PlayerActionC2SPacket$Action;Lnet/minecraft/util/math/Direction;I)V", + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;handleBlockBreakAction(Lnet/minecraft/core/BlockPos;Lnet/minecraft/network/protocol/game/ServerboundPlayerActionPacket$Action;Lnet/minecraft/core/Direction;I)V", shift = At.Shift.BEFORE )) - private void onClicked(PlayerActionC2SPacket packet, CallbackInfo ci) + private void onClicked(ServerboundPlayerActionPacket packet, CallbackInfo ci) { - if (packet.getAction() == PlayerActionC2SPacket.Action.START_DESTROY_BLOCK) + if (packet.getAction() == ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK) PLAYER_CLICKS_BLOCK.onBlockAction(player, packet.getPos(), packet.getDirection()); } - @Redirect(method = "onPlayerAction", at = @At( + @Redirect(method = "handlePlayerAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;stopUsingItem()V" + target = "Lnet/minecraft/server/level/ServerPlayer;releaseUsingItem()V" )) - private void onStopUsing(ServerPlayerEntity serverPlayerEntity) + private void onStopUsing(ServerPlayer serverPlayerEntity) { if (PLAYER_RELEASED_ITEM.isNeeded()) { - Hand hand = serverPlayerEntity.getActiveHand(); - ItemStack stack = serverPlayerEntity.getActiveItem().copy(); - serverPlayerEntity.stopUsingItem(); + InteractionHand hand = serverPlayerEntity.getUsedItemHand(); + ItemStack stack = serverPlayerEntity.getUseItem().copy(); + serverPlayerEntity.releaseUsingItem(); PLAYER_RELEASED_ITEM.onItemAction(player, hand, stack); } else { - serverPlayerEntity.stopUsingItem(); + serverPlayerEntity.releaseUsingItem(); } } - @Inject(method = "onPlayerInteractBlock", at = @At( + @Inject(method = "handleUseItemOn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerInteractionManager;interactBlock(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;Lnet/minecraft/util/hit/BlockHitResult;)Lnet/minecraft/util/ActionResult;" + target = "Lnet/minecraft/server/level/ServerPlayerGameMode;useItemOn(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;" )) - private void onBlockInteracted(PlayerInteractBlockC2SPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) + private void onBlockInteracted(ServerboundUseItemOnPacket playerInteractBlockC2SPacket_1, CallbackInfo ci) { if (PLAYER_RIGHT_CLICKS_BLOCK.isNeeded()) { - Hand hand = playerInteractBlockC2SPacket_1.getHand(); - BlockHitResult hitRes = playerInteractBlockC2SPacket_1.getBlockHitResult(); + InteractionHand hand = playerInteractBlockC2SPacket_1.getHand(); + BlockHitResult hitRes = playerInteractBlockC2SPacket_1.getHitResult(); PLAYER_RIGHT_CLICKS_BLOCK.onBlockHit(player, hand, hitRes); } } - @Inject(method = "onPlayerInteractItem", at = @At( + @Inject(method = "handleUseItem", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateLastActionTime()V" + target = "Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V" )) - private void onItemClicked(PlayerInteractItemC2SPacket playerInteractItemC2SPacket_1, CallbackInfo ci) + private void onItemClicked(ServerboundUseItemPacket playerInteractItemC2SPacket_1, CallbackInfo ci) { if (PLAYER_USES_ITEM.isNeeded()) { - Hand hand = playerInteractItemC2SPacket_1.getHand(); - PLAYER_USES_ITEM.onItemAction(player, hand, player.getStackInHand(hand).copy()); + InteractionHand hand = playerInteractItemC2SPacket_1.getHand(); + PLAYER_USES_ITEM.onItemAction(player, hand, player.getItemInHand(hand).copy()); } } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSneaking(Z)V", + target = "Lnet/minecraft/server/level/ServerPlayer;setShiftKeyDown(Z)V", ordinal = 0 )) - private void onStartSneaking(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onStartSneaking(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { PLAYER_STARTS_SNEAKING.onPlayerEvent(player); } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSneaking(Z)V", + target = "Lnet/minecraft/server/level/ServerPlayer;setShiftKeyDown(Z)V", ordinal = 1 )) - private void onStopSneaking(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onStopSneaking(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { PLAYER_STOPS_SNEAKING.onPlayerEvent(player); } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSprinting(Z)V", + target = "Lnet/minecraft/server/level/ServerPlayer;setSprinting(Z)V", ordinal = 0 )) - private void onStartSprinting(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onStartSprinting(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { PLAYER_STARTS_SPRINTING.onPlayerEvent(player); } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSprinting(Z)V", + target = "Lnet/minecraft/server/level/ServerPlayer;setSprinting(Z)V", ordinal = 1 )) - private void onStopSprinting(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onStopSprinting(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { PLAYER_STOPS_SPRINTING.onPlayerEvent(player); } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;isSleeping()Z", + target = "Lnet/minecraft/server/level/ServerPlayer;isSleeping()Z", shift = At.Shift.BEFORE )) - private void onWakeUp(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onWakeUp(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { //weird one - doesn't seem to work, maybe MP if (player.isSleeping()) @@ -215,12 +215,12 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin } - @Inject(method = "onClientCommand", at = @At( + @Inject(method = "handlePlayerCommand", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;checkFallFlying()Z", + target = "Lnet/minecraft/server/level/ServerPlayer;tryToStartFallFlying()Z", shift = At.Shift.BEFORE )) - private void onElytraEngage(ClientCommandC2SPacket clientCommandC2SPacket_1, CallbackInfo ci) + private void onElytraEngage(ServerboundPlayerCommandPacket clientCommandC2SPacket_1, CallbackInfo ci) { PLAYER_DEPLOYS_ELYTRA.onPlayerEvent(player); } @@ -244,38 +244,38 @@ public class ServerPlayNetworkHandler_scarpetEventsMixin PLAYER_ATTACKS_ENTITY.onEntityHandAction(player, playerInteractEntityC2SPacket_1.getEntity(player.getWorld()), null); }*/ - @Inject(method = "onButtonClick", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateLastActionTime()V")) - private void onItemBeingPickedFromInventory(ButtonClickC2SPacket packet, CallbackInfo ci) + @Inject(method = "handleContainerButtonClick", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V")) + private void onItemBeingPickedFromInventory(ServerboundContainerButtonClickPacket packet, CallbackInfo ci) { // crafts not int the crafting window //CarpetSettings.LOG.error("Player clicks button "+packet.getButtonId()); } - @Inject(method = "onCraftRequest", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;updateLastActionTime()V")) - private void onRecipeSelectedInRecipeManager(CraftRequestC2SPacket packet, CallbackInfo ci) + @Inject(method = "handlePlaceRecipe", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V")) + private void onRecipeSelectedInRecipeManager(ServerboundPlaceRecipePacket packet, CallbackInfo ci) { if (PLAYER_CHOOSES_RECIPE.isNeeded()) { - PLAYER_CHOOSES_RECIPE.onRecipeSelected(player, packet.getRecipe(), packet.shouldCraftAll()); + PLAYER_CHOOSES_RECIPE.onRecipeSelected(player, packet.getRecipe(), packet.isShiftDown()); } } - @Inject(method = "onUpdateSelectedSlot", at = @At("HEAD")) - private void onUpdatedSelectedSLot(UpdateSelectedSlotC2SPacket packet, CallbackInfo ci) + @Inject(method = "handleSetCarriedItem", at = @At("HEAD")) + private void onUpdatedSelectedSLot(ServerboundSetCarriedItemPacket packet, CallbackInfo ci) { - if (PLAYER_SWITCHES_SLOT.isNeeded() && player.getServer() != null && player.getServer().isOnThread()) + if (PLAYER_SWITCHES_SLOT.isNeeded() && player.getServer() != null && player.getServer().isSameThread()) { - PLAYER_SWITCHES_SLOT.onSlotSwitch(player, player.getInventory().selectedSlot, packet.getSelectedSlot()); + PLAYER_SWITCHES_SLOT.onSlotSwitch(player, player.getInventory().selected, packet.getSlot()); } } - @Inject(method = "onHandSwing", at = @At( + @Inject(method = "handleAnimate", at = @At( value = "INVOKE", target = - "Lnet/minecraft/server/network/ServerPlayerEntity;updateLastActionTime()V", + "Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V", shift = At.Shift.BEFORE) ) - private void onSwing(HandSwingC2SPacket packet, CallbackInfo ci) + private void onSwing(ServerboundSwingPacket packet, CallbackInfo ci) { - if (PLAYER_SWINGS_HAND.isNeeded() && !player.handSwinging) + if (PLAYER_SWINGS_HAND.isNeeded() && !player.swinging) { PLAYER_SWINGS_HAND.onHandAction(player, packet.getHand()); } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_tickMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_tickMixin.java index a1fb9341..4c5c29d5 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_tickMixin.java @@ -1,31 +1,31 @@ package carpet.mixins; import carpet.helpers.TickSpeed; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.network.packet.c2s.play.PlayerInputC2SPacket; -import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ServerPlayNetworkHandler.class) +@Mixin(ServerGamePacketListenerImpl.class) public class ServerPlayNetworkHandler_tickMixin { - @Shadow public ServerPlayerEntity player; + @Shadow public ServerPlayer player; - @Shadow private double lastTickX; + @Shadow private double firstGoodX; - @Shadow private double lastTickY; + @Shadow private double firstGoodY; - @Shadow private double lastTickZ; + @Shadow private double firstGoodZ; - @Inject(method = "onPlayerInput", at = @At(value = "RETURN")) - private void checkMoves(PlayerInputC2SPacket p, CallbackInfo ci) + @Inject(method = "handlePlayerInput", at = @At(value = "RETURN")) + private void checkMoves(ServerboundPlayerInputPacket p, CallbackInfo ci) { - if (p.getSideways() != 0.0F || p.getForward() != 0.0F || p.isJumping() || p.isSneaking()) + if (p.getXxa() != 0.0F || p.getZza() != 0.0F || p.isJumping() || p.isShiftKeyDown()) { TickSpeed.reset_player_active_timeout(); } @@ -35,24 +35,24 @@ public class ServerPlayNetworkHandler_tickMixin private static long lastMovedTick = 0L; private static double lastMoved = 0.0D; - @Inject(method = "onPlayerMove", at = @At( + @Inject(method = "handleMovePlayer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;isSleeping()Z", + target = "Lnet/minecraft/server/level/ServerPlayer;isSleeping()Z", shift = At.Shift.BEFORE )) - private void checkMove(PlayerMoveC2SPacket p, CallbackInfo ci) + private void checkMove(ServerboundMovePlayerPacket p, CallbackInfo ci) { - double movedBy = player.getPos().squaredDistanceTo(lastTickX, lastTickY, lastTickZ); + double movedBy = player.position().distanceToSqr(firstGoodX, firstGoodY, firstGoodZ); if (movedBy == 0.0D) return; // corrective tick - if (movedBy < 0.0009 && lastMoved > 0.0009 && Math.abs(player.getServer().getTicks()-lastMovedTick-20)<2) + if (movedBy < 0.0009 && lastMoved > 0.0009 && Math.abs(player.getServer().getTickCount()-lastMovedTick-20)<2) { return; } if (movedBy > 0.0D) { lastMoved = movedBy; - lastMovedTick = player.getServer().getTicks(); + lastMovedTick = player.getServer().getTickCount(); TickSpeed.reset_player_active_timeout(); } } diff --git a/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java b/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java index 8e68cac4..5b8b5108 100644 --- a/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerEntityMixin.java @@ -5,15 +5,15 @@ import carpet.fakes.ServerPlayerEntityInterface; import carpet.helpers.EntityPlayerActionPack; import com.mojang.authlib.GameProfile; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ServerPlayerEntity.class) +@Mixin(ServerPlayer.class) public abstract class ServerPlayerEntityMixin implements ServerPlayerEntityInterface { @Unique @@ -27,11 +27,11 @@ public abstract class ServerPlayerEntityMixin implements ServerPlayerEntityInter @Inject(method = "", at = @At(value = "RETURN")) private void onServerPlayerEntityContructor( MinecraftServer minecraftServer_1, - ServerWorld serverWorld_1, + ServerLevel serverWorld_1, GameProfile gameProfile_1, CallbackInfo ci) { - this.actionPack = new EntityPlayerActionPack((ServerPlayerEntity) (Object) this); + this.actionPack = new EntityPlayerActionPack((ServerPlayer) (Object) this); } @Inject(method = "tick", at = @At(value = "HEAD")) diff --git a/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java index 63a1e8f2..369ba244 100644 --- a/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerEntity_scarpetEventMixin.java @@ -4,18 +4,18 @@ import carpet.fakes.EntityInterface; import carpet.fakes.ServerPlayerEntityInterface; import carpet.script.EntityEventsGroup; import com.mojang.authlib.GameProfile; -import net.minecraft.entity.Entity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.network.packet.c2s.play.ClientSettingsC2SPacket; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.stat.Stat; -import net.minecraft.util.Hand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.game.ServerboundClientInformationPacket; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.stats.Stat; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; @@ -30,91 +30,91 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_DIES; import static carpet.script.CarpetEventServer.Event.PLAYER_FINISHED_USING_ITEM; import static carpet.script.CarpetEventServer.Event.STATISTICS; -@Mixin(ServerPlayerEntity.class) -public abstract class ServerPlayerEntity_scarpetEventMixin extends PlayerEntity implements ServerPlayerEntityInterface +@Mixin(ServerPlayer.class) +public abstract class ServerPlayerEntity_scarpetEventMixin extends Player implements ServerPlayerEntityInterface { // to denote if the player reference is valid @Unique private boolean isInvalidReference = false; - public ServerPlayerEntity_scarpetEventMixin(World world, BlockPos blockPos, float f, GameProfile gameProfile) + public ServerPlayerEntity_scarpetEventMixin(Level world, BlockPos blockPos, float f, GameProfile gameProfile) { super(world, blockPos, f, gameProfile); } - @Shadow protected abstract void consumeItem(); + @Shadow protected abstract void completeUsingItem(); - @Shadow public boolean notInAnyWorld; + @Shadow public boolean wonGame; - @Redirect(method = "consumeItem", at = @At( + @Redirect(method = "completeUsingItem", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;consumeItem()V" + target = "Lnet/minecraft/world/entity/player/Player;completeUsingItem()V" )) - private void finishedUsingItem(PlayerEntity playerEntity) + private void finishedUsingItem(Player playerEntity) { if (PLAYER_FINISHED_USING_ITEM.isNeeded()) { - Hand hand = getActiveHand(); - PLAYER_FINISHED_USING_ITEM.onItemAction((ServerPlayerEntity) (Object)this, hand, getActiveItem()); + InteractionHand hand = getUsedItemHand(); + PLAYER_FINISHED_USING_ITEM.onItemAction((ServerPlayer) (Object)this, hand, getUseItem()); // do vanilla - super.consumeItem(); + super.completeUsingItem(); } else { // do vanilla - super.consumeItem(); + super.completeUsingItem(); } } - @Inject(method = "increaseStat", at = @At("HEAD")) + @Inject(method = "awardStat", at = @At("HEAD")) private void grabStat(Stat stat, int amount, CallbackInfo ci) { - STATISTICS.onPlayerStatistic((ServerPlayerEntity) (Object)this, stat, amount); + STATISTICS.onPlayerStatistic((ServerPlayer) (Object)this, stat, amount); } - @Inject(method = "onDeath", at = @At("HEAD")) + @Inject(method = "die", at = @At("HEAD")) private void onDeathEvent(DamageSource source, CallbackInfo ci) { - ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, source.name); + ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, source.msgId); if (PLAYER_DIES.isNeeded()) { - PLAYER_DIES.onPlayerEvent((ServerPlayerEntity) (Object)this); + PLAYER_DIES.onPlayerEvent((ServerPlayer) (Object)this); } } - @Redirect(method = "updateInput", at = @At( + @Redirect(method = "setPlayerInput", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;setSneaking(Z)V" + target = "Lnet/minecraft/server/level/ServerPlayer;setShiftKeyDown(Z)V" )) - private void setSneakingConditionally(ServerPlayerEntity serverPlayerEntity, boolean sneaking) + private void setSneakingConditionally(ServerPlayer serverPlayerEntity, boolean sneaking) { if (!((EntityInterface)serverPlayerEntity.getVehicle()).isPermanentVehicle()) // won't since that method makes sure its not null - serverPlayerEntity.setSneaking(sneaking); + serverPlayerEntity.setShiftKeyDown(sneaking); } - private Vec3d previousLocation; - private RegistryKey previousDimension; + private Vec3 previousLocation; + private ResourceKey previousDimension; - @Inject(method = "moveToWorld", at = @At("HEAD")) - private void logPreviousCoordinates(ServerWorld serverWorld, CallbackInfoReturnable cir) + @Inject(method = "changeDimension", at = @At("HEAD")) + private void logPreviousCoordinates(ServerLevel serverWorld, CallbackInfoReturnable cir) { - previousLocation = getPos(); - previousDimension = world.getRegistryKey(); //dimension type + previousLocation = position(); + previousDimension = level.dimension(); //dimension type } - @Inject(method = "moveToWorld", at = @At("RETURN")) - private void atChangeDimension(ServerWorld destination, CallbackInfoReturnable cir) + @Inject(method = "changeDimension", at = @At("RETURN")) + private void atChangeDimension(ServerLevel destination, CallbackInfoReturnable cir) { if (PLAYER_CHANGES_DIMENSION.isNeeded()) { - ServerPlayerEntity player = (ServerPlayerEntity) (Object)this; - Vec3d to = null; - if (!notInAnyWorld || previousDimension != World.END || destination.getRegistryKey() != World.OVERWORLD) // end ow + ServerPlayer player = (ServerPlayer) (Object)this; + Vec3 to = null; + if (!wonGame || previousDimension != Level.END || destination.dimension() != Level.OVERWORLD) // end ow { - to = getPos(); + to = position(); } - PLAYER_CHANGES_DIMENSION.onDimensionChange(player, previousLocation, to, previousDimension, destination.getRegistryKey()); + PLAYER_CHANGES_DIMENSION.onDimensionChange(player, previousLocation, to, previousDimension, destination.dimension()); } }; @@ -140,8 +140,8 @@ public abstract class ServerPlayerEntity_scarpetEventMixin extends PlayerEntity return this.language; } - @Inject(method = "setClientSettings", at = @At("HEAD")) - public void setLanguage(ClientSettingsC2SPacket packet, CallbackInfo ci) + @Inject(method = "updateOptions", at = @At("HEAD")) + public void setLanguage(ServerboundClientInformationPacket packet, CallbackInfo ci) { this.language = packet.language(); } diff --git a/src/main/java/carpet/mixins/ServerPlayerEntity_updateSuppressionCrashFixMixin.java b/src/main/java/carpet/mixins/ServerPlayerEntity_updateSuppressionCrashFixMixin.java index 83a3fecd..5d177801 100644 --- a/src/main/java/carpet/mixins/ServerPlayerEntity_updateSuppressionCrashFixMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerEntity_updateSuppressionCrashFixMixin.java @@ -5,39 +5,39 @@ import carpet.helpers.ThrowableSuppression; import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; import com.mojang.authlib.GameProfile; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.util.crash.CrashException; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.ReportedException; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(ServerPlayerEntity.class) -public abstract class ServerPlayerEntity_updateSuppressionCrashFixMixin extends PlayerEntity { +@Mixin(ServerPlayer.class) +public abstract class ServerPlayerEntity_updateSuppressionCrashFixMixin extends Player { - public ServerPlayerEntity_updateSuppressionCrashFixMixin(World world, BlockPos pos, float yaw, GameProfile profile) { + public ServerPlayerEntity_updateSuppressionCrashFixMixin(Level world, BlockPos pos, float yaw, GameProfile profile) { super(world, pos, yaw, profile); } @Redirect( - method = "playerTick()V", + method = "doTick()V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;tick()V" + target = "Lnet/minecraft/world/entity/player/Player;tick()V" ), require = 0 ) - private void fixUpdateSuppressionCrashPlayerTick(PlayerEntity playerEntity){ + private void fixUpdateSuppressionCrashPlayerTick(Player playerEntity){ if (!CarpetSettings.updateSuppressionCrashFix) { super.tick(); return; } try { super.tick(); - } catch (CrashException e) { + } catch (ReportedException e) { if (!(e.getCause() instanceof ThrowableSuppression throwableSuppression)) throw e; logUpdateSuppressionPlayer(throwableSuppression.pos); } catch (ThrowableSuppression e) { @@ -49,7 +49,7 @@ public abstract class ServerPlayerEntity_updateSuppressionCrashFixMixin extends private void logUpdateSuppressionPlayer(BlockPos pos) { if(LoggerRegistry.__updateSuppressedCrashes) { LoggerRegistry.getLogger("updateSuppressedCrashes").log(() -> { - return new BaseText[]{Messenger.c( + return new BaseComponent[]{Messenger.c( "w Server crash prevented in: ", "m player tick ", "w - at: ", diff --git a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_antiCheatMixin.java b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_antiCheatMixin.java index 28e4bea6..ca2254ac 100644 --- a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_antiCheatMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_antiCheatMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.network.ServerPlayerInteractionManager; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(value = ServerPlayerInteractionManager.class, priority = 69420) // not that important for carpet +@Mixin(value = ServerPlayerGameMode.class, priority = 69420) // not that important for carpet public class ServerPlayerInteractionManager_antiCheatMixin { /* @@ -27,41 +27,41 @@ public class ServerPlayerInteractionManager_antiCheatMixin // that shoudn't've been a constant at the first place // resolves problems with mobs using reach entity attributes. - @Redirect(method = "processBlockBreakingAction", at = @At( + @Redirect(method = "handleBlockBreakAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;getX()D" + target = "Lnet/minecraft/server/level/ServerPlayer;getX()D" )) - private double getXX(ServerPlayerEntity player, - BlockPos pos, PlayerActionC2SPacket.Action action, Direction direction, int worldHeight) + private double getXX(ServerPlayer player, + BlockPos pos, ServerboundPlayerActionPacket.Action action, Direction direction, int worldHeight) { if (CarpetSettings.antiCheatDisabled && - player.getPos().add(0, 1.5, 0).squaredDistanceTo(Vec3d.ofCenter(pos)) < 1024 + player.position().add(0, 1.5, 0).distanceToSqr(Vec3.atCenterOf(pos)) < 1024 ) return pos.getX()+0.5; return player.getX(); } - @Redirect(method = "processBlockBreakingAction", at = @At( + @Redirect(method = "handleBlockBreakAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;getY()D" + target = "Lnet/minecraft/server/level/ServerPlayer;getY()D" )) - private double getYY(ServerPlayerEntity player, - BlockPos pos, PlayerActionC2SPacket.Action action, Direction direction, int worldHeight) + private double getYY(ServerPlayer player, + BlockPos pos, ServerboundPlayerActionPacket.Action action, Direction direction, int worldHeight) { if (CarpetSettings.antiCheatDisabled && - player.getPos().add(0, 1.5, 0).squaredDistanceTo(Vec3d.ofCenter(pos)) < 1024 + player.position().add(0, 1.5, 0).distanceToSqr(Vec3.atCenterOf(pos)) < 1024 ) return pos.getY()-1.0; return player.getY(); } - @Redirect(method = "processBlockBreakingAction", at = @At( + @Redirect(method = "handleBlockBreakAction", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;getZ()D" + target = "Lnet/minecraft/server/level/ServerPlayer;getZ()D" )) - private double getZZ(ServerPlayerEntity player, - BlockPos pos, PlayerActionC2SPacket.Action action, Direction direction, int worldHeight) + private double getZZ(ServerPlayer player, + BlockPos pos, ServerboundPlayerActionPacket.Action action, Direction direction, int worldHeight) { if (CarpetSettings.antiCheatDisabled && - player.getPos().add(0, 1.5, 0).squaredDistanceTo(Vec3d.ofCenter(pos)) < 1024 + player.position().add(0, 1.5, 0).distanceToSqr(Vec3.atCenterOf(pos)) < 1024 ) return pos.getZ()+0.5; return player.getZ(); } diff --git a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_cactusMixin.java b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_cactusMixin.java index 6a696075..b215d33b 100644 --- a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_cactusMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_cactusMixin.java @@ -1,31 +1,31 @@ package carpet.mixins; import carpet.helpers.BlockRotator; -import net.minecraft.block.BlockState; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.network.ServerPlayerInteractionManager; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.world.World; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(ServerPlayerInteractionManager.class) +@Mixin(ServerPlayerGameMode.class) public class ServerPlayerInteractionManager_cactusMixin { - @Redirect(method = "interactBlock", at = @At( + @Redirect(method = "useItemOn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/BlockState;onUse(Lnet/minecraft/world/World;Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/util/Hand;Lnet/minecraft/util/hit/BlockHitResult;)Lnet/minecraft/util/ActionResult;" + 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 ActionResult activateWithOptionalCactus(BlockState blockState, World world_1, PlayerEntity playerEntity_1, Hand hand_1, BlockHitResult blockHitResult_1) + private InteractionResult activateWithOptionalCactus(BlockState blockState, Level world_1, Player playerEntity_1, InteractionHand hand_1, BlockHitResult blockHitResult_1) { boolean flipped = BlockRotator.flipBlockWithCactus(blockState, world_1, playerEntity_1, hand_1, blockHitResult_1); if (flipped) - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; - return blockState.onUse(world_1, playerEntity_1, hand_1, blockHitResult_1); + return blockState.use(world_1, playerEntity_1, hand_1, blockHitResult_1); } } diff --git a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java index d7ce33b2..927a5168 100644 --- a/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerInteractionManager_scarpetEventsMixin.java @@ -1,19 +1,19 @@ package carpet.mixins; import carpet.fakes.ServerPlayerInteractionManagerInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.network.ServerPlayerInteractionManager; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -25,22 +25,22 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_BREAK_BLOCK; import static carpet.script.CarpetEventServer.Event.PLAYER_INTERACTS_WITH_BLOCK; -@Mixin(ServerPlayerInteractionManager.class) +@Mixin(ServerPlayerGameMode.class) public class ServerPlayerInteractionManager_scarpetEventsMixin implements ServerPlayerInteractionManagerInterface { - @Shadow public ServerPlayerEntity player; + @Shadow public ServerPlayer player; - @Shadow private boolean mining; + @Shadow private boolean isDestroyingBlock; - @Shadow private BlockPos miningPos; + @Shadow private BlockPos destroyPos; - @Shadow private int blockBreakingProgress; + @Shadow private int lastSentState; - @Shadow public ServerWorld world; + @Shadow public ServerLevel level; - @Inject(method = "tryBreakBlock", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( + @Inject(method = "destroyBlock", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/Block;onBreak(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/entity/player/PlayerEntity;)V", + target = "Lnet/minecraft/world/level/block/Block;playerWillDestroy(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/player/Player;)V", shift = At.Shift.BEFORE )) private void onBlockBroken(BlockPos blockPos_1, CallbackInfoReturnable cir, BlockState blockState_1, BlockEntity be, Block b) @@ -48,11 +48,11 @@ public class ServerPlayerInteractionManager_scarpetEventsMixin implements Server PLAYER_BREAK_BLOCK.onBlockBroken(player, blockPos_1, blockState_1); } - @Inject(method = "interactBlock", at = @At( + @Inject(method = "useItemOn", at = @At( value = "RETURN", ordinal = 2 )) - private void onBlockActivated(ServerPlayerEntity serverPlayerEntity, World world, ItemStack stack, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) + private void onBlockActivated(ServerPlayer serverPlayerEntity, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) { PLAYER_INTERACTS_WITH_BLOCK.onBlockHit(player, hand, hitResult); } @@ -60,21 +60,21 @@ public class ServerPlayerInteractionManager_scarpetEventsMixin implements Server @Override public BlockPos getCurrentBreakingBlock() { - if (!mining) return null; - return miningPos; + if (!isDestroyingBlock) return null; + return destroyPos; } @Override public int getCurrentBlockBreakingProgress() { - if (!mining) return -1; - return blockBreakingProgress; + if (!isDestroyingBlock) return -1; + return lastSentState; } @Override public void setBlockBreakingProgress(int progress) { - blockBreakingProgress = MathHelper.clamp(progress, -1, 10); - world.setBlockBreakingInfo(-1*this.player.getId(), miningPos, blockBreakingProgress); + lastSentState = Mth.clamp(progress, -1, 10); + level.destroyBlockProgress(-1*this.player.getId(), destroyPos, lastSentState); } } diff --git a/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java b/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java index 7a5ad342..6b0206a0 100644 --- a/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_scarpetMixin.java @@ -3,21 +3,20 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.ServerWorldInterface; import carpet.script.CarpetEventServer; -import net.minecraft.entity.Entity; -import net.minecraft.world.LocalDifficulty; -import net.minecraft.world.entity.EntityLike; -import net.minecraft.entity.LightningEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.server.world.ServerEntityManager; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.profiler.Profiler; -import net.minecraft.world.chunk.WorldChunk; -import net.minecraft.world.entity.EntityLookup; -import net.minecraft.world.explosion.Explosion; -import net.minecraft.world.explosion.ExplosionBehavior; -import net.minecraft.world.level.ServerWorldProperties; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.ExplosionDamageCalculator; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.entity.LevelEntityGetter; +import net.minecraft.world.level.entity.PersistentEntitySectionManager; +import net.minecraft.world.level.storage.ServerLevelData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -31,20 +30,20 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import static carpet.script.CarpetEventServer.Event.EXPLOSION; import static carpet.script.CarpetEventServer.Event.LIGHTNING; -@Mixin(ServerWorld.class) +@Mixin(ServerLevel.class) public class ServerWorld_scarpetMixin implements ServerWorldInterface { @Inject(method = "tickChunk", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;spawnEntity(Lnet/minecraft/entity/Entity;)Z", + target = "Lnet/minecraft/server/level/ServerLevel;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z", shift = At.Shift.BEFORE, ordinal = 1 )) - private void onNaturalLightinig(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, + private void onNaturalLightinig(LevelChunk chunk, int randomTickSpeed, CallbackInfo ci, //ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, boolean bl2) - ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, LocalDifficulty localDifficulty, boolean bl2, LightningEntity lightningEntity) + ChunkPos chunkPos, boolean bl, int i, int j, ProfilerFiller profiler, BlockPos blockPos, DifficultyInstance localDifficulty, boolean bl2, LightningBolt lightningEntity) { - if (LIGHTNING.isNeeded()) LIGHTNING.onWorldEventFlag((ServerWorld) (Object)this, blockPos, bl2?1:0); + if (LIGHTNING.isNeeded()) LIGHTNING.onWorldEventFlag((ServerLevel) (Object)this, blockPos, bl2?1:0); } /* @@ -71,24 +70,24 @@ public class ServerWorld_scarpetMixin implements ServerWorldInterface } */ - @Inject(method = "createExplosion", at = @At("HEAD")) - private void handleExplosion(/*@Nullable*/ Entity entity, /*@Nullable*/ DamageSource damageSource, /*@Nullable*/ ExplosionBehavior explosionBehavior, double d, double e, double f, float g, boolean bl, Explosion.DestructionType destructionType, CallbackInfoReturnable cir) + @Inject(method = "explode", at = @At("HEAD")) + private void handleExplosion(/*@Nullable*/ Entity entity, /*@Nullable*/ DamageSource damageSource, /*@Nullable*/ ExplosionDamageCalculator explosionBehavior, double d, double e, double f, float g, boolean bl, Explosion.BlockInteraction destructionType, CallbackInfoReturnable cir) { if (EXPLOSION.isNeeded()) - EXPLOSION.onExplosion((ServerWorld) (Object)this, entity, null, d, e, f, g, bl, null, null, destructionType); + EXPLOSION.onExplosion((ServerLevel) (Object)this, entity, null, d, e, f, g, bl, null, null, destructionType); } @Final @Shadow - private ServerWorldProperties worldProperties; - @Shadow @Final private ServerEntityManager entityManager; + private ServerLevelData serverLevelData; + @Shadow @Final private PersistentEntitySectionManager entityManager; - public ServerWorldProperties getWorldPropertiesCM(){ - return worldProperties; + public ServerLevelData getWorldPropertiesCM(){ + return serverLevelData; } @Override - public EntityLookup getEntityLookupCMPublic() { - return entityManager.getLookup(); + public LevelEntityGetter getEntityLookupCMPublic() { + return entityManager.getEntityGetter(); } } diff --git a/src/main/java/carpet/mixins/ServerWorld_spawnChunksMixin.java b/src/main/java/carpet/mixins/ServerWorld_spawnChunksMixin.java index a462a6f6..fe729f60 100644 --- a/src/main/java/carpet/mixins/ServerWorld_spawnChunksMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_spawnChunksMixin.java @@ -1,15 +1,15 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.level.ServerLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; -@Mixin(ServerWorld.class) +@Mixin(ServerLevel.class) public class ServerWorld_spawnChunksMixin { - @ModifyConstant(method = "setSpawnPos", constant = @Constant(intValue = 11), expect = 2) + @ModifyConstant(method = "setDefaultSpawnPos", constant = @Constant(intValue = 11), expect = 2) private int pushLimit(int original) { return CarpetSettings.spawnChunksSize; diff --git a/src/main/java/carpet/mixins/ServerWorld_tickMixin.java b/src/main/java/carpet/mixins/ServerWorld_tickMixin.java index 90d3ac67..d7042d2d 100644 --- a/src/main/java/carpet/mixins/ServerWorld_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_tickMixin.java @@ -2,14 +2,6 @@ package carpet.mixins; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.profiler.Profiler; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.village.raid.RaidManager; -import net.minecraft.world.MutableWorldProperties; -import net.minecraft.world.World; -import net.minecraft.world.border.WorldBorder; -import net.minecraft.world.dimension.DimensionType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -19,16 +11,24 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.function.BooleanSupplier; import java.util.function.Supplier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.entity.raid.Raids; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.storage.WritableLevelData; -@Mixin(ServerWorld.class) -public abstract class ServerWorld_tickMixin extends World +@Mixin(ServerLevel.class) +public abstract class ServerWorld_tickMixin extends Level { - protected ServerWorld_tickMixin(MutableWorldProperties properties, RegistryKey registryKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) + protected ServerWorld_tickMixin(WritableLevelData properties, ResourceKey registryKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(properties, registryKey, dimensionType, supplier, bl, bl2, l); } - @Shadow protected abstract void processSyncedBlockEvents(); + @Shadow protected abstract void runBlockEvents(); @Shadow protected abstract void tickTime(); @@ -40,7 +40,7 @@ public abstract class ServerWorld_tickMixin extends World )) private void startWeatherSection(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - currentSection = CarpetProfiler.start_section((World)(Object)this, "Environment", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level)(Object)this, "Environment", CarpetProfiler.TYPE.GENERAL); } @Inject(method = "tick", at = @At( value = "CONSTANT", @@ -63,7 +63,7 @@ public abstract class ServerWorld_tickMixin extends World if (currentSection != null) { // out of chunk - currentSection = CarpetProfiler.start_section((World) (Object) this, "Blocks", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level) (Object) this, "Blocks", CarpetProfiler.TYPE.GENERAL); } } @@ -76,7 +76,7 @@ public abstract class ServerWorld_tickMixin extends World if (currentSection != null) { CarpetProfiler.end_current_section(currentSection); - currentSection = CarpetProfiler.start_section((World) (Object) this, "Village", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level) (Object) this, "Village", CarpetProfiler.TYPE.GENERAL); } } @Inject(method = "tick", at = @At( @@ -99,7 +99,7 @@ public abstract class ServerWorld_tickMixin extends World )) private void startBlockAgainSection(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - currentSection = CarpetProfiler.start_section((World) (Object) this, "Blocks", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level) (Object) this, "Blocks", CarpetProfiler.TYPE.GENERAL); } @Inject(method = "tick", at = @At( @@ -111,13 +111,13 @@ public abstract class ServerWorld_tickMixin extends World if (currentSection != null) { CarpetProfiler.end_current_section(currentSection); - currentSection = CarpetProfiler.start_section((World) (Object) this, "Entities", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level) (Object) this, "Entities", CarpetProfiler.TYPE.GENERAL); } } @Inject(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;tickBlockEntities()V", + target = "Lnet/minecraft/server/level/ServerLevel;tickBlockEntities()V", shift = At.Shift.BEFORE )) private void endEntitySection(BooleanSupplier booleanSupplier_1, CallbackInfo ci) @@ -129,14 +129,14 @@ public abstract class ServerWorld_tickMixin extends World @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/border/WorldBorder;tick()V" + target = "Lnet/minecraft/world/level/border/WorldBorder;tick()V" )) private void tickWorldBorder(WorldBorder worldBorder) { if (TickSpeed.process_entities) worldBorder.tick(); } - @Inject(method = "tickWeather", cancellable = true, at = @At("HEAD")) + @Inject(method = "advanceWeatherCycle", cancellable = true, at = @At("HEAD")) private void tickWeather(CallbackInfo ci) { if (!TickSpeed.process_entities) ci.cancel(); @@ -144,40 +144,39 @@ public abstract class ServerWorld_tickMixin extends World @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;tickTime()V" // right before chunk source + target = "Lnet/minecraft/server/level/ServerLevel;tickTime()V" )) - private void tickTimeConditionally(ServerWorld serverWorld) + private void tickTimeConditionally(ServerLevel serverWorld) { if (TickSpeed.process_entities) tickTime(); } @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;isDebugWorld()Z" // isDebug - //target = "Lnet/minecraft/world/level/LevelProperties;getGeneratorType()Lnet/minecraft/world/level/LevelGeneratorType;" + target = "Lnet/minecraft/server/level/ServerLevel;isDebug()Z" )) - private boolean tickPendingBlocks(ServerWorld serverWorld) + private boolean tickPendingBlocks(ServerLevel serverWorld) { if (!TickSpeed.process_entities) return true; - return serverWorld.isDebugWorld(); // isDebug() + return serverWorld.isDebug(); // isDebug() } @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/village/raid/RaidManager;tick()V" + target = "Lnet/minecraft/world/entity/raid/Raids;tick()V" )) - private void tickConditionally(RaidManager raidManager) + private void tickConditionally(Raids raidManager) { if (TickSpeed.process_entities) raidManager.tick(); } @Redirect(method = "tick", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;processSyncedBlockEvents()V" // aka sendBlockActions + target = "Lnet/minecraft/server/level/ServerLevel;runBlockEvents()V" )) - private void tickConditionally(ServerWorld serverWorld) + private void tickConditionally(ServerLevel serverWorld) { - if (TickSpeed.process_entities) processSyncedBlockEvents(); + if (TickSpeed.process_entities) runBlockEvents(); } diff --git a/src/main/java/carpet/mixins/SetBlockCommandMixin.java b/src/main/java/carpet/mixins/SetBlockCommandMixin.java index eb050fd5..30928c29 100644 --- a/src/main/java/carpet/mixins/SetBlockCommandMixin.java +++ b/src/main/java/carpet/mixins/SetBlockCommandMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.server.command.SetBlockCommand; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.server.commands.SetBlockCommand; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -12,12 +12,12 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(SetBlockCommand.class) public class SetBlockCommandMixin { - @Redirect(method = "execute", at = @At( + @Redirect(method = "setBlock", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" )) - private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) + private static void conditionalUpdating(ServerLevel serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.blockUpdated(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java b/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java index f662c1c3..ec344482 100644 --- a/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/ShulkerBoxBlockEntity_creativeNoClipMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.entity.ShulkerBoxBlockEntity; -import net.minecraft.block.piston.PistonBehavior; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.world.level.material.PushReaction; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -12,14 +12,14 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(ShulkerBoxBlockEntity.class) public class ShulkerBoxBlockEntity_creativeNoClipMixin { - @Redirect(method = "pushEntities", at = @At( + @Redirect(method = "moveCollidedEntities", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/Entity;getPistonBehavior()Lnet/minecraft/block/piston/PistonBehavior;" + target = "Lnet/minecraft/world/entity/Entity;getPistonPushReaction()Lnet/minecraft/world/level/material/PushReaction;" )) - private PistonBehavior getPistonBehaviourOfNoClipPlayers(Entity entity) + private PushReaction getPistonBehaviourOfNoClipPlayers(Entity entity) { - if (CarpetSettings.creativeNoClip && entity instanceof PlayerEntity && (((PlayerEntity) entity).isCreative()) && ((PlayerEntity) entity).getAbilities().flying) - return PistonBehavior.IGNORE; - return entity.getPistonBehavior(); + if (CarpetSettings.creativeNoClip && entity instanceof Player && (((Player) entity).isCreative()) && ((Player) entity).getAbilities().flying) + return PushReaction.IGNORE; + return entity.getPistonPushReaction(); } } diff --git a/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java b/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java index eeb85747..eff37250 100644 --- a/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java +++ b/src/main/java/carpet/mixins/SimpleEntityLookup_scarpetMixin.java @@ -1,27 +1,27 @@ package carpet.mixins; import carpet.fakes.SimpleEntityLookupInterface; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.entity.EntityLike; -import net.minecraft.world.entity.EntityTrackingSection; -import net.minecraft.world.entity.SectionedEntityCache; -import net.minecraft.world.entity.SimpleEntityLookup; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.List; import java.util.stream.Collectors; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.entity.EntityAccess; +import net.minecraft.world.level.entity.EntitySection; +import net.minecraft.world.level.entity.EntitySectionStorage; +import net.minecraft.world.level.entity.LevelEntityGetterAdapter; -@Mixin(SimpleEntityLookup.class) -public class SimpleEntityLookup_scarpetMixin implements SimpleEntityLookupInterface +@Mixin(LevelEntityGetterAdapter.class) +public class SimpleEntityLookup_scarpetMixin implements SimpleEntityLookupInterface { - @Shadow @Final private SectionedEntityCache cache; + @Shadow @Final private EntitySectionStorage sectionStorage; @Override public List getChunkEntities(ChunkPos chpos) { - return this.cache.getTrackingSections(chpos.toLong()).flatMap(EntityTrackingSection::stream).collect(Collectors.toList()); + return this.sectionStorage.getExistingSectionsInChunk(chpos.toLong()).flatMap(EntitySection::getEntities).collect(Collectors.toList()); } } diff --git a/src/main/java/carpet/mixins/SkeletonHorseTrapTriggerGoal_extremeMixin.java b/src/main/java/carpet/mixins/SkeletonHorseTrapTriggerGoal_extremeMixin.java index 9461756c..a5ae8324 100644 --- a/src/main/java/carpet/mixins/SkeletonHorseTrapTriggerGoal_extremeMixin.java +++ b/src/main/java/carpet/mixins/SkeletonHorseTrapTriggerGoal_extremeMixin.java @@ -1,14 +1,14 @@ package carpet.mixins; import carpet.utils.RandomTools; -import net.minecraft.entity.ai.goal.SkeletonHorseTrapTriggerGoal; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.animal.horse.SkeletonTrapGoal; -@Mixin(SkeletonHorseTrapTriggerGoal.class) +@Mixin(SkeletonTrapGoal.class) public class SkeletonHorseTrapTriggerGoal_extremeMixin { @Redirect(method = "tick", expect = 2, at = @At( diff --git a/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java index cf4d0543..4e41b9fa 100644 --- a/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/SkyLightStorage_scarpetChunkCreationMixin.java @@ -7,103 +7,103 @@ import org.spongepowered.asm.mixin.Shadow; import carpet.fakes.ChunkLightProviderInterface; import carpet.fakes.LightStorageInterface; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.LightType; -import net.minecraft.world.chunk.ChunkNibbleArray; -import net.minecraft.world.chunk.ChunkProvider; -import net.minecraft.world.chunk.light.BlockLightStorage.Data; -import net.minecraft.world.chunk.light.ChunkLightProvider; -import net.minecraft.world.chunk.light.LightStorage; -import net.minecraft.world.chunk.light.SkyLightStorage; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.chunk.LightChunkGetter; +import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap; +import net.minecraft.world.level.lighting.LayerLightEngine; +import net.minecraft.world.level.lighting.LayerLightSectionStorage; +import net.minecraft.world.level.lighting.SkyLightSectionStorage; -@Mixin(SkyLightStorage.class) -public abstract class SkyLightStorage_scarpetChunkCreationMixin extends LightStorage implements LightStorageInterface +@Mixin(SkyLightSectionStorage.class) +public abstract class SkyLightStorage_scarpetChunkCreationMixin extends LayerLightSectionStorage implements LightStorageInterface { - protected SkyLightStorage_scarpetChunkCreationMixin(final LightType lightType, final ChunkProvider chunkProvider, final Data lightData) + protected SkyLightStorage_scarpetChunkCreationMixin(final LightLayer lightType, final LightChunkGetter chunkProvider, final BlockDataLayerStorageMap lightData) { super(lightType, chunkProvider, lightData); } @Shadow @Final - private LongSet sectionsToUpdate; + private LongSet sectionsToAddSourcesTo; @Shadow @Final - private LongSet sectionsToRemove; + private LongSet sectionsToRemoveSourcesFrom; @Shadow @Final - private LongSet field_15820; + private LongSet sectionsWithSources; - @Shadow protected abstract boolean isAtOrAboveTopmostSection(final long pos); + @Shadow protected abstract boolean isAboveData(final long pos); - @Shadow protected abstract boolean isSectionEnabled(final long sectionPos); + @Shadow protected abstract boolean lightOnInSection(final long sectionPos); @Override public void processRemoveLightData(final long cPos) { for (int y = -1; y < 17; ++y) { - final long sectionPos = ChunkSectionPos.asLong(ChunkSectionPos.unpackX(cPos), y, ChunkSectionPos.unpackZ(cPos)); + final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); - this.sectionsToUpdate.remove(sectionPos); - this.sectionsToRemove.remove(sectionPos); + this.sectionsToAddSourcesTo.remove(sectionPos); + this.sectionsToRemoveSourcesFrom.remove(sectionPos); - this.field_15820.remove(sectionPos); + this.sectionsWithSources.remove(sectionPos); } } @Override - public void processRelight(final ChunkLightProvider lightProvider, final long cPos) + public void processRelight(final LayerLightEngine lightProvider, final long cPos) { final LevelPropagator_resetChunkInterface levelPropagator = (LevelPropagator_resetChunkInterface) lightProvider; for (int y = -1; y < 17; ++y) { - final long sectionPos = ChunkSectionPos.asLong(ChunkSectionPos.unpackX(cPos), y, ChunkSectionPos.unpackZ(cPos)); - final long pos = BlockPos.asLong(ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackX(sectionPos)), ChunkSectionPos.getBlockCoord(y), ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackZ(sectionPos))); + final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); + final long pos = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(sectionPos)), SectionPos.sectionToBlockCoord(y), SectionPos.sectionToBlockCoord(SectionPos.z(sectionPos))); - if (!this.hasSection(sectionPos)) + if (!this.storingLightForSection(sectionPos)) continue; - for (final Direction dir : Direction.Type.HORIZONTAL) + for (final Direction dir : Direction.Plane.HORIZONTAL) { - long neighborCeilingSectionPos = ChunkSectionPos.offset(sectionPos, dir); - final ChunkNibbleArray neighborLightArray = this.getLightSection(neighborCeilingSectionPos); + long neighborCeilingSectionPos = SectionPos.offset(sectionPos, dir); + final DataLayer neighborLightArray = this.getDataLayerData(neighborCeilingSectionPos); - ChunkNibbleArray neighborCeilingLightArray = neighborLightArray; + DataLayer neighborCeilingLightArray = neighborLightArray; - while (neighborCeilingLightArray == null && !this.isAtOrAboveTopmostSection(neighborCeilingSectionPos)) + while (neighborCeilingLightArray == null && !this.isAboveData(neighborCeilingSectionPos)) { - neighborCeilingSectionPos = ChunkSectionPos.offset(neighborCeilingSectionPos, Direction.UP); - neighborCeilingLightArray = this.getLightSection(neighborCeilingSectionPos); + neighborCeilingSectionPos = SectionPos.offset(neighborCeilingSectionPos, Direction.UP); + neighborCeilingLightArray = this.getDataLayerData(neighborCeilingSectionPos); } - final int ox = 15 * Math.max(dir.getOffsetX(), 0); - final int oz = 15 * Math.max(dir.getOffsetZ(), 0); + final int ox = 15 * Math.max(dir.getStepX(), 0); + final int oz = 15 * Math.max(dir.getStepZ(), 0); - final int dx = Math.abs(dir.getOffsetZ()); - final int dz = Math.abs(dir.getOffsetX()); + final int dx = Math.abs(dir.getStepZ()); + final int dz = Math.abs(dir.getStepX()); int emptyLightLevel = (neighborCeilingLightArray == null) - ? (this.isSectionEnabled(ChunkSectionPos.withZeroY(neighborCeilingSectionPos)) ? 0 : 15) + ? (this.lightOnInSection(SectionPos.getZeroNode(neighborCeilingSectionPos)) ? 0 : 15) : 0; int neighbourY = (neighborLightArray == null) - ? ChunkSectionPos.getBlockCoord(ChunkSectionPos.unpackY(neighborCeilingSectionPos)) + ? SectionPos.sectionToBlockCoord(SectionPos.y(neighborCeilingSectionPos)) : 0; for (int t = 0; t < 16; ++t) for (int dy = 0; dy < 16; ++dy) { - final long dst = BlockPos.add(pos, ox + t * dx, dy, oz + t * dz); + final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); long src = BlockPos.offset(dst, dir); long adj_src = (neighborLightArray != null) ? src - : BlockPos.asLong(BlockPos.unpackLongX(src), neighbourY, BlockPos.unpackLongZ(src)); + : BlockPos.asLong(BlockPos.getX(src), neighbourY, BlockPos.getZ(src)); final int srcLevel = neighborCeilingLightArray != null ? ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, adj_src) diff --git a/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java b/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java index c4257c3c..51971583 100644 --- a/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java +++ b/src/main/java/carpet/mixins/Slot_stackableSBoxesMixin.java @@ -2,19 +2,19 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.InventoryHelper; -import net.minecraft.block.ShulkerBoxBlock; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.ShulkerBoxBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(Slot.class) public class Slot_stackableSBoxesMixin { - @Redirect(method = "insertStack(Lnet/minecraft/item/ItemStack;I)Lnet/minecraft/item/ItemStack;", at = @At( + @Redirect(method = "safeInsert(Lnet/minecraft/world/item/ItemStack;I)Lnet/minecraft/world/item/ItemStack;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/screen/slot/Slot;getMaxItemCount(Lnet/minecraft/item/ItemStack;)I" + target = "Lnet/minecraft/world/inventory/Slot;getMaxStackSize(Lnet/minecraft/world/item/ItemStack;)I" )) private int getMaxCountForSboxesInSlot(Slot slot, ItemStack stack) { @@ -26,6 +26,6 @@ public class Slot_stackableSBoxesMixin { { return CarpetSettings.shulkerBoxStackSize; } - return slot.getMaxItemCount(stack); + return slot.getMaxStackSize(stack); } } diff --git a/src/main/java/carpet/mixins/SoundEngineInt_cleanLogsMixin.java b/src/main/java/carpet/mixins/SoundEngineInt_cleanLogsMixin.java index 8f7bbe81..4e3330e0 100644 --- a/src/main/java/carpet/mixins/SoundEngineInt_cleanLogsMixin.java +++ b/src/main/java/carpet/mixins/SoundEngineInt_cleanLogsMixin.java @@ -6,7 +6,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(targets="net.minecraft.client.sound.SoundEngine$SourceSetImpl", priority = 69420) +@Mixin(targets="com.mojang.blaze3d.audio.Library$CountingChannelPool", priority = 69420) public class SoundEngineInt_cleanLogsMixin { // createSource // method_19666, remap = false, diff --git a/src/main/java/carpet/mixins/SoundSystem_cleanLogsMixin.java b/src/main/java/carpet/mixins/SoundSystem_cleanLogsMixin.java index 00b32ffe..ec47b34b 100644 --- a/src/main/java/carpet/mixins/SoundSystem_cleanLogsMixin.java +++ b/src/main/java/carpet/mixins/SoundSystem_cleanLogsMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.client.sound.SoundSystem; +import net.minecraft.client.sounds.SoundEngine; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(value = SoundSystem.class, priority = 69420) +@Mixin(value = SoundEngine.class, priority = 69420) public class SoundSystem_cleanLogsMixin { /*@Redirect(method = "play(Lnet/minecraft/client/sound/SoundInstance;)V", require = 0, at = @At( remap = false, diff --git a/src/main/java/carpet/mixins/SpawnGroup_spawnMixin.java b/src/main/java/carpet/mixins/SpawnGroup_spawnMixin.java index bbad9dda..d123f62a 100644 --- a/src/main/java/carpet/mixins/SpawnGroup_spawnMixin.java +++ b/src/main/java/carpet/mixins/SpawnGroup_spawnMixin.java @@ -2,7 +2,7 @@ package carpet.mixins; import carpet.fakes.SpawnGroupInterface; import carpet.utils.SpawnReporter; -import net.minecraft.entity.SpawnGroup; +import net.minecraft.world.entity.MobCategory; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -10,20 +10,20 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(SpawnGroup.class) +@Mixin(MobCategory.class) public class SpawnGroup_spawnMixin implements SpawnGroupInterface { - @Shadow @Final private int capacity; + @Shadow @Final private int max; - @Inject(method = "getCapacity", at = @At("HEAD"), cancellable = true) + @Inject(method = "getMaxInstancesPerChunk", at = @At("HEAD"), cancellable = true) private void getModifiedCapacity(CallbackInfoReturnable cir) { - cir.setReturnValue ((int) ((double)capacity*(Math.pow(2.0,(SpawnReporter.mobcap_exponent/4))))); + cir.setReturnValue ((int) ((double)max*(Math.pow(2.0,(SpawnReporter.mobcap_exponent/4))))); } @Override public int getInitialSpawnCap() { - return capacity; + return max; } } diff --git a/src/main/java/carpet/mixins/SpawnHelperInnerMixin.java b/src/main/java/carpet/mixins/SpawnHelperInnerMixin.java index d5d863fd..9ffb9db1 100644 --- a/src/main/java/carpet/mixins/SpawnHelperInnerMixin.java +++ b/src/main/java/carpet/mixins/SpawnHelperInnerMixin.java @@ -3,9 +3,8 @@ package carpet.mixins; import carpet.fakes.SpawnHelperInnerInterface; import carpet.utils.SpawnReporter; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.util.math.GravityField; -import net.minecraft.world.SpawnHelper; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.PotentialCalculator; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -13,12 +12,12 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(SpawnHelper.Info.class) +@Mixin(NaturalSpawner.SpawnState.class) public class SpawnHelperInnerMixin implements SpawnHelperInnerInterface { - @Shadow @Final private int spawningChunkCount; + @Shadow @Final private int spawnableChunkCount; - @Shadow @Final private GravityField densityField; + @Shadow @Final private PotentialCalculator spawnPotential; //@Shadow @Final private Object2IntOpenHashMap groupToCount; @@ -33,14 +32,14 @@ public class SpawnHelperInnerMixin implements SpawnHelperInnerInterface @Override - public GravityField getPotentialCalculator() + public PotentialCalculator getPotentialCalculator() { - return densityField; + return spawnPotential; } @Override public int cmGetChunkCount() { - return spawningChunkCount; + return spawnableChunkCount; } diff --git a/src/main/java/carpet/mixins/SpawnHelperMixin.java b/src/main/java/carpet/mixins/SpawnHelperMixin.java index df3a3331..df9b9180 100644 --- a/src/main/java/carpet/mixins/SpawnHelperMixin.java +++ b/src/main/java/carpet/mixins/SpawnHelperMixin.java @@ -3,31 +3,6 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.WorldInterface; import carpet.utils.SpawnReporter; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.FenceGateBlock; -import net.minecraft.entity.Entity; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.entity.EntityData; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.tag.BlockTags; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.util.shape.VoxelShapes; -import net.minecraft.world.ServerWorldAccess; -import net.minecraft.world.LocalDifficulty; -import net.minecraft.world.SpawnHelper; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.WorldChunk; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -38,19 +13,44 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Map; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.util.Mth; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SpawnGroupData; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.ServerLevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.FenceGateBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; -@Mixin(SpawnHelper.class) +@Mixin(NaturalSpawner.class) public class SpawnHelperMixin { - @Shadow @Final private static int CHUNK_AREA; + @Shadow @Final private static int MAGIC_NUMBER; - @Shadow @Final private static SpawnGroup[] SPAWNABLE_GROUPS; + @Shadow @Final private static MobCategory[] SPAWNING_CATEGORIES; - @Redirect(method = "canSpawn(Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/world/gen/StructureAccessor;Lnet/minecraft/world/gen/chunk/ChunkGenerator;Lnet/minecraft/world/biome/SpawnSettings$SpawnEntry;Lnet/minecraft/util/math/BlockPos$Mutable;D)Z", at = @At( + @Redirect(method = "isValidSpawnPostitionForType(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/world/level/StructureFeatureManager;Lnet/minecraft/world/level/chunk/ChunkGenerator;Lnet/minecraft/world/level/biome/MobSpawnSettings$SpawnerData;Lnet/minecraft/core/BlockPos$MutableBlockPos;D)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;isSpaceEmpty(Lnet/minecraft/util/math/Box;)Z" + target = "Lnet/minecraft/server/level/ServerLevel;noCollision(Lnet/minecraft/world/phys/AABB;)Z" )) - private static boolean doesNotCollide(ServerWorld world, Box bb) + private static boolean doesNotCollide(ServerLevel world, AABB bb) { //.doesNotCollide is VERY expensive. On the other side - most worlds are not made of trapdoors in // various configurations, but solid and 'passable' blocks, like air, water grass, etc. @@ -58,51 +58,51 @@ public class SpawnHelperMixin // in case something more complex happens - we default to full block collision check if (!CarpetSettings.lagFreeSpawning) { - return world.isSpaceEmpty(bb); + return world.noCollision(bb); } - int minX = MathHelper.floor(bb.minX); - int minY = MathHelper.floor(bb.minY); - int minZ = MathHelper.floor(bb.minZ); - int maxY = MathHelper.ceil(bb.maxY)-1; - BlockPos.Mutable blockpos = new BlockPos.Mutable(); - if (bb.getXLength() <= 1) // small mobs + int minX = Mth.floor(bb.minX); + int minY = Mth.floor(bb.minY); + int minZ = Mth.floor(bb.minZ); + int maxY = Mth.ceil(bb.maxY)-1; + BlockPos.MutableBlockPos blockpos = new BlockPos.MutableBlockPos(); + if (bb.getXsize() <= 1) // small mobs { for (int y=minY; y <= maxY; y++) { blockpos.set(minX,y,minZ); VoxelShape box = world.getBlockState(blockpos).getCollisionShape(world, blockpos); - if (box != VoxelShapes.empty()) + if (box != Shapes.empty()) { - if (box == VoxelShapes.fullCube()) + if (box == Shapes.block()) { return false; } else { - return world.isSpaceEmpty(bb); + return world.noCollision(bb); } } } return true; } // this code is only applied for mobs larger than 1 block in footprint - int maxX = MathHelper.ceil(bb.maxX)-1; - int maxZ = MathHelper.ceil(bb.maxZ)-1; + int maxX = Mth.ceil(bb.maxX)-1; + int maxZ = Mth.ceil(bb.maxZ)-1; for (int y = minY; y <= maxY; y++) for (int x = minX; x <= maxX; x++) for (int z = minZ; z <= maxZ; z++) { blockpos.set(x, y, z); VoxelShape box = world.getBlockState(blockpos).getCollisionShape(world, blockpos); - if (box != VoxelShapes.empty()) + if (box != Shapes.empty()) { - if (box == VoxelShapes.fullCube()) + if (box == Shapes.block()) { return false; } else { - return world.isSpaceEmpty(bb); + return world.noCollision(bb); } } } @@ -117,12 +117,12 @@ public class SpawnHelperMixin BlockState state = world.getBlockState(blockpos); Block block = state.getBlock(); if ( - state.isIn(BlockTags.FENCES) || - state.isIn(BlockTags.WALLS) || - ((block instanceof FenceGateBlock) && !state.get(FenceGateBlock.OPEN)) + state.is(BlockTags.FENCES) || + state.is(BlockTags.WALLS) || + ((block instanceof FenceGateBlock) && !state.getValue(FenceGateBlock.OPEN)) ) { - if (x == minX || x == maxX || z == minZ || z == maxZ) return world.isSpaceEmpty(bb); + if (x == minX || x == maxX || z == minZ || z == maxZ) return world.noCollision(bb); return false; } } @@ -130,11 +130,11 @@ public class SpawnHelperMixin return true; } - @Redirect(method = "createMob", at = @At( + @Redirect(method = "getMobForSpawn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/EntityType;create(Lnet/minecraft/world/World;)Lnet/minecraft/entity/Entity;" + target = "Lnet/minecraft/world/entity/EntityType;create(Lnet/minecraft/world/level/Level;)Lnet/minecraft/world/entity/Entity;" )) - private static Entity create(EntityType entityType, World world_1) + private static Entity create(EntityType entityType, Level world_1) { if (CarpetSettings.lagFreeSpawning) { @@ -149,12 +149,12 @@ public class SpawnHelperMixin return entityType.create(world_1); } - @Redirect(method = "spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V", at = @At( + @Redirect(method = "spawnCategoryForPosition(Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkAccess;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/NaturalSpawner$SpawnPredicate;Lnet/minecraft/world/level/NaturalSpawner$AfterSpawnCallback;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/server/world/ServerWorld;spawnEntityAndPassengers(Lnet/minecraft/entity/Entity;)V" + target = "Lnet/minecraft/server/level/ServerLevel;addFreshEntityWithPassengers(Lnet/minecraft/world/entity/Entity;)V" )) - private static void spawnEntity(ServerWorld world, Entity entity_1, - SpawnGroup group, ServerWorld world2, Chunk chunk, BlockPos pos, SpawnHelper.Checker checker, SpawnHelper.Runner runner) + private static void spawnEntity(ServerLevel world, Entity entity_1, + MobCategory group, ServerLevel world2, ChunkAccess chunk, BlockPos pos, NaturalSpawner.SpawnPredicate checker, NaturalSpawner.AfterSpawnCallback runner) { if (CarpetSettings.lagFreeSpawning) // we used the mob - next time we will create a new one when needed @@ -164,35 +164,35 @@ public class SpawnHelperMixin { SpawnReporter.registerSpawn( //world.method_27983(), // getDimensionType //dimension.getType(), // getDimensionType - (MobEntity) entity_1, + (Mob) entity_1, group, //entity_1.getType().getSpawnGroup(), - entity_1.getBlockPos()); + entity_1.blockPosition()); } if (!SpawnReporter.mock_spawns) - world.spawnEntityAndPassengers(entity_1); + world.addFreshEntityWithPassengers(entity_1); //world.spawnEntity(entity_1); } - @Redirect(method = "spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V", at = @At( + @Redirect(method = "spawnCategoryForPosition(Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkAccess;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/NaturalSpawner$SpawnPredicate;Lnet/minecraft/world/level/NaturalSpawner$AfterSpawnCallback;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/mob/MobEntity;initialize(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/world/LocalDifficulty;Lnet/minecraft/entity/SpawnReason;Lnet/minecraft/entity/EntityData;Lnet/minecraft/nbt/NbtCompound;)Lnet/minecraft/entity/EntityData;" + target = "Lnet/minecraft/world/entity/Mob;finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;" )) - private static EntityData spawnEntity(MobEntity mobEntity, ServerWorldAccess serverWorldAccess, LocalDifficulty difficulty, SpawnReason spawnReason, EntityData entityData, NbtCompound entityTag) + private static SpawnGroupData spawnEntity(Mob mobEntity, ServerLevelAccessor serverWorldAccess, DifficultyInstance difficulty, MobSpawnType spawnReason, SpawnGroupData entityData, CompoundTag entityTag) { if (!SpawnReporter.mock_spawns) // WorldAccess - return mobEntity.initialize(serverWorldAccess, difficulty, spawnReason, entityData, entityTag); + return mobEntity.finalizeSpawn(serverWorldAccess, difficulty, spawnReason, entityData, entityTag); return null; } - @Redirect(method = "spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V", at = @At( + @Redirect(method = "spawnCategoryForPosition(Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkAccess;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/NaturalSpawner$SpawnPredicate;Lnet/minecraft/world/level/NaturalSpawner$AfterSpawnCallback;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/player/PlayerEntity;squaredDistanceTo(DDD)D" + target = "Lnet/minecraft/world/entity/player/Player;distanceToSqr(DDD)D" )) - private static double getSqDistanceTo(PlayerEntity playerEntity, double double_1, double double_2, double double_3, - SpawnGroup entityCategory, ServerWorld serverWorld, Chunk chunk, BlockPos blockPos) + private static double getSqDistanceTo(Player playerEntity, double double_1, double double_2, double double_3, + MobCategory entityCategory, ServerLevel serverWorld, ChunkAccess chunk, BlockPos blockPos) { - double distanceTo = playerEntity.squaredDistanceTo(double_1, double_2, double_3); - if (CarpetSettings.lagFreeSpawning && distanceTo > 16384.0D && entityCategory != SpawnGroup.CREATURE) + double distanceTo = playerEntity.distanceToSqr(double_1, double_2, double_3); + if (CarpetSettings.lagFreeSpawning && distanceTo > 16384.0D && entityCategory != MobCategory.CREATURE) return 0.0; return distanceTo; } @@ -201,16 +201,16 @@ public class SpawnHelperMixin //// - @Redirect(method = "spawn", at = @At( + @Redirect(method = "spawnForChunk", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/SpawnHelper;spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/WorldChunk;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V" + target = "Lnet/minecraft/world/level/NaturalSpawner;spawnCategoryForChunk(Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/LevelChunk;Lnet/minecraft/world/level/NaturalSpawner$SpawnPredicate;Lnet/minecraft/world/level/NaturalSpawner$AfterSpawnCallback;)V" )) // inject our repeat of spawns if more spawn ticks per tick are chosen. - private static void spawnMultipleTimes(SpawnGroup category, ServerWorld world, WorldChunk chunk, SpawnHelper.Checker checker, SpawnHelper.Runner runner) + private static void spawnMultipleTimes(MobCategory category, ServerLevel world, LevelChunk chunk, NaturalSpawner.SpawnPredicate checker, NaturalSpawner.AfterSpawnCallback runner) { for (int i = 0; i < SpawnReporter.spawn_tries.get(category); i++) { - SpawnHelper.spawnEntitiesInChunk(category, world, chunk, checker, runner); + NaturalSpawner.spawnCategoryForChunk(category, world, chunk, checker, runner); } } @@ -267,25 +267,25 @@ public class SpawnHelperMixin */ //temporary mixin until naming gets fixed - @Inject(method = "spawn", at = @At("HEAD")) + @Inject(method = "spawnForChunk", at = @At("HEAD")) // allows to change mobcaps and captures each category try per dimension before it fails due to full mobcaps. - private static void checkSpawns(ServerWorld world, WorldChunk chunk, SpawnHelper.Info info, + private static void checkSpawns(ServerLevel world, LevelChunk chunk, NaturalSpawner.SpawnState info, boolean spawnAnimals, boolean spawnMonsters, boolean shouldSpawnAnimals, CallbackInfo ci) { if (SpawnReporter.track_spawns > 0L) { - SpawnGroup[] var6 = SPAWNABLE_GROUPS; + MobCategory[] var6 = SPAWNING_CATEGORIES; int var7 = var6.length; for(int var8 = 0; var8 < var7; ++var8) { - SpawnGroup entityCategory = var6[var8]; - if ((spawnAnimals || !entityCategory.isPeaceful()) && (spawnMonsters || entityCategory.isPeaceful()) && (shouldSpawnAnimals || !entityCategory.isRare()) ) + MobCategory entityCategory = var6[var8]; + if ((spawnAnimals || !entityCategory.isFriendly()) && (spawnMonsters || entityCategory.isFriendly()) && (shouldSpawnAnimals || !entityCategory.isPersistent()) ) { - RegistryKey dim = world.getRegistryKey(); // getDimensionType; - int newCap = entityCategory.getCapacity(); //(int) ((double)entityCategory.getCapacity()*(Math.pow(2.0,(SpawnReporter.mobcap_exponent/4)))); + ResourceKey dim = world.dimension(); // getDimensionType; + int newCap = entityCategory.getMaxInstancesPerChunk(); //(int) ((double)entityCategory.getCapacity()*(Math.pow(2.0,(SpawnReporter.mobcap_exponent/4)))); int int_2 = SpawnReporter.chunkCounts.get(dim); // eligible chunks for spawning - int int_3 = newCap * int_2 / CHUNK_AREA; //current spawning limits - int mobCount = info.getGroupToCount().getInt(entityCategory); + int int_3 = newCap * int_2 / MAGIC_NUMBER; //current spawning limits + int mobCount = info.getMobCategoryCounts().getInt(entityCategory); if (SpawnReporter.track_spawns > 0L && !SpawnReporter.first_chunk_marker.contains(entityCategory)) { diff --git a/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java b/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java index f328921e..1c6fdcf9 100644 --- a/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java +++ b/src/main/java/carpet/mixins/StatePredicate_scarpetMixin.java @@ -4,11 +4,6 @@ import carpet.fakes.BlockPredicateInterface; import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.state.property.Property; -import net.minecraft.tag.Tag; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -16,14 +11,19 @@ import org.spongepowered.asm.mixin.Shadow; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.tags.Tag; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; -@Mixin(targets = "net.minecraft.command.argument.BlockPredicateArgumentType$StatePredicate") +@Mixin(targets = "net.minecraft.commands.arguments.blocks.BlockPredicateArgument$BlockPredicate") public class StatePredicate_scarpetMixin implements BlockPredicateInterface { @Shadow @Final private BlockState state; - @Shadow @Final /*@Nullable*/ private NbtCompound nbt; + @Shadow @Final /*@Nullable*/ private CompoundTag nbt; @Shadow @Final private Set> properties; @@ -50,7 +50,7 @@ public class StatePredicate_scarpetMixin implements BlockPredicateInterface } @Override - public NbtCompound getCMDataTag() + public CompoundTag getCMDataTag() { return nbt; } diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java index 57cf46c6..c6f044fc 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntityRenderer_mixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.entity.StructureBlockBlockEntity; -import net.minecraft.client.render.block.entity.BlockEntityRenderer; -import net.minecraft.client.render.block.entity.StructureBlockBlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.StructureBlockRenderer; +import net.minecraft.world.level.block.entity.StructureBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(StructureBlockBlockEntityRenderer.class) -public abstract class StructureBlockBlockEntityRenderer_mixin implements BlockEntityRenderer +@Mixin(StructureBlockRenderer.class) +public abstract class StructureBlockBlockEntityRenderer_mixin implements BlockEntityRenderer { - @Inject(method = "getRenderDistance", at = @At("HEAD"), cancellable = true) + @Inject(method = "getViewDistance", at = @At("HEAD"), cancellable = true) void newLimit(CallbackInfoReturnable cir) { if (CarpetSettings.structureBlockOutlineDistance != 96) diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java index b7279ace..c8e46c05 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java @@ -1,31 +1,33 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.entity.StructureBlockBlockEntity; -import net.minecraft.structure.Structure; -import net.minecraft.structure.StructurePlacementData; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ServerWorldAccess; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Desc; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ServerLevelAccessor; +import net.minecraft.world.level.block.entity.StructureBlockEntity; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -@Mixin(StructureBlockBlockEntity.class) +@Mixin(StructureBlockEntity.class) public abstract class StructureBlockBlockEntity_fillUpdatesMixin { - @Redirect(method = "place", at = @At( + @Redirect(target = @Desc(args = {ServerLevel.class, boolean.class, StructureTemplate.class}, value = "loadStructure", ret = boolean.class, owner = StructureBlockEntity.class), at = @At( value = "INVOKE", - target = "Lnet/minecraft/structure/Structure;place(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/structure/StructurePlacementData;Ljava/util/Random;I)Z" + desc = @Desc(owner = StructureTemplate.class, value = "placeInWorld", args = {ServerLevelAccessor.class, BlockPos.class, BlockPos.class, StructurePlaceSettings.class, Random.class, int.class}, ret = boolean.class) )) - private boolean onStructurePlacen(Structure structure, ServerWorldAccess serverWorldAccess, BlockPos pos, BlockPos blockPos, StructurePlacementData placementData, Random random, int i) + private boolean onStructurePlacen(StructureTemplate structure, ServerLevelAccessor serverWorldAccess, BlockPos pos, BlockPos blockPos, StructurePlaceSettings placementData, Random random, int i) { if(!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); try { - return structure.place(serverWorldAccess, pos, blockPos, placementData, random, i); // serverWorldAccess, pos, placementData, random); + return structure.placeInWorld(serverWorldAccess, pos, blockPos, placementData, random, i); // serverWorldAccess, pos, placementData, random); } finally { diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java index 8ff19855..6d129df9 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntity_limitsMixin.java @@ -3,19 +3,19 @@ package carpet.mixins; import carpet.CarpetSettings; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.Block; -import net.minecraft.block.entity.StructureBlockBlockEntity; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.StructureBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.ModifyConstant; -@Mixin(StructureBlockBlockEntity.class) +@Mixin(StructureBlockEntity.class) public abstract class StructureBlockBlockEntity_limitsMixin { @ModifyConstant( - method = "readNbt", + method = "load", constant = @Constant(intValue = 48) ) private int positiveLimit(int original) { @@ -23,7 +23,7 @@ public abstract class StructureBlockBlockEntity_limitsMixin } @ModifyConstant( - method = "readNbt", + method = "load", constant = @Constant(intValue = -48) ) private int negativeLimit(int original) { @@ -34,7 +34,7 @@ public abstract class StructureBlockBlockEntity_limitsMixin method = "saveStructure(Z)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/structure/Structure;saveFromWorld(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/Vec3i;ZLnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate;fillFromWorld(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/Vec3i;ZLnet/minecraft/world/level/block/Block;)V" ), index = 4 ) diff --git a/src/main/java/carpet/mixins/StructureFeatureMixin.java b/src/main/java/carpet/mixins/StructureFeatureMixin.java index 6abf3b2b..bd2321b9 100644 --- a/src/main/java/carpet/mixins/StructureFeatureMixin.java +++ b/src/main/java/carpet/mixins/StructureFeatureMixin.java @@ -3,32 +3,6 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.StructureFeatureInterface; import com.google.common.collect.ImmutableMultimap; -//import net.minecraft.class_6834; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.structure.StructureGeneratorFactory; -import net.minecraft.structure.StructurePiecesCollector; -import net.minecraft.structure.StructurePiecesGenerator; -import net.minecraft.structure.StructureStart; -import net.minecraft.util.Util; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.BlockBox; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.HeightLimitView; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.BiomeCoords; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.gen.random.AtomicSimpleRandom; -import net.minecraft.world.gen.random.ChunkRandom; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.feature.ConfiguredStructureFeature; -import net.minecraft.world.gen.feature.DefaultFeatureConfig; -import net.minecraft.world.gen.feature.FeatureConfig; -import net.minecraft.world.gen.feature.StructureFeature; -import net.minecraft.world.gen.random.RandomSeed; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -37,11 +11,31 @@ import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.function.Predicate; +import net.minecraft.Util; +import net.minecraft.core.BlockPos; +import net.minecraft.core.QuartPos; +import net.minecraft.core.Registry; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.RandomSupport; +import net.minecraft.world.level.levelgen.WorldgenRandom; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.levelgen.structure.pieces.PieceGenerator; +import net.minecraft.world.level.levelgen.structure.pieces.PieceGeneratorSupplier; +import net.minecraft.world.level.levelgen.structure.pieces.StructurePiecesBuilder; @Mixin(StructureFeature.class) -public abstract class StructureFeatureMixin implements StructureFeatureInterface +public abstract class StructureFeatureMixin implements StructureFeatureInterface { - @Shadow public abstract String getName(); + @Shadow public abstract String getFeatureName(); //@Shadow public abstract StructureFeature.StructureStartFactory getStructureStartFactory(); @@ -57,12 +51,12 @@ public abstract class StructureFeatureMixin implements //@Shadow @Final private class_6834 piecesGenerator; - @Shadow @Final private StructureGeneratorFactory piecesGenerator; + @Shadow @Final private PieceGeneratorSupplier pieceGenerator; @Override - public boolean plopAnywhere(ServerWorld world, BlockPos pos, ChunkGenerator generator, boolean wireOnly, Biome biome, C config) + public boolean plopAnywhere(ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly, Biome biome, C config) { - if (world.isClient()) + if (world.isClientSide()) return false; CarpetSettings.skipGenerationChecks.set(true); try @@ -70,28 +64,28 @@ public abstract class StructureFeatureMixin implements Random rand = new Random(world.getRandom().nextInt()); int j = pos.getX() >> 4; int k = pos.getZ() >> 4; - long chId = ChunkPos.toLong(j, k); + long chId = ChunkPos.asLong(j, k); StructureStart structurestart = forceStructureStart(world, generator, rand, chId, biome, config); - if (structurestart == StructureStart.DEFAULT) + if (structurestart == StructureStart.INVALID_START) { return false; } StructureFeature thiss = (StructureFeature) (Object)this; - world.getChunk(j, k).addStructureReference(thiss, chId); + world.getChunk(j, k).addReferenceForFeature(thiss, chId); - BlockBox box = structurestart.getBoundingBox(); + BoundingBox box = structurestart.getBoundingBox(); if (!wireOnly) { - Registry> registry3 = world.getRegistryManager().get(Registry.STRUCTURE_FEATURE_KEY); - world.setCurrentlyGeneratingStructureName(() -> { + Registry> registry3 = world.registryAccess().registryOrThrow(Registry.STRUCTURE_FEATURE_REGISTRY); + world.setCurrentlyGenerating(() -> { Objects.requireNonNull(thiss); - return registry3.getKey(thiss).map(Object::toString).orElseGet(thiss::toString); + return registry3.getResourceKey(thiss).map(Object::toString).orElseGet(thiss::toString); }); - structurestart.place(world, world.getStructureAccessor(), generator, rand, box, new ChunkPos(j, k)); + structurestart.placeInChunk(world, world.structureFeatureManager(), generator, rand, box, new ChunkPos(j, k)); } //structurestart.notifyPostProcessAt(new ChunkPos(j, k)); - int i = Math.max(box.getBlockCountX(),box.getBlockCountZ())/16+1; + int i = Math.max(box.getXSpan(),box.getZSpan())/16+1; //int i = getRadius(); for (int k1 = j - i; k1 <= j + i; ++k1) @@ -99,10 +93,10 @@ public abstract class StructureFeatureMixin implements for (int l1 = k - i; l1 <= k + i; ++l1) { if (k1 == j && l1 == k) continue; - long nbchkid = ChunkPos.toLong(k1, l1); - if (box.intersectsXZ(k1<<4, l1<<4, (k1<<4) + 15, (l1<<4) + 15)) + long nbchkid = ChunkPos.asLong(k1, l1); + if (box.intersects(k1<<4, l1<<4, (k1<<4) + 15, (l1<<4) + 15)) { - world.getChunk(k1, l1).addStructureReference(thiss, chId); + world.getChunk(k1, l1).addReferenceForFeature(thiss, chId); } } } @@ -119,39 +113,39 @@ public abstract class StructureFeatureMixin implements return true; } - private StructureStart forceStructureStart(ServerWorld worldIn, ChunkGenerator generator, Random rand, long packedChunkPos, Biome biome, C config) + private StructureStart forceStructureStart(ServerLevel worldIn, ChunkGenerator generator, Random rand, long packedChunkPos, Biome biome, C config) { ChunkPos chunkpos = new ChunkPos(packedChunkPos); - BlockPos centerpos = chunkpos.getBlockPos(9, 0, 9); + BlockPos centerpos = chunkpos.getBlockAt(9, 0, 9); StructureStart structurestart; StructureFeature thiss= (StructureFeature)(Object)this; - Chunk ichunk = worldIn.getChunk(chunkpos.x, chunkpos.z, ChunkStatus.STRUCTURE_STARTS, false); + ChunkAccess ichunk = worldIn.getChunk(chunkpos.x, chunkpos.z, ChunkStatus.STRUCTURE_STARTS, false); if (ichunk != null) { - StructureStart structurestartt = ichunk.getStructureStart(thiss); + StructureStart structurestartt = ichunk.getStartForFeature(thiss); - if (structurestartt != null && structurestartt != StructureStart.DEFAULT) + if (structurestartt != null && structurestartt != StructureStart.INVALID_START) { return (StructureStart) structurestartt; } } Biome biome_1 = biome; if (biome == null) - biome_1 = generator.getBiomeForNoiseGen(BiomeCoords.fromBlock(centerpos.getX()), - BiomeCoords.fromBlock(centerpos.getY()), BiomeCoords.fromBlock(centerpos.getZ())); + biome_1 = generator.getNoiseBiome(QuartPos.fromBlock(centerpos.getX()), + QuartPos.fromBlock(centerpos.getY()), QuartPos.fromBlock(centerpos.getZ())); //if (config == null) // config = (C) new DefaultFeatureConfig(); - Optional> optional = piecesGenerator.createGenerator(new StructureGeneratorFactory.Context<>(generator, generator.getBiomeSource(), worldIn.getSeed(), chunkpos, config, worldIn, b -> true, worldIn.getStructureManager(), worldIn.getRegistryManager())); - if (optional.isEmpty()) return (StructureStart) StructureStart.DEFAULT; - StructurePiecesCollector lv = new StructurePiecesCollector(); - optional.get().generatePieces(lv, new StructurePiecesGenerator.Context(config, generator, worldIn.getStructureManager(), chunkpos, worldIn, Util.make(new ChunkRandom(new AtomicSimpleRandom(RandomSeed.getSeed())), (chunkRandomx) -> { - chunkRandomx.setCarverSeed(worldIn.getSeed(), chunkpos.x, chunkpos.z); + Optional> optional = pieceGenerator.createGenerator(new PieceGeneratorSupplier.Context<>(generator, generator.getBiomeSource(), worldIn.getSeed(), chunkpos, config, worldIn, b -> true, worldIn.getStructureManager(), worldIn.registryAccess())); + if (optional.isEmpty()) return (StructureStart) StructureStart.INVALID_START; + StructurePiecesBuilder lv = new StructurePiecesBuilder(); + optional.get().generatePieces(lv, new PieceGenerator.Context(config, generator, worldIn.getStructureManager(), chunkpos, worldIn, Util.make(new WorldgenRandom(new LegacyRandomSource(RandomSupport.seedUniquifier())), (chunkRandomx) -> { + chunkRandomx.setLargeFeatureSeed(worldIn.getSeed(), chunkpos.x, chunkpos.z); }), worldIn.getSeed())); - StructureStart structurestart1 = new StructureStart<>(thiss, chunkpos, 0, lv.toList()); + StructureStart structurestart1 = new StructureStart<>(thiss, chunkpos, 0, lv.build()); //StructureStart structurestart1 = getStructureStartFactory().create((StructureFeature)(Object)this, chunkpos,0,worldIn.getSeed()); @@ -159,9 +153,9 @@ public abstract class StructureFeatureMixin implements //structurestart1.init(worldIn.getRegistryManager(), generator, worldIn.getStructureManager() , chunkpos, config, ichunk, b -> true); //structurestart = structurestart1.hasChildren() ? structurestart1 : (StructureStart) StructureStart.DEFAULT; - if (structurestart1.hasChildren()) + if (structurestart1.isValid()) { - worldIn.getChunk(chunkpos.x, chunkpos.z).setStructureStart(thiss, structurestart1); + worldIn.getChunk(chunkpos.x, chunkpos.z).setStartForFeature(thiss, structurestart1); } //long2objectmap.put(packedChunkPos, structurestart); diff --git a/src/main/java/carpet/mixins/StructureGeneratorFactory_plopMixin.java b/src/main/java/carpet/mixins/StructureGeneratorFactory_plopMixin.java index b1f55208..1e450b92 100644 --- a/src/main/java/carpet/mixins/StructureGeneratorFactory_plopMixin.java +++ b/src/main/java/carpet/mixins/StructureGeneratorFactory_plopMixin.java @@ -1,18 +1,18 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.structure.StructureGeneratorFactory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.function.Predicate; +import net.minecraft.world.level.levelgen.structure.pieces.PieceGeneratorSupplier; -@Mixin(StructureGeneratorFactory.class) +@Mixin(PieceGeneratorSupplier.class) public interface StructureGeneratorFactory_plopMixin { @SuppressWarnings("UnresolvedMixinReference") - @Redirect(method = "method_39845(Ljava/util/function/Predicate;Ljava/util/Optional;Lnet/minecraft/structure/StructureGeneratorFactory$Context;)Ljava/util/Optional;", at = @At( + @Redirect(method = "lambda$simple$0(Ljava/util/function/Predicate;Ljava/util/Optional;Lnet/minecraft/world/level/levelgen/structure/pieces/PieceGeneratorSupplier$Context;)Ljava/util/Optional;", at = @At( value = "INVOKE", target = "java/util/function/Predicate.test(Ljava/lang/Object;)Z" )) diff --git a/src/main/java/carpet/mixins/StructurePiece_scarpetPlopMixin.java b/src/main/java/carpet/mixins/StructurePiece_scarpetPlopMixin.java index 8c49bd91..9d33016e 100644 --- a/src/main/java/carpet/mixins/StructurePiece_scarpetPlopMixin.java +++ b/src/main/java/carpet/mixins/StructurePiece_scarpetPlopMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.structure.StructurePiece; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.Chunk; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.levelgen.structure.StructurePiece; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -11,12 +11,12 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(StructurePiece.class) public class StructurePiece_scarpetPlopMixin { - @Redirect(method = "addBlock", at = @At( + @Redirect(method = "placeBlock", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/chunk/Chunk;markBlockForPostProcessing(Lnet/minecraft/util/math/BlockPos;)V" + target = "Lnet/minecraft/world/level/chunk/ChunkAccess;markPosForPostprocessing(Lnet/minecraft/core/BlockPos;)V" )) - private void markOrNot(Chunk chunk, BlockPos pos) + private void markOrNot(ChunkAccess chunk, BlockPos pos) { - if (!CarpetSettings.skipGenerationChecks.get()) chunk.markBlockForPostProcessing(pos); + if (!CarpetSettings.skipGenerationChecks.get()) chunk.markPosForPostprocessing(pos); } } diff --git a/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java b/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java index 11b5216e..5836d55b 100644 --- a/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java @@ -1,34 +1,34 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.structure.Structure; -import net.minecraft.structure.StructurePlacementData; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ServerWorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.ServerLevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(Structure.class) +@Mixin(StructureTemplate.class) public class Structure_fillUpdatesMixin { - @Redirect( method = "place(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/structure/StructurePlacementData;Ljava/util/Random;I)Z", at = @At( + @Redirect( method = "placeInWorld(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;Ljava/util/Random;I)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/ServerWorldAccess;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/world/level/ServerLevelAccessor;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" )) - private void skipUpdateNeighbours(ServerWorldAccess serverWorldAccess, BlockPos pos, Block block) + private void skipUpdateNeighbours(ServerLevelAccessor serverWorldAccess, BlockPos pos, Block block) { if (!CarpetSettings.impendingFillSkipUpdates.get()) - serverWorldAccess.updateNeighbors(pos, block); + serverWorldAccess.blockUpdated(pos, block); } - @Redirect(method = "place(Lnet/minecraft/world/ServerWorldAccess;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/structure/StructurePlacementData;Ljava/util/Random;I)Z", at = @At( + @Redirect(method = "placeInWorld(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;Ljava/util/Random;I)Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/structure/StructurePlacementData;shouldUpdateNeighbors()Z" + target = "Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;getKnownShape()Z" )) - private boolean skipPostprocess(StructurePlacementData structurePlacementData) + private boolean skipPostprocess(StructurePlaceSettings structurePlacementData) { - return structurePlacementData.shouldUpdateNeighbors() || CarpetSettings.impendingFillSkipUpdates.get(); + return structurePlacementData.getKnownShape() || CarpetSettings.impendingFillSkipUpdates.get(); } } diff --git a/src/main/java/carpet/mixins/SummonCommandMixin.java b/src/main/java/carpet/mixins/SummonCommandMixin.java index 8825c743..b0d3468c 100644 --- a/src/main/java/carpet/mixins/SummonCommandMixin.java +++ b/src/main/java/carpet/mixins/SummonCommandMixin.java @@ -1,15 +1,15 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LightningEntity; -import net.minecraft.entity.mob.SkeletonHorseEntity; -import net.minecraft.server.command.SummonCommand; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.GameRules; -import net.minecraft.world.LocalDifficulty; +import net.minecraft.core.BlockPos; +import net.minecraft.server.commands.SummonCommand; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.entity.animal.horse.SkeletonHorse; +import net.minecraft.world.level.GameRules; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -17,28 +17,28 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(SummonCommand.class) public class SummonCommandMixin { - @Redirect(method = "execute", at = @At( + @Redirect(method = "spawnEntity", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/Entity;getBlockPos()Lnet/minecraft/util/math/BlockPos;" + target = "Lnet/minecraft/world/entity/Entity;blockPosition()Lnet/minecraft/core/BlockPos;" )) private static BlockPos addRiders(Entity entity) { // [CM] SummonNaturalLightning - if statement around - if (CarpetSettings.summonNaturalLightning && entity instanceof LightningEntity && !entity.getEntityWorld().isClient) + if (CarpetSettings.summonNaturalLightning && entity instanceof LightningBolt && !entity.getCommandSenderWorld().isClientSide) { - ServerWorld world = (ServerWorld) entity.getEntityWorld(); - BlockPos at = entity.getBlockPos(); - LocalDifficulty localDifficulty_1 = world.getLocalDifficulty(at); - boolean boolean_2 = world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && world.random.nextDouble() < (double)localDifficulty_1.getLocalDifficulty() * 0.01D; + ServerLevel world = (ServerLevel) entity.getCommandSenderWorld(); + BlockPos at = entity.blockPosition(); + DifficultyInstance localDifficulty_1 = world.getCurrentDifficultyAt(at); + boolean boolean_2 = world.getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING) && world.random.nextDouble() < (double)localDifficulty_1.getEffectiveDifficulty() * 0.01D; if (boolean_2) { - SkeletonHorseEntity skeletonHorseEntity_1 = EntityType.SKELETON_HORSE.create(world); - skeletonHorseEntity_1.setTrapped(true); - skeletonHorseEntity_1.setBreedingAge(0); - skeletonHorseEntity_1.setPosition(entity.getX(), entity.getY(), entity.getZ()); - world.spawnEntity(skeletonHorseEntity_1); + SkeletonHorse skeletonHorseEntity_1 = EntityType.SKELETON_HORSE.create(world); + skeletonHorseEntity_1.setTrap(true); + skeletonHorseEntity_1.setAge(0); + skeletonHorseEntity_1.setPos(entity.getX(), entity.getY(), entity.getZ()); + world.addFreshEntity(skeletonHorseEntity_1); } } - return entity.getBlockPos(); + return entity.blockPosition(); } } diff --git a/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java b/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java index d6e4fc40..60d0572d 100644 --- a/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java +++ b/src/main/java/carpet/mixins/TagPredicate_scarpetMixin.java @@ -3,25 +3,25 @@ package carpet.mixins; import carpet.fakes.BlockPredicateInterface; import carpet.script.value.StringValue; import carpet.script.value.Value; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.tag.Tag; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.Map; import java.util.stream.Collectors; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.tags.Tag; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; -@Mixin(targets = "net.minecraft.command.argument.BlockPredicateArgumentType$TagPredicate") +@Mixin(targets = "net.minecraft.commands.arguments.blocks.BlockPredicateArgument$TagPredicate") public class TagPredicate_scarpetMixin implements BlockPredicateInterface { @Shadow @Final private Tag tag; - @Shadow @Final private Map properties; + @Shadow @Final private Map vagueProperties; - @Shadow @Final /*@Nullable*/ private NbtCompound nbt; + @Shadow @Final /*@Nullable*/ private CompoundTag nbt; @Override public BlockState getCMBlockState() @@ -38,14 +38,14 @@ public class TagPredicate_scarpetMixin implements BlockPredicateInterface @Override public Map getCMProperties() { - return properties.entrySet().stream().collect(Collectors.toMap( + return vagueProperties.entrySet().stream().collect(Collectors.toMap( e -> new StringValue(e.getKey()), e -> new StringValue(e.getValue()) )); } @Override - public NbtCompound getCMDataTag() + public CompoundTag getCMDataTag() { return nbt; } diff --git a/src/main/java/carpet/mixins/Team_scarpetMixin.java b/src/main/java/carpet/mixins/Team_scarpetMixin.java index ffd0eb59..019c84fe 100644 --- a/src/main/java/carpet/mixins/Team_scarpetMixin.java +++ b/src/main/java/carpet/mixins/Team_scarpetMixin.java @@ -1,13 +1,13 @@ package carpet.mixins; -import net.minecraft.scoreboard.Team; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.world.scores.PlayerTeam; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(Team.class) +@Mixin(PlayerTeam.class) public interface Team_scarpetMixin { @Accessor("color") - Formatting getColor(); + ChatFormatting getColor(); } diff --git a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java index d98a3534..98fbc687 100644 --- a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_scarpetChunkCreationMixin.java @@ -14,10 +14,26 @@ import java.util.stream.Collectors; import carpet.fakes.SimpleEntityLookupInterface; import carpet.fakes.ServerWorldInterface; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.Util; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerTask; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ChunkHolder.ChunkLoadingFailure; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ChunkMap.DistanceManager; +import net.minecraft.server.level.ChunkTaskPriorityQueueSorter; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.server.level.TicketType; +import net.minecraft.server.level.progress.ChunkProgressListener; +import net.minecraft.util.thread.BlockableEventLoop; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.storage.RegionFile; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -38,72 +54,56 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.longs.LongSet; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.minecraft.server.WorldGenerationProgressListener; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.server.world.ChunkHolder.Unloaded; -import net.minecraft.server.world.ChunkTaskPrioritySystem; -import net.minecraft.server.world.ChunkTicketType; -import net.minecraft.server.world.ServerLightingProvider; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.server.world.ThreadedAnvilChunkStorage; -import net.minecraft.server.world.ThreadedAnvilChunkStorage.TicketManager; -import net.minecraft.util.Util; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.thread.ThreadExecutor; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.chunk.WorldChunk; -import net.minecraft.world.storage.RegionFile; import static carpet.script.CarpetEventServer.Event.CHUNK_GENERATED; import static carpet.script.CarpetEventServer.Event.CHUNK_LOADED; -@Mixin(ThreadedAnvilChunkStorage.class) +@Mixin(ChunkMap.class) public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implements ThreadedAnvilChunkStorageInterface { @Shadow @Final - private ServerWorld world; + private ServerLevel level; @Shadow @Final - private LongSet loadedChunks; + private LongSet entitiesInLevel; @Shadow @Final - private Long2ObjectLinkedOpenHashMap currentChunkHolders; + private Long2ObjectLinkedOpenHashMap updatingChunkMap; @Shadow - private boolean chunkHolderListDirty; + private boolean modified; @Shadow @Final - private ServerLightingProvider lightingProvider; + private ThreadedLevelLightEngine lightEngine; @Shadow @Final - private ChunkTaskPrioritySystem chunkTaskPrioritySystem; + private ChunkTaskPriorityQueueSorter queueSorter; @Shadow @Final - private ThreadExecutor mainThreadExecutor; + private BlockableEventLoop mainThreadExecutor; @Shadow @Final - private WorldGenerationProgressListener worldGenerationProgressListener; + private ChunkProgressListener progressListener; @Shadow @Final - private TicketManager ticketManager; + private DistanceManager distanceManager; @Shadow - protected abstract boolean updateHolderMap(); + protected abstract boolean promoteChunkMap(); @Shadow - protected abstract CompletableFuture, Unloaded>> getRegion (final ChunkPos centerChunk, final int margin, final IntFunction distanceToStatus); + protected abstract CompletableFuture, ChunkLoadingFailure>> getChunkRangeFuture (final ChunkPos centerChunk, final int margin, final IntFunction distanceToStatus); @Shadow - protected abstract Iterable entryIterator(); + protected abstract Iterable getChunks(); ThreadLocal generated = ThreadLocal.withInitial(() -> null); @@ -111,12 +111,12 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // in convertToFullChunk // fancier version of the one below, ensuring that the event is triggered when the chunk is actually loaded. @SuppressWarnings("UnresolvedMixinReference") - @Inject(method = "method_20460", at = @At("HEAD")) - private void onChunkGeneratedStart(ChunkHolder chunkHolder, Either chunk, CallbackInfoReturnable>> cir) + @Inject(method = "lambda$protoChunkToFullChunk$28", at = @At("HEAD")) + private void onChunkGeneratedStart(ChunkHolder chunkHolder, Either chunk, CallbackInfoReturnable>> cir) { if (CHUNK_GENERATED.isNeeded() || CHUNK_LOADED.isNeeded()) { - generated.set(chunkHolder.getCurrentChunk().getStatus() != ChunkStatus.FULL); + generated.set(chunkHolder.getLastAvailable().getStatus() != ChunkStatus.FULL); } else { @@ -125,21 +125,21 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem } @SuppressWarnings("UnresolvedMixinReference") - @Inject(method = "method_20460", at = @At("RETURN")) - private void onChunkGeneratedEnd(ChunkHolder chunkHolder, Either chunk, CallbackInfoReturnable>> cir) + @Inject(method = "lambda$protoChunkToFullChunk$28", at = @At("RETURN")) + private void onChunkGeneratedEnd(ChunkHolder chunkHolder, Either chunk, CallbackInfoReturnable>> cir) { Boolean localGenerated= generated.get(); if (localGenerated != null) { - MinecraftServer server = this.world.getServer(); - int ticks = server.getTicks(); + MinecraftServer server = this.level.getServer(); + int ticks = server.getTickCount(); ChunkPos chpos = chunkHolder.getPos(); // need to send these because if an app does something with that event, it may lock the thread // so better be safe and schedule it for later, aSaP if (CHUNK_GENERATED.isNeeded() && localGenerated) - server.send(new ServerTask(ticks, () -> CHUNK_GENERATED.onChunkEvent(this.world, chpos, true))); + server.tell(new TickTask(ticks, () -> CHUNK_GENERATED.onChunkEvent(this.level, chpos, true))); if (CHUNK_LOADED.isNeeded()) - server.send(new ServerTask(ticks, () -> CHUNK_LOADED.onChunkEvent(this.world, chpos, localGenerated))); + server.tell(new TickTask(ticks, () -> CHUNK_LOADED.onChunkEvent(this.level, chpos, localGenerated))); } } @@ -164,7 +164,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Unique private void addTicket(final ChunkPos pos, final ChunkStatus status) { // UNKNOWN - this.ticketManager.addTicketWithLevel(ChunkTicketType.UNKNOWN, pos, 33 + ChunkStatus.getDistanceFromFull(status), pos); + this.distanceManager.addTicket(TicketType.UNKNOWN, pos, 33 + ChunkStatus.getDistance(status), pos); } @Unique @@ -176,14 +176,14 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Unique private void addRelightTicket(final ChunkPos pos) { - this.ticketManager.addTicket(ChunkTicketType.LIGHT, pos, 1, pos); + this.distanceManager.addRegionTicket(TicketType.LIGHT, pos, 1, pos); } @Override public void releaseRelightTicket(final ChunkPos pos) { - this.mainThreadExecutor.send(Util.debugRunnable( - () -> this.ticketManager.removeTicket(ChunkTicketType.LIGHT, pos, 1, pos), + this.mainThreadExecutor.tell(Util.name( + () -> this.distanceManager.removeRegionTicket(TicketType.LIGHT, pos, 1, pos), () -> "release relight ticket " + pos )); } @@ -191,7 +191,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Unique private void tickTicketManager() { - this.ticketManager.tick((ThreadedAnvilChunkStorage) (Object) this); + this.distanceManager.runAllUpdates((ChunkMap) (Object) this); } @Unique @@ -201,7 +201,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem final Set ret = new HashSet<>(); for (final ChunkPos pos : requestedChunks) - if (WorldTools.canHasChunk(this.world, pos, regionCache, true)) + if (WorldTools.canHasChunk(this.level, pos, regionCache, true)) ret.add(pos); return ret; @@ -212,7 +212,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem { final Set existingChunks = this.getExistingChunks(requestedChunks); for (final ChunkPos pos : existingChunks) - this.currentChunkHolders.get(pos.toLong()).getChunkAt(ChunkStatus.EMPTY, (ThreadedAnvilChunkStorage) (Object) this); + this.updatingChunkMap.get(pos.toLong()).getOrScheduleFuture(ChunkStatus.EMPTY, (ChunkMap) (Object) this); return existingChunks; } @@ -234,7 +234,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // Fetch all currently loaded chunks final Set loadedChunks = requestedChunks.stream().filter( - pos -> this.currentChunkHolders.get(pos.toLong()).getCurrentChunk() != null // all relevant ChunkHolders exist + pos -> this.updatingChunkMap.get(pos.toLong()).getLastAvailable() != null // all relevant ChunkHolders exist ).collect(Collectors.toSet()); if (report != null) @@ -261,19 +261,19 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Unique private void waitFor(final Future future) { - this.mainThreadExecutor.runTasks(future::isDone); + this.mainThreadExecutor.managedBlock(future::isDone); } @Unique private void waitFor(final List> futures) { - this.waitFor(Util.combine(futures)); + this.waitFor(Util.sequenceFailFast(futures)); } @Unique - private Chunk getCurrentChunk(final ChunkPos pos) + private ChunkAccess getCurrentChunk(final ChunkPos pos) { - final CompletableFuture future = this.currentChunkHolders.get(pos.toLong()).getSavingFuture(); + final CompletableFuture future = this.updatingChunkMap.get(pos.toLong()).getChunkToSave(); this.waitFor(future); return future.join(); @@ -284,17 +284,17 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem { this.addTicket(pos); this.tickTicketManager(); - if (this.currentChunkHolders.get(pos.toLong()).getCurrentChunk() == null) // chunk unloaded - if (WorldTools.canHasChunk(this.world, pos, null, true)) - this.currentChunkHolders.get(pos.toLong()).getChunkAt(ChunkStatus.EMPTY, (ThreadedAnvilChunkStorage) (Object) this); - final Chunk chunk = this.getCurrentChunk(pos); - if (!(chunk.getStatus().isAtLeast(ChunkStatus.LIGHT.getPrevious()))) return; - ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); + if (this.updatingChunkMap.get(pos.toLong()).getLastAvailable() == null) // chunk unloaded + if (WorldTools.canHasChunk(this.level, pos, null, true)) + this.updatingChunkMap.get(pos.toLong()).getOrScheduleFuture(ChunkStatus.EMPTY, (ChunkMap) (Object) this); + final ChunkAccess chunk = this.getCurrentChunk(pos); + if (!(chunk.getStatus().isOrAfter(ChunkStatus.LIGHT.getParent()))) return; + ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk); this.addRelightTicket(pos); - final CompletableFuture lightFuture = this.getRegion (pos, 1, (pos_) -> ChunkStatus.LIGHT) + final CompletableFuture lightFuture = this.getChunkRangeFuture (pos, 1, (pos_) -> ChunkStatus.LIGHT) .thenCompose( either -> either.map( - list -> ((ServerLightingProviderInterface) this.lightingProvider).relight(chunk), + list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk), unloaded -> { this.releaseRelightTicket(pos); return CompletableFuture.completedFuture(null); @@ -317,7 +317,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // Finish pending generation stages // This ensures that no generation events will be put back on the main thread after the chunks have been deleted - final Set affectedChunks = new HashSet<>(); + final Set affectedChunks = new HashSet<>(); for (final ChunkPos pos : existingChunks) affectedChunks.add(this.getCurrentChunk(pos)); @@ -328,7 +328,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem final Set neighbors = new HashSet<>(); - for (final Chunk chunk : affectedChunks) + for (final ChunkAccess chunk : affectedChunks) { final ChunkPos pos = chunk.getPos(); @@ -346,79 +346,79 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // Determine affected neighbors - final Set affectedNeighbors = new HashSet<>(); + final Set affectedNeighbors = new HashSet<>(); for (final ChunkPos pos : neighbors) { - final Chunk chunk = this.getCurrentChunk(pos); + final ChunkAccess chunk = this.getCurrentChunk(pos); - if (chunk.getStatus().isAtLeast(ChunkStatus.LIGHT.getPrevious())) + if (chunk.getStatus().isOrAfter(ChunkStatus.LIGHT.getParent())) affectedNeighbors.add(chunk); } // Unload affected chunks - for (final Chunk chunk : affectedChunks) + for (final ChunkAccess chunk : affectedChunks) { final ChunkPos pos = chunk.getPos(); // remove entities long longPos = pos.toLong(); - if (this.loadedChunks.contains(longPos) && chunk instanceof WorldChunk) - ((SimpleEntityLookupInterface)((ServerWorldInterface)world).getEntityLookupCMPublic()).getChunkEntities(pos).forEach(entity -> { if (!(entity instanceof PlayerEntity)) entity.discard();}); + if (this.entitiesInLevel.contains(longPos) && chunk instanceof LevelChunk) + ((SimpleEntityLookupInterface)((ServerWorldInterface)level).getEntityLookupCMPublic()).getChunkEntities(pos).forEach(entity -> { if (!(entity instanceof Player)) entity.discard();}); - if (chunk instanceof WorldChunk) - ((WorldChunk) chunk).setLoadedToWorld(false); + if (chunk instanceof LevelChunk) + ((LevelChunk) chunk).setLoaded(false); - if (this.loadedChunks.remove(pos.toLong()) && chunk instanceof WorldChunk) - this.world.unloadEntities((WorldChunk) chunk); // block entities only + if (this.entitiesInLevel.remove(pos.toLong()) && chunk instanceof LevelChunk) + this.level.unload((LevelChunk) chunk); // block entities only - ((ServerLightingProviderInterface) this.lightingProvider).invokeUpdateChunkStatus(pos); - ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); + ((ServerLightingProviderInterface) this.lightEngine).invokeUpdateChunkStatus(pos); + ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk); - this.worldGenerationProgressListener.setChunkStatus(pos, null); + this.progressListener.onStatusChange(pos, null); } // Replace ChunkHolders - for (final Chunk chunk : affectedChunks) + for (final ChunkAccess chunk : affectedChunks) { final ChunkPos cPos = chunk.getPos(); final long pos = cPos.toLong(); - final ChunkHolder oldHolder = this.currentChunkHolders.remove(pos); - final ChunkHolder newHolder = new ChunkHolder(cPos, oldHolder.getLevel(), world, this.lightingProvider, this.chunkTaskPrioritySystem, (ChunkHolder.PlayersWatchingChunkProvider) this); - ((ChunkHolderInterface) newHolder).setDefaultProtoChunk(cPos, this.mainThreadExecutor, world); // enable chunk blending? - this.currentChunkHolders.put(pos, newHolder); + final ChunkHolder oldHolder = this.updatingChunkMap.remove(pos); + final ChunkHolder newHolder = new ChunkHolder(cPos, oldHolder.getTicketLevel(), level, this.lightEngine, this.queueSorter, (ChunkHolder.PlayerProvider) this); + ((ChunkHolderInterface) newHolder).setDefaultProtoChunk(cPos, this.mainThreadExecutor, level); // enable chunk blending? + this.updatingChunkMap.put(pos, newHolder); - ((ChunkTicketManagerInterface) this.ticketManager).replaceHolder(oldHolder, newHolder); + ((ChunkTicketManagerInterface) this.distanceManager).replaceHolder(oldHolder, newHolder); } - this.chunkHolderListDirty = true; - this.updateHolderMap(); + this.modified = true; + this.promoteChunkMap(); // Remove light for affected neighbors - for (final Chunk chunk : affectedNeighbors) - ((ServerLightingProviderInterface) this.lightingProvider).removeLightData(chunk); + for (final ChunkAccess chunk : affectedNeighbors) + ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk); // Schedule relighting of neighbors - for (final Chunk chunk : affectedNeighbors) + for (final ChunkAccess chunk : affectedNeighbors) this.addRelightTicket(chunk.getPos()); this.tickTicketManager(); final List> lightFutures = new ArrayList<>(); - for (final Chunk chunk : affectedNeighbors) + for (final ChunkAccess chunk : affectedNeighbors) { final ChunkPos pos = chunk.getPos(); - lightFutures.add(this.getRegion (pos, 1, (pos_) -> ChunkStatus.LIGHT).thenCompose( + lightFutures.add(this.getChunkRangeFuture (pos, 1, (pos_) -> ChunkStatus.LIGHT).thenCompose( either -> either.map( - list -> ((ServerLightingProviderInterface) this.lightingProvider).relight(chunk), + list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk), unloaded -> { this.releaseRelightTicket(pos); return CompletableFuture.completedFuture(null); @@ -432,7 +432,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem // Also, this is needed to ensure chunks are saved to disk final Map targetGenerationStatus = affectedChunks.stream().collect( - Collectors.toMap(Chunk::getPos, Chunk::getStatus) + Collectors.toMap(ChunkAccess::getPos, ChunkAccess::getStatus) ); for (final Entry entry : targetGenerationStatus.entrySet()) @@ -445,7 +445,7 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem for (final Entry entry : targetGenerationStatus.entrySet()) targetGenerationFutures.add(Pair.of( entry.getValue(), - this.currentChunkHolders.get(entry.getKey().toLong()).getChunkAt(entry.getValue(), (ThreadedAnvilChunkStorage) (Object) this) + this.updatingChunkMap.get(entry.getKey().toLong()).getOrScheduleFuture(entry.getValue(), (ChunkMap) (Object) this) )); final Map>> targetGenerationFuturesGrouped = targetGenerationFutures.stream().collect( @@ -458,19 +458,19 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem ) ); - for (final ChunkStatus status : ChunkStatus.createOrderedList()) + for (final ChunkStatus status : ChunkStatus.getStatusList()) { final List> futures = targetGenerationFuturesGrouped.get(status); if (futures == null) continue; - report.put("layer_count_" + status.getId(), futures.size()); + report.put("layer_count_" + status.getName(), futures.size()); final long start = System.currentTimeMillis(); this.waitFor(futures); - report.put("layer_time_" + status.getId(), (int) (System.currentTimeMillis() - start)); + report.put("layer_time_" + status.getName(), (int) (System.currentTimeMillis() - start)); } report.put("relight_count", lightFutures.size()); @@ -485,6 +485,6 @@ public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implem @Override public Iterable getChunksCM() { - return entryIterator(); + return getChunks(); } } diff --git a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_tickMixin.java b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_tickMixin.java index 35044b84..48662c0b 100644 --- a/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_tickMixin.java +++ b/src/main/java/carpet/mixins/ThreadedAnvilChunkStorage_tickMixin.java @@ -1,8 +1,6 @@ package carpet.mixins; import carpet.utils.CarpetProfiler; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.server.world.ThreadedAnvilChunkStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,17 +9,19 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.function.BooleanSupplier; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerLevel; -@Mixin(ThreadedAnvilChunkStorage.class) +@Mixin(ChunkMap.class) public class ThreadedAnvilChunkStorage_tickMixin { - @Shadow @Final private ServerWorld world; + @Shadow @Final private ServerLevel level; CarpetProfiler.ProfilerToken currentSection; @Inject(method = "tick", at = @At("HEAD")) private void startProfilerSection(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - currentSection = CarpetProfiler.start_section(world, "Unloading", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section(level, "Unloading", CarpetProfiler.TYPE.GENERAL); } @Inject(method = "tick", at = @At("RETURN")) diff --git a/src/main/java/carpet/mixins/ThrownEntityMixin.java b/src/main/java/carpet/mixins/ThrownEntityMixin.java index f1eb5f35..e82c5a32 100644 --- a/src/main/java/carpet/mixins/ThrownEntityMixin.java +++ b/src/main/java/carpet/mixins/ThrownEntityMixin.java @@ -2,26 +2,26 @@ package carpet.mixins; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.TrajectoryLogHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.projectile.ProjectileEntity; -import net.minecraft.entity.projectile.thrown.ThrownEntity; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.ThrowableProjectile; +import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(ThrownEntity.class) +@Mixin(ThrowableProjectile.class) public abstract class ThrownEntityMixin extends Entity { private TrajectoryLogHelper logHelper; - public ThrownEntityMixin(EntityType entityType_1, World world_1) { super(entityType_1, world_1); } + public ThrownEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Inject(method = "(Lnet/minecraft/entity/EntityType;Lnet/minecraft/world/World;)V", at = @At("RETURN")) - private void addLogger(EntityType entityType_1, World world_1, CallbackInfo ci) + @Inject(method = "(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V", at = @At("RETURN")) + private void addLogger(EntityType entityType_1, Level world_1, CallbackInfo ci) { - if (LoggerRegistry.__projectiles && !world_1.isClient) + if (LoggerRegistry.__projectiles && !world_1.isClientSide) logHelper = new TrajectoryLogHelper("projectiles"); } @@ -29,7 +29,7 @@ public abstract class ThrownEntityMixin extends Entity private void tickCheck(CallbackInfo ci) { if (LoggerRegistry.__projectiles && logHelper != null) - logHelper.onTick(getX(), getY(), getZ(), getVelocity()); + logHelper.onTick(getX(), getY(), getZ(), getDeltaMovement()); } @Override diff --git a/src/main/java/carpet/mixins/TntBlockMixin.java b/src/main/java/carpet/mixins/TntBlockMixin.java index c6664ef7..02f238ac 100644 --- a/src/main/java/carpet/mixins/TntBlockMixin.java +++ b/src/main/java/carpet/mixins/TntBlockMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.TntBlock; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.TntBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -12,10 +12,10 @@ import org.spongepowered.asm.mixin.injection.Redirect; public abstract class TntBlockMixin { // Add carpet rule check for tntDoNotUpdate to an if statement. - @Redirect(method = "onBlockAdded", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/World;isReceivingRedstonePower(Lnet/minecraft/util/math/BlockPos;)Z")) - private boolean isTNTDoNotUpdate(World world, BlockPos blockPos) + @Redirect(method = "onPlace", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/Level;hasNeighborSignal(Lnet/minecraft/core/BlockPos;)Z")) + private boolean isTNTDoNotUpdate(Level world, BlockPos blockPos) { - return !CarpetSettings.tntDoNotUpdate && world.isReceivingRedstonePower(blockPos); + return !CarpetSettings.tntDoNotUpdate && world.hasNeighborSignal(blockPos); } } diff --git a/src/main/java/carpet/mixins/TntEntityMixin.java b/src/main/java/carpet/mixins/TntEntityMixin.java index 52849252..0aaef2c0 100644 --- a/src/main/java/carpet/mixins/TntEntityMixin.java +++ b/src/main/java/carpet/mixins/TntEntityMixin.java @@ -2,13 +2,6 @@ package carpet.mixins; import carpet.fakes.TntEntityInterface; import carpet.CarpetSettings; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.TntEntity; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.explosion.Explosion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -16,8 +9,15 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import carpet.logging.LoggerRegistry; import carpet.logging.logHelpers.TNTLogHelper; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; -@Mixin(TntEntity.class) +@Mixin(PrimedTnt.class) public abstract class TntEntityMixin extends Entity implements TntEntityInterface { //@Shadow private int fuseTimer; @@ -28,24 +28,24 @@ public abstract class TntEntityMixin extends Entity implements TntEntityInterfac private boolean mergeBool = false; private int mergedTNT = 1; - public TntEntityMixin(EntityType entityType_1, World world_1) + public TntEntityMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } - @Inject(method = "(Lnet/minecraft/world/World;DDDLnet/minecraft/entity/LivingEntity;)V", + @Inject(method = "(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/entity/LivingEntity;)V", at = @At("RETURN")) - private void modifyTNTAngle(World world, double x, double y, double z, LivingEntity entity, CallbackInfo ci) + private void modifyTNTAngle(Level world, double x, double y, double z, LivingEntity entity, CallbackInfo ci) { if (CarpetSettings.hardcodeTNTangle != -1.0D) - setVelocity(-Math.sin(CarpetSettings.hardcodeTNTangle) * 0.02, 0.2, -Math.cos(CarpetSettings.hardcodeTNTangle) * 0.02); + setDeltaMovement(-Math.sin(CarpetSettings.hardcodeTNTangle) * 0.02, 0.2, -Math.cos(CarpetSettings.hardcodeTNTangle) * 0.02); } - @Inject(method = "(Lnet/minecraft/entity/EntityType;Lnet/minecraft/world/World;)V", at = @At("RETURN")) - private void initTNTLoggerPrime(EntityType entityType_1, World world_1, CallbackInfo ci) + @Inject(method = "(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V", at = @At("RETURN")) + private void initTNTLoggerPrime(EntityType entityType_1, Level world_1, CallbackInfo ci) { - if (LoggerRegistry.__tnt && !world_1.isClient) + if (LoggerRegistry.__tnt && !world_1.isClientSide) { logHelper = new TNTLogHelper(); } @@ -56,48 +56,48 @@ public abstract class TntEntityMixin extends Entity implements TntEntityInterfac { if (LoggerRegistry.__tnt && logHelper != null && !logHelper.initialized) { - logHelper.onPrimed(getX(), getY(), getZ(), getVelocity()); + logHelper.onPrimed(getX(), getY(), getZ(), getDeltaMovement()); } } - @Inject(method = "(Lnet/minecraft/world/World;DDDLnet/minecraft/entity/LivingEntity;)V", + @Inject(method = "(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/entity/LivingEntity;)V", at = @At(value = "RETURN")) - private void initTNTLogger(World world_1, double double_1, double double_2, double double_3, + private void initTNTLogger(Level world_1, double double_1, double double_2, double double_3, LivingEntity livingEntity_1, CallbackInfo ci) { if(CarpetSettings.tntPrimerMomentumRemoved) - this.setVelocity(new Vec3d(0.0, 0.20000000298023224D, 0.0)); + this.setDeltaMovement(new Vec3(0.0, 0.20000000298023224D, 0.0)); } @Inject(method = "explode", at = @At(value = "HEAD")) private void onExplode(CallbackInfo ci) { if (LoggerRegistry.__tnt && logHelper != null) - logHelper.onExploded(getX(), getY(), getZ(), this.world.getTime()); + logHelper.onExploded(getX(), getY(), getZ(), this.level.getGameTime()); if (mergedTNT > 1) for (int i = 0; i < mergedTNT - 1; i++) - this.world.createExplosion(this, this.getX(), this.getY() + (double)(this.getHeight() / 16.0F), + this.level.explode(this, this.getX(), this.getY() + (double)(this.getBbHeight() / 16.0F), this.getZ(), 4.0F, - Explosion.DestructionType.BREAK); + Explosion.BlockInteraction.BREAK); } @Inject(method = "tick", at = @At(value = "INVOKE", - target = "Lnet/minecraft/entity/TntEntity;setVelocity(Lnet/minecraft/util/math/Vec3d;)V", + target = "Lnet/minecraft/world/entity/item/PrimedTnt;setDeltaMovement(Lnet/minecraft/world/phys/Vec3;)V", ordinal = 2)) private void tryMergeTnt(CallbackInfo ci) { // Merge code for combining tnt into a single entity if they happen to exist in the same spot, same fuse, no motion CARPET-XCOM if(CarpetSettings.mergeTNT){ - Vec3d velocity = getVelocity(); - if(!world.isClient && mergeBool && velocity.x == 0 && velocity.y == 0 && velocity.z == 0){ + Vec3 velocity = getDeltaMovement(); + if(!level.isClientSide && mergeBool && velocity.x == 0 && velocity.y == 0 && velocity.z == 0){ mergeBool = false; - for(Entity entity : world.getOtherEntities(this, this.getBoundingBox())){ - if(entity instanceof TntEntity && !entity.isRemoved()){ - TntEntity entityTNTPrimed = (TntEntity)entity; - Vec3d tntVelocity = entityTNTPrimed.getVelocity(); + for(Entity entity : level.getEntities(this, this.getBoundingBox())){ + if(entity instanceof PrimedTnt && !entity.isRemoved()){ + PrimedTnt entityTNTPrimed = (PrimedTnt)entity; + Vec3 tntVelocity = entityTNTPrimed.getDeltaMovement(); if(tntVelocity.x == 0 && tntVelocity.y == 0 && tntVelocity.z == 0 && this.getX() == entityTNTPrimed.getX() && this.getZ() == entityTNTPrimed.getZ() && this.getY() == entityTNTPrimed.getY() && getFuse() == entityTNTPrimed.getFuse()){ @@ -110,12 +110,12 @@ public abstract class TntEntityMixin extends Entity implements TntEntityInterfac } } - @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/TntEntity;setFuse(I)V")) + @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/item/PrimedTnt;setFuse(I)V")) private void setMergeable(CallbackInfo ci) { // Merge code, merge only tnt that have had a chance to move CARPET-XCOM - Vec3d velocity = getVelocity(); - if(!world.isClient && (velocity.y != 0 || velocity.x != 0 || velocity.z != 0)){ + Vec3 velocity = getDeltaMovement(); + if(!level.isClientSide && (velocity.y != 0 || velocity.x != 0 || velocity.z != 0)){ mergeBool = true; } } diff --git a/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java b/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java index dd7cef1e..c87f71fe 100644 --- a/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/TradeOutputSlot_scarpetEventMixin.java @@ -1,11 +1,5 @@ package carpet.mixins; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.slot.TradeOutputSlot; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.village.Merchant; -import net.minecraft.village.MerchantInventory; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -17,19 +11,26 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import static carpet.script.CarpetEventServer.Event.PLAYER_TRADES; -@Mixin(value = TradeOutputSlot.class) +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.MerchantContainer; +import net.minecraft.world.inventory.MerchantResultSlot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.trading.Merchant; + +@Mixin(value = MerchantResultSlot.class) public abstract class TradeOutputSlot_scarpetEventMixin { @Shadow @Final private Merchant merchant; - @Shadow @Final private MerchantInventory merchantInventory; + @Shadow @Final private MerchantContainer slots; - @Inject(method = "onTakeItem", at = @At(value = "INVOKE", - target = "Lnet/minecraft/village/Merchant;trade(Lnet/minecraft/village/TradeOffer;)V") + @Inject(method = "onTake", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/item/trading/Merchant;notifyTrade(Lnet/minecraft/world/item/trading/MerchantOffer;)V") ) - private void onTrade(PlayerEntity player, ItemStack stack, CallbackInfo ci) { - if(PLAYER_TRADES.isNeeded() && !player.world.isClient()) + private void onTrade(Player player, ItemStack stack, CallbackInfo ci) { + if(PLAYER_TRADES.isNeeded() && !player.level.isClientSide()) { - PLAYER_TRADES.onTrade((ServerPlayerEntity) player, merchant, merchantInventory.getTradeOffer()); + PLAYER_TRADES.onTrade((ServerPlayer) player, merchant, slots.getActiveOffer()); } } } diff --git a/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java b/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java index e67f342a..61cc35c7 100644 --- a/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java +++ b/src/main/java/carpet/mixins/UpdateStructureBlockC2SPacketMixin.java @@ -3,11 +3,11 @@ package carpet.mixins; import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.network.CarpetClient; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.c2s.play.UpdateStructureBlockC2SPacket; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3i; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Vec3i; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerboundSetStructureBlockPacket; +import net.minecraft.util.Mth; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; @@ -16,7 +16,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(UpdateStructureBlockC2SPacket.class) +@Mixin(ServerboundSetStructureBlockPacket.class) public class UpdateStructureBlockC2SPacketMixin { @Mutable @Final @Shadow private BlockPos offset; @@ -24,14 +24,14 @@ public class UpdateStructureBlockC2SPacketMixin { private Vec3i size; @Inject( - method = "(Lnet/minecraft/network/PacketByteBuf;)V", + method = "(Lnet/minecraft/network/FriendlyByteBuf;)V", at = @At("TAIL") ) - private void structureBlockLimitsRead(PacketByteBuf buf, CallbackInfo ci) { + private void structureBlockLimitsRead(FriendlyByteBuf buf, CallbackInfo ci) { if (buf.readableBytes() == 6*4) { // This will throw an exception if carpet is not installed on client - offset = new BlockPos(MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit)); - size = new Vec3i(MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), MathHelper.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit)); + offset = new BlockPos(Mth.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), Mth.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit), Mth.clamp(buf.readInt(), -CarpetSettings.structureBlockLimit, CarpetSettings.structureBlockLimit)); + size = new Vec3i(Mth.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), Mth.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit), Mth.clamp(buf.readInt(), 0, CarpetSettings.structureBlockLimit)); } } @@ -39,7 +39,7 @@ public class UpdateStructureBlockC2SPacketMixin { method = "write", at = @At("TAIL") ) - private void structureBlockLimitsWrite(PacketByteBuf buf, CallbackInfo ci) { + private void structureBlockLimitsWrite(FriendlyByteBuf buf, CallbackInfo ci) { //client method, only applicable if with carpet is on the server, or running locally if (CarpetSettings.structureBlockLimit != CarpetSettings.vanillaStructureBlockLimit) { diff --git a/src/main/java/carpet/mixins/VillagerEntity_aiMixin.java b/src/main/java/carpet/mixins/VillagerEntity_aiMixin.java index 1810c48e..3539b879 100644 --- a/src/main/java/carpet/mixins/VillagerEntity_aiMixin.java +++ b/src/main/java/carpet/mixins/VillagerEntity_aiMixin.java @@ -3,31 +3,6 @@ package carpet.mixins; import carpet.helpers.ParticleDisplay; import carpet.utils.Messenger; import carpet.utils.MobAI; -import net.minecraft.block.Blocks; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.ai.brain.Activity; -import net.minecraft.entity.ai.brain.Memory; -import net.minecraft.entity.ai.brain.MemoryModuleType; -import net.minecraft.entity.ai.pathing.Path; -import net.minecraft.entity.passive.MerchantEntity; -import net.minecraft.entity.passive.VillagerEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.BedItem; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.particle.BlockStateParticleEffect; -import net.minecraft.particle.ParticleTypes; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.ActionResult; -import net.minecraft.util.dynamic.GlobalPos; -import net.minecraft.util.Hand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.poi.PointOfInterest; -import net.minecraft.world.poi.PointOfInterestStorage; -import net.minecraft.world.poi.PointOfInterestType; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -38,21 +13,46 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.particles.BlockParticleOption; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.memory.ExpirableValue; +import net.minecraft.world.entity.ai.memory.MemoryModuleType; +import net.minecraft.world.entity.ai.village.poi.PoiManager; +import net.minecraft.world.entity.ai.village.poi.PoiRecord; +import net.minecraft.world.entity.ai.village.poi.PoiType; +import net.minecraft.world.entity.npc.AbstractVillager; +import net.minecraft.world.entity.npc.Villager; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.schedule.Activity; +import net.minecraft.world.item.BedItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; -@Mixin(VillagerEntity.class) -public abstract class VillagerEntity_aiMixin extends MerchantEntity +@Mixin(Villager.class) +public abstract class VillagerEntity_aiMixin extends AbstractVillager { - @Shadow protected abstract void sayNo(); + @Shadow protected abstract void setUnhappy(); - @Shadow protected abstract int getAvailableFood(); + @Shadow protected abstract int countFoodPointsInInventory(); - @Shadow public abstract void eatForBreeding(); + @Shadow public abstract void eatAndDigestFood(); int totalFood; boolean hasBed; int displayAge; - public VillagerEntity_aiMixin(EntityType entityType_1, World world_1) + public VillagerEntity_aiMixin(EntityType entityType_1, Level world_1) { super(entityType_1, world_1); } @@ -63,22 +63,22 @@ public abstract class VillagerEntity_aiMixin extends MerchantEntity if (MobAI.isTracking(this, MobAI.TrackingType.IRON_GOLEM_SPAWNING)) { long time; - Optional> last_seen = this.brain.getMemories().get(MemoryModuleType.GOLEM_DETECTED_RECENTLY); + Optional> last_seen = this.brain.getMemories().get(MemoryModuleType.GOLEM_DETECTED_RECENTLY); if (!last_seen.isPresent()) { time = 0; } else { - time = last_seen.get().getExpiry(); + time = last_seen.get().getTimeToLive(); } boolean recentlySeen = time > 0; - Optional optional_11 = this.brain.getOptionalMemory(MemoryModuleType.LAST_SLEPT); + Optional optional_11 = this.brain.getMemory(MemoryModuleType.LAST_SLEPT); //Optional optional_22 = this.brain.getOptionalMemory(MemoryModuleType.LAST_WORKED_AT_POI); //boolean work = false; boolean sleep = false; - boolean panic = this.brain.hasActivity(Activity.PANIC); - long currentTime = this.world.getTime(); + boolean panic = this.brain.isActive(Activity.PANIC); + long currentTime = this.level.getGameTime(); if (optional_11.isPresent()) { sleep = (currentTime - optional_11.get()) < 24000L; } @@ -95,14 +95,14 @@ public abstract class VillagerEntity_aiMixin extends MerchantEntity } else if (MobAI.isTracking(this, MobAI.TrackingType.VILLAGER_BREEDING)) { - if (age % 50 == 0 || age < 20) + if (tickCount % 50 == 0 || tickCount < 20) { - totalFood = getAvailableFood() / 12; - hasBed = this.brain.getOptionalMemory(MemoryModuleType.HOME).isPresent(); - displayAge = getBreedingAge(); + totalFood = countFoodPointsInInventory() / 12; + hasBed = this.brain.getMemory(MemoryModuleType.HOME).isPresent(); + displayAge = getAge(); } - if (Math.abs(displayAge) < 100 && displayAge !=0) displayAge = getBreedingAge(); + if (Math.abs(displayAge) < 100 && displayAge !=0) displayAge = getAge(); this.setCustomName(Messenger.c( (hasBed?"eb ":"fb ")+"\u2616 ",//"\u263d ", @@ -113,78 +113,78 @@ public abstract class VillagerEntity_aiMixin extends MerchantEntity } } - @Inject(method = "interactMob", at = @At("HEAD"), cancellable = true) - private void onInteract(PlayerEntity playerEntity_1, Hand hand_1, CallbackInfoReturnable cir) + @Inject(method = "mobInteract", at = @At("HEAD"), cancellable = true) + private void onInteract(Player playerEntity_1, InteractionHand hand_1, CallbackInfoReturnable cir) { if (MobAI.isTracking(this, MobAI.TrackingType.VILLAGER_BREEDING)) { - ItemStack itemStack_1 = playerEntity_1.getStackInHand(hand_1); + ItemStack itemStack_1 = playerEntity_1.getItemInHand(hand_1); if (itemStack_1.getItem() == Items.EMERALD) { - GlobalPos bedPos = this.brain.getOptionalMemory(MemoryModuleType.HOME).orElse(null); - if (bedPos == null || bedPos.getDimension() != world.getRegistryKey()) // get Dimension + GlobalPos bedPos = this.brain.getMemory(MemoryModuleType.HOME).orElse(null); + if (bedPos == null || bedPos.dimension() != level.dimension()) // get Dimension { - sayNo(); - ((ServerWorld) getEntityWorld()).spawnParticles(new BlockStateParticleEffect(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.getDefaultState()), getX(), getY() + getStandingEyeHeight() + 1, getZ(), 1, 0.1, 0.1, 0.1, 0.0); + setUnhappy(); + ((ServerLevel) getCommandSenderWorld()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.defaultBlockState()), getX(), getY() + getEyeHeight() + 1, getZ(), 1, 0.1, 0.1, 0.1, 0.0); } else { - ParticleDisplay.drawParticleLine((ServerPlayerEntity) playerEntity_1, getPos(), Vec3d.ofCenter(bedPos.getPos()), "dust 0 0 0 1", "happy_villager", 100, 0.2); // pos+0.5v + ParticleDisplay.drawParticleLine((ServerPlayer) playerEntity_1, position(), Vec3.atCenterOf(bedPos.pos()), "dust 0 0 0 1", "happy_villager", 100, 0.2); // pos+0.5v } } else if (itemStack_1.getItem() == Items.ROTTEN_FLESH) { - while(getAvailableFood() >= 12) eatForBreeding(); + while(countFoodPointsInInventory() >= 12) eatAndDigestFood(); } else if (itemStack_1.getItem() instanceof BedItem) { - List list_1 = ((ServerWorld) getEntityWorld()).getPointOfInterestStorage().getInCircle( - type -> type == PointOfInterestType.HOME, - getBlockPos(), - 48, PointOfInterestStorage.OccupationStatus.ANY).collect(Collectors.toList()); - for (PointOfInterest poi : list_1) + List list_1 = ((ServerLevel) getCommandSenderWorld()).getPoiManager().getInRange( + type -> type == PoiType.HOME, + blockPosition(), + 48, PoiManager.Occupancy.ANY).collect(Collectors.toList()); + for (PoiRecord poi : list_1) { - Vec3d pv = Vec3d.ofCenter(poi.getPos()); + Vec3 pv = Vec3.atCenterOf(poi.getPos()); if (!poi.hasSpace()) { - ((ServerWorld) getEntityWorld()).spawnParticles(ParticleTypes.HAPPY_VILLAGER, + ((ServerLevel) getCommandSenderWorld()).sendParticles(ParticleTypes.HAPPY_VILLAGER, pv.x, pv.y+1.5, pv.z, 50, 0.1, 0.3, 0.1, 0.0); } - else if (canReachHome((VillagerEntity)(Object)this, poi.getPos())) - ((ServerWorld) getEntityWorld()).spawnParticles(ParticleTypes.END_ROD, + else if (canReachHome((Villager)(Object)this, poi.getPos())) + ((ServerLevel) getCommandSenderWorld()).sendParticles(ParticleTypes.END_ROD, pv.x, pv.y+1, pv.z, 50, 0.1, 0.3, 0.1, 0.0); else - ((ServerWorld) getEntityWorld()).spawnParticles(new BlockStateParticleEffect(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.getDefaultState()), + ((ServerLevel) getCommandSenderWorld()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.defaultBlockState()), pv.x, pv.y+1, pv.z, 1, 0.1, 0.1, 0.1, 0.0); } } - cir.setReturnValue(ActionResult.FAIL); + cir.setReturnValue(InteractionResult.FAIL); cir.cancel(); } } // stolen from VillagerBreedTask - private boolean canReachHome(VillagerEntity villager, BlockPos pos) { - Path path = villager.getNavigation().findPathTo(pos, PointOfInterestType.HOME.getSearchDistance()); - return path != null && path.reachesTarget(); + private boolean canReachHome(Villager villager, BlockPos pos) { + Path path = villager.getNavigation().createPath(pos, PoiType.HOME.getValidRange()); + return path != null && path.canReach(); } - @Inject(method = "summonGolem", at = @At( + @Inject(method = "spawnGolemIfNeeded", at = @At( value = "INVOKE", - target = "Lnet/minecraft/util/math/Box;expand(DDD)Lnet/minecraft/util/math/Box;", + target = "Lnet/minecraft/world/phys/AABB;inflate(DDD)Lnet/minecraft/world/phys/AABB;", shift = At.Shift.AFTER )) - private void particleIt(ServerWorld serverWorld, long l, int i, CallbackInfo ci) + private void particleIt(ServerLevel serverWorld, long l, int i, CallbackInfo ci) { if (MobAI.isTracking(this, MobAI.TrackingType.IRON_GOLEM_SPAWNING)) { - ((ServerWorld) getEntityWorld()).spawnParticles(new BlockStateParticleEffect(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.getDefaultState()), getX(), getY()+3, getZ(), 1, 0.1, 0.1, 0.1, 0.0); + ((ServerLevel) getCommandSenderWorld()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.defaultBlockState()), getX(), getY()+3, getZ(), 1, 0.1, 0.1, 0.1, 0.0); } } diff --git a/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java b/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java index 14f0431c..a838f10d 100644 --- a/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/WallStandingBlockItem_creativeNoClipMixin.java @@ -1,38 +1,38 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.block.ShapeContext; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.WallStandingBlockItem; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.WorldView; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.StandingAndWallBlockItem; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.LevelReader; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(WallStandingBlockItem.class) +@Mixin(StandingAndWallBlockItem.class) public class WallStandingBlockItem_creativeNoClipMixin { @Redirect(method = "getPlacementState", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/WorldView;canPlace(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/ShapeContext;)Z" + target = "Lnet/minecraft/world/level/LevelReader;isUnobstructed(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Z" )) private boolean canCreativePlayerPlace( - WorldView worldView, BlockState state, BlockPos pos, ShapeContext context, - ItemPlacementContext itemcontext + LevelReader worldView, BlockState state, BlockPos pos, CollisionContext context, + BlockPlaceContext itemcontext ) { - PlayerEntity player = itemcontext.getPlayer(); + Player player = itemcontext.getPlayer(); if (CarpetSettings.creativeNoClip && player != null && player.isCreative() && player.getAbilities().flying) { // copy from canPlace VoxelShape voxelShape = state.getCollisionShape(worldView, pos, context); - return voxelShape.isEmpty() || worldView.doesNotIntersectEntities(player, voxelShape.offset(pos.getX(), pos.getY(), pos.getZ())); + return voxelShape.isEmpty() || worldView.isUnobstructed(player, voxelShape.move(pos.getX(), pos.getY(), pos.getZ())); } - return worldView.canPlace(state, pos, context); + return worldView.isUnobstructed(state, pos, context); } } diff --git a/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java b/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java index 07bacb52..860be204 100644 --- a/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java +++ b/src/main/java/carpet/mixins/WitherEntity_extremeMixin.java @@ -2,17 +2,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.entity.boss.WitherEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; +import net.minecraft.world.entity.boss.wither.WitherBoss; -@Mixin(WitherEntity.class) +@Mixin(WitherBoss.class) public class WitherEntity_extremeMixin { - @Redirect(method = "shootSkullAt(ILnet/minecraft/entity/LivingEntity;)V", at = @At( + @Redirect(method = "performRangedAttack(ILnet/minecraft/world/entity/LivingEntity;)V", at = @At( value = "INVOKE", target = "Ljava/util/Random;nextFloat()F") ) diff --git a/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java b/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java index b6136a8c..4f895361 100644 --- a/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java +++ b/src/main/java/carpet/mixins/WorldChunkBEList_tickMixin.java @@ -2,11 +2,11 @@ package carpet.mixins; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityTicker; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(targets = "net.minecraft.world.chunk.WorldChunk$DirectBlockEntityTickInvoker") +@Mixin(targets = "net.minecraft.world.level.chunk.LevelChunk$BoundTickingBlockEntity") public class WorldChunkBEList_tickMixin { @Shadow @Final private T blockEntity; @@ -25,14 +25,14 @@ public class WorldChunkBEList_tickMixin @Inject(method = "tick()V", at = @At("HEAD")) private void startTileEntitySection(CallbackInfo ci) { - entitySection = CarpetProfiler.start_block_entity_section(blockEntity.getWorld(), blockEntity, CarpetProfiler.TYPE.TILEENTITY); + entitySection = CarpetProfiler.start_block_entity_section(blockEntity.getLevel(), blockEntity, CarpetProfiler.TYPE.TILEENTITY); } @Redirect(method = "tick()V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/entity/BlockEntityTicker;tick(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/entity/BlockEntity;)V" + target = "Lnet/minecraft/world/level/block/entity/BlockEntityTicker;tick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/entity/BlockEntity;)V" )) - private void checkProcessTEs(BlockEntityTicker blockEntityTicker, World world, BlockPos pos, BlockState state, T blockEntity) + private void checkProcessTEs(BlockEntityTicker blockEntityTicker, Level world, BlockPos pos, BlockState state, T blockEntity) { if (TickSpeed.process_entities) blockEntityTicker.tick(world, pos, state, blockEntity); } diff --git a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java index 14f3039a..1a6fc418 100644 --- a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java @@ -1,44 +1,44 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(WorldChunk.class) +@Mixin(LevelChunk.class) public class WorldChunk_fillUpdatesMixin { // todo onStateReplaced needs a bit more love since it removes be which is needed @Redirect(method = "setBlockState", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/BlockState;onBlockAdded(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Z)V" + target = "Lnet/minecraft/world/level/block/state/BlockState;onPlace(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Z)V" )) - private void onAdded(BlockState blockState, World world_1, BlockPos blockPos_1, BlockState blockState_1, boolean boolean_1) + private void onAdded(BlockState blockState, Level world_1, BlockPos blockPos_1, BlockState blockState_1, boolean boolean_1) { if (!CarpetSettings.impendingFillSkipUpdates.get()) - blockState.onBlockAdded(world_1, blockPos_1, blockState_1, boolean_1); + blockState.onPlace(world_1, blockPos_1, blockState_1, boolean_1); } @Redirect(method = "setBlockState", at = @At( value = "INVOKE", - target = "Lnet/minecraft/block/BlockState;onStateReplaced(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Z)V" + target = "Lnet/minecraft/world/level/block/state/BlockState;onRemove(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Z)V" )) - private void onRemovedBlock(BlockState blockState, World world, BlockPos pos, BlockState state, boolean moved) + private void onRemovedBlock(BlockState blockState, Level world, BlockPos pos, BlockState state, boolean moved) { if (CarpetSettings.impendingFillSkipUpdates.get()) // doing due dilligence from AbstractBlock onStateReplaced { - if (blockState.hasBlockEntity() && !blockState.isOf(state.getBlock())) + if (blockState.hasBlockEntity() && !blockState.is(state.getBlock())) { world.removeBlockEntity(pos); } } else { - blockState.onStateReplaced(world, pos, state, moved); + blockState.onRemove(world, pos, state, moved); } } } diff --git a/src/main/java/carpet/mixins/WorldChunk_movableBEMixin.java b/src/main/java/carpet/mixins/WorldChunk_movableBEMixin.java new file mode 100644 index 00000000..c34cc696 --- /dev/null +++ b/src/main/java/carpet/mixins/WorldChunk_movableBEMixin.java @@ -0,0 +1,162 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import carpet.fakes.WorldChunkInterface; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.piston.MovingPistonBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.UpgradeData; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.blending.BlendingData; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(LevelChunk.class) +public abstract class WorldChunk_movableBEMixin extends ChunkAccess implements WorldChunkInterface +{ + @Shadow + @Final + Level level; + + public WorldChunk_movableBEMixin(ChunkPos pos, UpgradeData upgradeData, LevelHeightAccessor heightLimitView, Registry biome, long inhabitedTime, @Nullable LevelChunkSection[] sectionArrayInitializer, @Nullable BlendingData blendingData) { + super(pos, upgradeData, heightLimitView, biome, inhabitedTime, sectionArrayInitializer, blendingData); + } + + @Shadow + /* @Nullable */ + public abstract BlockEntity getBlockEntity(BlockPos blockPos_1, LevelChunk.EntityCreationType worldChunk$CreationType_1); + + @Shadow protected abstract void updateBlockEntityTicker(T blockEntity); + + @Shadow public abstract void addAndRegisterBlockEntity(BlockEntity blockEntity); + + // Fix Failure: If a moving BlockEntity is placed while BlockEntities are ticking, this will not find it and then replace it with a new TileEntity! + // blockEntity_2 = this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); + // question is - with the changes in the BE handling this might not be a case anymore + @Redirect(method = "setBlockState", at = @At(value = "INVOKE", ordinal = 0, + target = "Lnet/minecraft/world/level/chunk/LevelChunk;getBlockEntity(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/chunk/LevelChunk$EntityCreationType;)Lnet/minecraft/world/level/block/entity/BlockEntity;")) + private BlockEntity ifGetBlockEntity(LevelChunk worldChunk, BlockPos blockPos_1, + LevelChunk.EntityCreationType worldChunk$CreationType_1) + { + if (!CarpetSettings.movableBlockEntities) + { + return this.getBlockEntity(blockPos_1, LevelChunk.EntityCreationType.CHECK); + } + else + { + return this.level.getBlockEntity(blockPos_1); + } + } + + + /** + * Sets the Blockstate and the BlockEntity. + * Only sets BlockEntity if Block is BlockEntityProvider, but doesn't check if it actually matches (e.g. can assign beacon to chest entity). + * + * @author 2No2Name + */ + /* @Nullable */ + // todo update me to the new version + public BlockState setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState newBlockState, BlockEntity newBlockEntity, + boolean boolean_1) + { + int x = blockPos_1.getX() & 15; + int y = blockPos_1.getY(); + int z = blockPos_1.getZ() & 15; + LevelChunkSection chunkSection = this.getSection(this.getSectionIndex(y)); + if (chunkSection.hasOnlyAir()) + { + if (newBlockState.isAir()) + { + return null; + } + } + + boolean boolean_2 = chunkSection.hasOnlyAir(); + BlockState oldBlockState = chunkSection.setBlockState(x, y & 15, z, newBlockState); + if (oldBlockState == newBlockState) + { + return null; + } + else + { + Block newBlock = newBlockState.getBlock(); + Block oldBlock = oldBlockState.getBlock(); + ((Heightmap) this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING)).update(x, y, z, newBlockState); + ((Heightmap) this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES)).update(x, y, z, newBlockState); + ((Heightmap) this.heightmaps.get(Heightmap.Types.OCEAN_FLOOR)).update(x, y, z, newBlockState); + ((Heightmap) this.heightmaps.get(Heightmap.Types.WORLD_SURFACE)).update(x, y, z, newBlockState); + boolean boolean_3 = chunkSection.hasOnlyAir(); + if (boolean_2 != boolean_3) + { + this.level.getChunkSource().getLightEngine().updateSectionStatus(blockPos_1, boolean_3); + } + + if (!this.level.isClientSide) + { + if (!(oldBlock instanceof MovingPistonBlock))//this is a movableTE special case, if condition wasn't there it would remove the blockentity that was carried for some reason + oldBlockState.onRemove(this.level, blockPos_1, newBlockState, boolean_1);//this kills it + } + else if (oldBlock != newBlock && oldBlock instanceof EntityBlock) + { + this.level.removeBlockEntity(blockPos_1); + } + + if (chunkSection.getBlockState(x, y & 15, z).getBlock() != newBlock) + { + return null; + } + else + { + BlockEntity oldBlockEntity = null; + if (oldBlockState.hasBlockEntity()) + { + oldBlockEntity = this.getBlockEntity(blockPos_1, LevelChunk.EntityCreationType.CHECK); + if (oldBlockEntity != null) + { + oldBlockEntity.setBlockState(oldBlockState); + updateBlockEntityTicker(oldBlockEntity); + } + } + + if (oldBlockState.hasBlockEntity()) + { + if (newBlockEntity == null) + { + newBlockEntity = ((EntityBlock) newBlock).newBlockEntity(blockPos_1, newBlockState); + } + if (newBlockEntity != oldBlockEntity && newBlockEntity != null) + { + newBlockEntity.clearRemoved(); + this.level.setBlockEntity(newBlockEntity); + newBlockEntity.setBlockState(newBlockState); + updateBlockEntityTicker(newBlockEntity); + } + } + + if (!this.level.isClientSide) + { + newBlockState.onPlace(this.level, blockPos_1, oldBlockState, boolean_1); //This can call setblockstate! (e.g. hopper does) + } + + this.unsaved = true; // shouldSave + return oldBlockState; + } + } + } +} diff --git a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java b/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java deleted file mode 100644 index 6dfb9751..00000000 --- a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java +++ /dev/null @@ -1,164 +0,0 @@ -package carpet.mixins; - -import carpet.CarpetSettings; -import carpet.fakes.WorldChunkInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockEntityProvider; -import net.minecraft.block.BlockState; -import net.minecraft.block.PistonExtensionBlock; -import net.minecraft.block.entity.BlockEntity; -//import net.minecraft.fluid.Fluid; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.HeightLimitView; -import net.minecraft.world.Heightmap; -//import net.minecraft.world.TickScheduler; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkSection; -import net.minecraft.world.chunk.UpgradeData; -import net.minecraft.world.chunk.WorldChunk; -import net.minecraft.world.gen.chunk.BlendingData; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(WorldChunk.class) -public abstract class WorldChunk_movableTEMixin extends Chunk implements WorldChunkInterface -{ - @Shadow - @Final - World world; - - public WorldChunk_movableTEMixin(ChunkPos pos, UpgradeData upgradeData, HeightLimitView heightLimitView, Registry biome, long inhabitedTime, @Nullable ChunkSection[] sectionArrayInitializer, @Nullable BlendingData blendingData) { - super(pos, upgradeData, heightLimitView, biome, inhabitedTime, sectionArrayInitializer, blendingData); - } - - @Shadow - /* @Nullable */ - public abstract BlockEntity getBlockEntity(BlockPos blockPos_1, WorldChunk.CreationType worldChunk$CreationType_1); - - @Shadow protected abstract void updateTicker(T blockEntity); - - @Shadow public abstract void addBlockEntity(BlockEntity blockEntity); - - // Fix Failure: If a moving BlockEntity is placed while BlockEntities are ticking, this will not find it and then replace it with a new TileEntity! - // blockEntity_2 = this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); - // question is - with the changes in the BE handling this might not be a case anymore - @Redirect(method = "setBlockState", at = @At(value = "INVOKE", ordinal = 0, - target = "Lnet/minecraft/world/chunk/WorldChunk;getBlockEntity(Lnet/minecraft/util/math/BlockPos;" + "Lnet/minecraft/world/chunk/WorldChunk$CreationType;)" + "Lnet/minecraft/block/entity/BlockEntity;")) - private BlockEntity ifGetBlockEntity(WorldChunk worldChunk, BlockPos blockPos_1, - WorldChunk.CreationType worldChunk$CreationType_1) - { - if (!CarpetSettings.movableBlockEntities) - { - return this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); - } - else - { - return this.world.getBlockEntity(blockPos_1); - } - } - - - /** - * Sets the Blockstate and the BlockEntity. - * Only sets BlockEntity if Block is BlockEntityProvider, but doesn't check if it actually matches (e.g. can assign beacon to chest entity). - * - * @author 2No2Name - */ - /* @Nullable */ - // todo update me to the new version - public BlockState setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState newBlockState, BlockEntity newBlockEntity, - boolean boolean_1) - { - int x = blockPos_1.getX() & 15; - int y = blockPos_1.getY(); - int z = blockPos_1.getZ() & 15; - ChunkSection chunkSection = this.getSection(this.getSectionIndex(y)); - if (chunkSection.isEmpty()) - { - if (newBlockState.isAir()) - { - return null; - } - } - - boolean boolean_2 = chunkSection.isEmpty(); - BlockState oldBlockState = chunkSection.setBlockState(x, y & 15, z, newBlockState); - if (oldBlockState == newBlockState) - { - return null; - } - else - { - Block newBlock = newBlockState.getBlock(); - Block oldBlock = oldBlockState.getBlock(); - ((Heightmap) this.heightmaps.get(Heightmap.Type.MOTION_BLOCKING)).trackUpdate(x, y, z, newBlockState); - ((Heightmap) this.heightmaps.get(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES)).trackUpdate(x, y, z, newBlockState); - ((Heightmap) this.heightmaps.get(Heightmap.Type.OCEAN_FLOOR)).trackUpdate(x, y, z, newBlockState); - ((Heightmap) this.heightmaps.get(Heightmap.Type.WORLD_SURFACE)).trackUpdate(x, y, z, newBlockState); - boolean boolean_3 = chunkSection.isEmpty(); - if (boolean_2 != boolean_3) - { - this.world.getChunkManager().getLightingProvider().setSectionStatus(blockPos_1, boolean_3); - } - - if (!this.world.isClient) - { - if (!(oldBlock instanceof PistonExtensionBlock))//this is a movableTE special case, if condition wasn't there it would remove the blockentity that was carried for some reason - oldBlockState.onStateReplaced(this.world, blockPos_1, newBlockState, boolean_1);//this kills it - } - else if (oldBlock != newBlock && oldBlock instanceof BlockEntityProvider) - { - this.world.removeBlockEntity(blockPos_1); - } - - if (chunkSection.getBlockState(x, y & 15, z).getBlock() != newBlock) - { - return null; - } - else - { - BlockEntity oldBlockEntity = null; - if (oldBlockState.hasBlockEntity()) - { - oldBlockEntity = this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); - if (oldBlockEntity != null) - { - oldBlockEntity.setCachedState(oldBlockState); - updateTicker(oldBlockEntity); - } - } - - if (oldBlockState.hasBlockEntity()) - { - if (newBlockEntity == null) - { - newBlockEntity = ((BlockEntityProvider) newBlock).createBlockEntity(blockPos_1, newBlockState); - } - if (newBlockEntity != oldBlockEntity && newBlockEntity != null) - { - newBlockEntity.cancelRemoval(); - this.world.addBlockEntity(newBlockEntity); - newBlockEntity.setCachedState(newBlockState); - updateTicker(newBlockEntity); - } - } - - if (!this.world.isClient) - { - newBlockState.onBlockAdded(this.world, blockPos_1, oldBlockState, boolean_1); //This can call setblockstate! (e.g. hopper does) - } - - this.needsSaving = true; // shouldSave - return oldBlockState; - } - } - } -} diff --git a/src/main/java/carpet/mixins/WorldRenderer_creativeNoClipMixin.java b/src/main/java/carpet/mixins/WorldRenderer_creativeNoClipMixin.java index 4e8a8109..14bfa153 100644 --- a/src/main/java/carpet/mixins/WorldRenderer_creativeNoClipMixin.java +++ b/src/main/java/carpet/mixins/WorldRenderer_creativeNoClipMixin.java @@ -1,17 +1,17 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.render.WorldRenderer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.LevelRenderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(WorldRenderer.class) +@Mixin(LevelRenderer.class) public class WorldRenderer_creativeNoClipMixin { - @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerEntity;isSpectator()Z")) - private boolean canSeeWorld(ClientPlayerEntity clientPlayerEntity) + @Redirect(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;isSpectator()Z")) + private boolean canSeeWorld(LocalPlayer clientPlayerEntity) { return clientPlayerEntity.isSpectator() || (CarpetSettings.creativeNoClip && clientPlayerEntity.isCreative()); } diff --git a/src/main/java/carpet/mixins/WorldRenderer_fogOffMixin.java b/src/main/java/carpet/mixins/WorldRenderer_fogOffMixin.java index 2a4fb736..e132926e 100644 --- a/src/main/java/carpet/mixins/WorldRenderer_fogOffMixin.java +++ b/src/main/java/carpet/mixins/WorldRenderer_fogOffMixin.java @@ -1,24 +1,24 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.client.render.DimensionEffects; -import net.minecraft.client.render.WorldRenderer; +import net.minecraft.client.renderer.DimensionSpecialEffects; +import net.minecraft.client.renderer.LevelRenderer; //import net.minecraft.world.dimension.Dimension; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(value = WorldRenderer.class, priority = 69420) +@Mixin(value = LevelRenderer.class, priority = 69420) public class WorldRenderer_fogOffMixin { - @Redirect(method = "render", require = 0, expect = 0, at = @At( + @Redirect(method = "renderLevel", require = 0, expect = 0, at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/render/DimensionEffects;useThickFog(II)Z" + target = "Lnet/minecraft/client/renderer/DimensionSpecialEffects;isFoggyAt(II)Z" )) - private boolean isReallyThick(DimensionEffects skyProperties, int x, int z) + private boolean isReallyThick(DimensionSpecialEffects skyProperties, int x, int z) { if (CarpetSettings.fogOff) return false; - return skyProperties.useThickFog(x, z); + return skyProperties.isFoggyAt(x, z); } } diff --git a/src/main/java/carpet/mixins/WorldRenderer_pausedShakeMixin.java b/src/main/java/carpet/mixins/WorldRenderer_pausedShakeMixin.java index cdbbebb5..0e3794bd 100644 --- a/src/main/java/carpet/mixins/WorldRenderer_pausedShakeMixin.java +++ b/src/main/java/carpet/mixins/WorldRenderer_pausedShakeMixin.java @@ -2,38 +2,38 @@ package carpet.mixins; import carpet.fakes.MinecraftClientInferface; import carpet.helpers.TickSpeed; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.WorldRenderer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.LevelRenderer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable; -@Mixin(value = WorldRenderer.class, priority = 69420) +@Mixin(value = LevelRenderer.class, priority = 69420) public class WorldRenderer_pausedShakeMixin { - @Shadow @Final private MinecraftClient client; + @Shadow @Final private Minecraft minecraft; float initial = -1234.0f; // require 0 is for optifine being a bitch as it usually is. - @ModifyVariable(method = "render", argsOnly = true, require = 0, ordinal = 0, at = @At( + @ModifyVariable(method = "renderLevel", argsOnly = true, require = 0, ordinal = 0, at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/world/ClientWorld;getEntities()Ljava/lang/Iterable;" + target = "Lnet/minecraft/client/multiplayer/ClientLevel;entitiesForRendering()Ljava/lang/Iterable;" )) private float changeTickPhase(float previous) { initial = previous; if (!TickSpeed.process_entities) - return ((MinecraftClientInferface)client).getPausedTickDelta(); + return ((MinecraftClientInferface)minecraft).getPausedTickDelta(); return previous; } // require 0 is for optifine being a bitch as it usually is. - @ModifyVariable(method = "render", argsOnly = true, require = 0, ordinal = 0 ,at = @At( + @ModifyVariable(method = "renderLevel", argsOnly = true, require = 0, ordinal = 0 ,at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/particle/ParticleManager;renderParticles(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;Lnet/minecraft/client/render/LightmapTextureManager;Lnet/minecraft/client/render/Camera;F)V", + target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V", shift = At.Shift.BEFORE )) private float changeTickPhaseBack(float previous) diff --git a/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java b/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java index 7cb983a1..9d4d5d2e 100644 --- a/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java +++ b/src/main/java/carpet/mixins/WorldRenderer_scarpetRenderMixin.java @@ -2,31 +2,31 @@ package carpet.mixins; import carpet.network.CarpetClient; import carpet.script.utils.ShapesRenderer; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.BufferBuilderStorage; -import net.minecraft.client.render.Camera; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.render.LightmapTextureManager; -import net.minecraft.client.render.WorldRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.math.Matrix4f; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Matrix4f; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.RenderBuffers; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(WorldRenderer.class) +@Mixin(LevelRenderer.class) public class WorldRenderer_scarpetRenderMixin { @Inject(method = "", at = @At("RETURN")) - private void addRenderers(MinecraftClient client, BufferBuilderStorage bufferBuilders, CallbackInfo ci) + private void addRenderers(Minecraft client, RenderBuffers bufferBuilders, CallbackInfo ci) { CarpetClient.shapes = new ShapesRenderer(client); } - @Inject(method = "render", at = @At( + @Inject(method = "renderLevel", at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/render/TexturedRenderLayers;getEntityTranslucentCull()Lnet/minecraft/client/render/RenderLayer;", shift = At.Shift.BEFORE + target = "Lnet/minecraft/client/renderer/Sheets;translucentCullBlockSheet()Lnet/minecraft/client/renderer/RenderType;", shift = At.Shift.BEFORE //target = "Lnet/minecraft/client/render/RenderLayer;getWaterMask()Lnet/minecraft/client/render/RenderLayer;", shift = At.Shift.AFTER //target = "Lnet/minecraft/client/render/BufferBuilderStorage;getEffectVertexConsumers()Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;", shift = At.Shift.BEFORE //target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER @@ -34,7 +34,7 @@ public class WorldRenderer_scarpetRenderMixin //target = "Lnet/minecraft/client/render/BufferBuilderStorage;getEntityVertexConsumers()Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;", shift = At.Shift.AFTER //target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER // before return )) - private void renderScarpetThings(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f matrix4f, CallbackInfo ci) + private void renderScarpetThings(PoseStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightmapTextureManager, Matrix4f matrix4f, CallbackInfo ci) { // in normal circumstances we want to render shapes at the very end so it appears correctly behind stuff. // we might actually not need to play with render hooks here. diff --git a/src/main/java/carpet/mixins/World_fillUpdatesMixin.java b/src/main/java/carpet/mixins/World_fillUpdatesMixin.java index 23cffe19..0c7b76fc 100644 --- a/src/main/java/carpet/mixins/World_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/World_fillUpdatesMixin.java @@ -1,19 +1,19 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.block.Block; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(World.class) +@Mixin(Level.class) public abstract class World_fillUpdatesMixin { - @ModifyConstant(method = "setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;II)Z", //setBlockState main + @ModifyConstant(method = "setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;II)Z", //setBlockState main constant = @Constant(intValue = 16)) private int addFillUpdatesInt(int original) { if (CarpetSettings.impendingFillSkipUpdates.get()) @@ -21,13 +21,13 @@ public abstract class World_fillUpdatesMixin return original; } - @Redirect(method = "setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;II)Z", at = @At( //setBlockState main + @Redirect(method = "setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;II)Z", at = @At( //setBlockState main value = "INVOKE", - target = "Lnet/minecraft/world/World;updateNeighbors(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V" + target = "Lnet/minecraft/world/level/Level;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" )) - private void updateNeighborsMaybe(World world, BlockPos blockPos, Block block) + private void updateNeighborsMaybe(Level world, BlockPos blockPos, Block block) { - if (!CarpetSettings.impendingFillSkipUpdates.get()) world.updateNeighbors(blockPos, block); + if (!CarpetSettings.impendingFillSkipUpdates.get()) world.blockUpdated(blockPos, block); } } diff --git a/src/main/java/carpet/mixins/World_getOtherEntitiesLimited.java b/src/main/java/carpet/mixins/World_getOtherEntitiesLimited.java index ee2d73b9..597d8b22 100644 --- a/src/main/java/carpet/mixins/World_getOtherEntitiesLimited.java +++ b/src/main/java/carpet/mixins/World_getOtherEntitiesLimited.java @@ -2,13 +2,6 @@ package carpet.mixins; import carpet.fakes.WorldInterface; import com.google.common.collect.Lists; -import net.minecraft.entity.Entity; -import net.minecraft.entity.boss.dragon.EnderDragonEntity; -import net.minecraft.entity.boss.dragon.EnderDragonPart; -import net.minecraft.util.math.Box; -import net.minecraft.util.profiler.Profiler; -import net.minecraft.world.World; -import net.minecraft.world.entity.EntityLookup; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -16,19 +9,26 @@ import org.spongepowered.asm.mixin.Shadow; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.EnderDragonPart; +import net.minecraft.world.entity.boss.enderdragon.EnderDragon; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.LevelEntityGetter; +import net.minecraft.world.phys.AABB; -@Mixin(World.class) +@Mixin(Level.class) public abstract class World_getOtherEntitiesLimited implements WorldInterface { private static final RuntimeException CONTROL_FLOW_EXCEPTION = new RuntimeException("Should be caught for control flow in World_getOtherEntitiesLimited!"); @Override - public List getOtherEntitiesLimited(@Nullable Entity except, Box box, Predicate predicate, int limit) { - this.getProfiler().visit("getEntities"); // visit + public List getOtherEntitiesLimited(@Nullable Entity except, AABB box, Predicate predicate, int limit) { + this.getProfiler().incrementCounter("getEntities"); // visit AtomicInteger checkedEntities = new AtomicInteger(); List list = Lists.newArrayList(); try { - this.getEntityLookup().forEachIntersects(box, (entity) -> { + this.getEntities().get(box, (entity) -> { if (checkedEntities.getAndIncrement() > limit) { throw CONTROL_FLOW_EXCEPTION; } @@ -37,8 +37,8 @@ public abstract class World_getOtherEntitiesLimited implements WorldInterface { list.add(entity); } - if (entity instanceof EnderDragonEntity) { - EnderDragonPart[] var4 = ((EnderDragonEntity) entity).getBodyParts(); + if (entity instanceof EnderDragon) { + EnderDragonPart[] var4 = ((EnderDragon) entity).getSubEntities(); for (EnderDragonPart enderDragonPart : var4) { if (entity != except && predicate.test(enderDragonPart)) { @@ -56,8 +56,8 @@ public abstract class World_getOtherEntitiesLimited implements WorldInterface { } @Shadow - public abstract Profiler getProfiler(); + public abstract ProfilerFiller getProfiler(); @Shadow - protected abstract EntityLookup getEntityLookup(); + protected abstract LevelEntityGetter getEntities(); } diff --git a/src/main/java/carpet/mixins/World_movableBEMixin.java b/src/main/java/carpet/mixins/World_movableBEMixin.java new file mode 100644 index 00000000..e288c604 --- /dev/null +++ b/src/main/java/carpet/mixins/World_movableBEMixin.java @@ -0,0 +1,120 @@ +package carpet.mixins; + +import carpet.fakes.WorldChunkInterface; +import carpet.fakes.WorldInterface; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(Level.class) +public abstract class World_movableBEMixin implements WorldInterface, LevelAccessor +{ + @Shadow + @Final + public boolean isClientSide; + + @Shadow + public abstract LevelChunk getChunkAt(BlockPos blockPos_1); + + @Shadow + public abstract BlockState getBlockState(BlockPos blockPos_1); + + //@Shadow + //public abstract ChunkManager getChunkManager(); + + @Shadow + public abstract void setBlocksDirty(BlockPos blockPos_1, BlockState s1, BlockState s2); + + @Shadow + public abstract void sendBlockUpdated(BlockPos var1, BlockState var2, BlockState var3, int var4); + + @Shadow + public abstract void updateNeighborsAt(BlockPos blockPos_1, Block block_1); + + @Shadow + public abstract void onBlockStateChange(BlockPos blockPos_1, BlockState blockState_1, BlockState blockState_2); + + @Shadow public abstract ProfilerFiller getProfiler(); + + @Shadow public abstract void updateNeighbourForOutputSignal(BlockPos pos, Block block); + + //@Shadow public abstract boolean setBlockState(BlockPos pos, BlockState state, int flags); + + @Shadow public abstract boolean isDebug(); + + /** + * @author 2No2Name + */ + public boolean setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState blockState_1, BlockEntity newBlockEntity, int int_1) + { + if (isOutsideBuildHeight(blockPos_1) || !this.isClientSide && isDebug()) return false; + LevelChunk worldChunk_1 = this.getChunkAt(blockPos_1); + Block block_1 = blockState_1.getBlock(); + + BlockState blockState_2; + if (newBlockEntity != null && block_1 instanceof EntityBlock) + blockState_2 = ((WorldChunkInterface) worldChunk_1).setBlockStateWithBlockEntity(blockPos_1, blockState_1, newBlockEntity, (int_1 & 64) != 0); + else + blockState_2 = worldChunk_1.setBlockState(blockPos_1, blockState_1, (int_1 & 64) != 0); + + if (blockState_2 == null) + { + return false; + } + else + { + BlockState blockState_3 = this.getBlockState(blockPos_1); + + if (blockState_3 != blockState_2 && (blockState_3.getLightBlock((BlockGetter) this, blockPos_1) != blockState_2.getLightBlock((BlockGetter) this, blockPos_1) || blockState_3.getLightEmission() != blockState_2.getLightEmission() || blockState_3.useShapeForLightOcclusion() || blockState_2.useShapeForLightOcclusion())) + { + ProfilerFiller profiler = getProfiler(); + profiler.push("queueCheckLight"); + this.getChunkSource().getLightEngine().checkBlock(blockPos_1); + profiler.pop(); + } + + if (blockState_3 == blockState_1) + { + if (blockState_2 != blockState_3) + { + this.setBlocksDirty(blockPos_1, blockState_2, blockState_3); + } + + if ((int_1 & 2) != 0 && (!this.isClientSide || (int_1 & 4) == 0) && (this.isClientSide || worldChunk_1.getFullStatus() != null && worldChunk_1.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING))) + { + this.sendBlockUpdated(blockPos_1, blockState_2, blockState_1, int_1); + } + + if (!this.isClientSide && (int_1 & 1) != 0) + { + this.updateNeighborsAt(blockPos_1, blockState_2.getBlock()); + if (blockState_1.hasAnalogOutputSignal()) + { + updateNeighbourForOutputSignal(blockPos_1, block_1); + } + } + + if ((int_1 & 16) == 0) + { + int int_2 = int_1 & -34; + blockState_2.updateIndirectNeighbourShapes(this, blockPos_1, int_2); // prepare + blockState_1.updateNeighbourShapes(this, blockPos_1, int_2); // updateNeighbours + blockState_1.updateIndirectNeighbourShapes(this, blockPos_1, int_2); // prepare + } + this.onBlockStateChange(blockPos_1, blockState_2, blockState_3); + } + return true; + } + } +} diff --git a/src/main/java/carpet/mixins/World_movableTEMixin.java b/src/main/java/carpet/mixins/World_movableTEMixin.java deleted file mode 100644 index 13a217c9..00000000 --- a/src/main/java/carpet/mixins/World_movableTEMixin.java +++ /dev/null @@ -1,121 +0,0 @@ -package carpet.mixins; - -import carpet.fakes.WorldChunkInterface; -import carpet.fakes.WorldInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockEntityProvider; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.server.world.ChunkHolder; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.profiler.Profiler; -import net.minecraft.world.BlockView; -import net.minecraft.world.WorldAccess; -import net.minecraft.world.World; -import net.minecraft.world.chunk.EmptyChunk; -import net.minecraft.world.chunk.WorldChunk; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(World.class) -public abstract class World_movableTEMixin implements WorldInterface, WorldAccess -{ - @Shadow - @Final - public boolean isClient; - - @Shadow - public abstract WorldChunk getWorldChunk(BlockPos blockPos_1); - - @Shadow - public abstract BlockState getBlockState(BlockPos blockPos_1); - - //@Shadow - //public abstract ChunkManager getChunkManager(); - - @Shadow - public abstract void scheduleBlockRerenderIfNeeded(BlockPos blockPos_1, BlockState s1, BlockState s2); - - @Shadow - public abstract void updateListeners(BlockPos var1, BlockState var2, BlockState var3, int var4); - - @Shadow - public abstract void updateNeighborsAlways(BlockPos blockPos_1, Block block_1); - - @Shadow - public abstract void onBlockChanged(BlockPos blockPos_1, BlockState blockState_1, BlockState blockState_2); - - @Shadow public abstract Profiler getProfiler(); - - @Shadow public abstract void updateComparators(BlockPos pos, Block block); - - //@Shadow public abstract boolean setBlockState(BlockPos pos, BlockState state, int flags); - - @Shadow public abstract boolean isDebugWorld(); - - /** - * @author 2No2Name - */ - public boolean setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState blockState_1, BlockEntity newBlockEntity, int int_1) - { - if (isOutOfHeightLimit(blockPos_1) || !this.isClient && isDebugWorld()) return false; - WorldChunk worldChunk_1 = this.getWorldChunk(blockPos_1); - Block block_1 = blockState_1.getBlock(); - - BlockState blockState_2; - if (newBlockEntity != null && block_1 instanceof BlockEntityProvider) - blockState_2 = ((WorldChunkInterface) worldChunk_1).setBlockStateWithBlockEntity(blockPos_1, blockState_1, newBlockEntity, (int_1 & 64) != 0); - else - blockState_2 = worldChunk_1.setBlockState(blockPos_1, blockState_1, (int_1 & 64) != 0); - - if (blockState_2 == null) - { - return false; - } - else - { - BlockState blockState_3 = this.getBlockState(blockPos_1); - - if (blockState_3 != blockState_2 && (blockState_3.getOpacity((BlockView) this, blockPos_1) != blockState_2.getOpacity((BlockView) this, blockPos_1) || blockState_3.getLuminance() != blockState_2.getLuminance() || blockState_3.hasSidedTransparency() || blockState_2.hasSidedTransparency())) - { - Profiler profiler = getProfiler(); - profiler.push("queueCheckLight"); - this.getChunkManager().getLightingProvider().checkBlock(blockPos_1); - profiler.pop(); - } - - if (blockState_3 == blockState_1) - { - if (blockState_2 != blockState_3) - { - this.scheduleBlockRerenderIfNeeded(blockPos_1, blockState_2, blockState_3); - } - - if ((int_1 & 2) != 0 && (!this.isClient || (int_1 & 4) == 0) && (this.isClient || worldChunk_1.getLevelType() != null && worldChunk_1.getLevelType().isAfter(ChunkHolder.LevelType.TICKING))) - { - this.updateListeners(blockPos_1, blockState_2, blockState_1, int_1); - } - - if (!this.isClient && (int_1 & 1) != 0) - { - this.updateNeighborsAlways(blockPos_1, blockState_2.getBlock()); - if (blockState_1.hasComparatorOutput()) - { - updateComparators(blockPos_1, block_1); - } - } - - if ((int_1 & 16) == 0) - { - int int_2 = int_1 & -34; - blockState_2.prepare(this, blockPos_1, int_2); // prepare - blockState_1.updateNeighbors(this, blockPos_1, int_2); // updateNeighbours - blockState_1.prepare(this, blockPos_1, int_2); // prepare - } - this.onBlockChanged(blockPos_1, blockState_2, blockState_3); - } - return true; - } - } -} diff --git a/src/main/java/carpet/mixins/World_scarpetPlopMixin.java b/src/main/java/carpet/mixins/World_scarpetPlopMixin.java index aed0e49e..1dc95519 100644 --- a/src/main/java/carpet/mixins/World_scarpetPlopMixin.java +++ b/src/main/java/carpet/mixins/World_scarpetPlopMixin.java @@ -1,31 +1,31 @@ package carpet.mixins; import carpet.CarpetSettings; -import net.minecraft.world.Heightmap; -import net.minecraft.world.World; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.levelgen.Heightmap; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(World.class) +@Mixin(Level.class) public class World_scarpetPlopMixin { - @Redirect(method = "getTopY", at = @At( + @Redirect(method = "getHeight", at = @At( value = "INVOKE", - target = "net/minecraft/world/chunk/WorldChunk.sampleHeightmap(Lnet/minecraft/world/Heightmap$Type;II)I" + target = "net/minecraft/world/level/chunk/LevelChunk.getHeight(Lnet/minecraft/world/level/levelgen/Heightmap$Types;II)I" )) - private int fixSampleHeightmap(WorldChunk chunk, Heightmap.Type type, int x, int z) + private int fixSampleHeightmap(LevelChunk chunk, Heightmap.Types type, int x, int z) { if (CarpetSettings.skipGenerationChecks.get()) { - Heightmap.Type newType = type; - if (type == Heightmap.Type.OCEAN_FLOOR_WG) newType = Heightmap.Type.OCEAN_FLOOR; - else if (type == Heightmap.Type.WORLD_SURFACE_WG) newType = Heightmap.Type.WORLD_SURFACE; - return chunk.sampleHeightmap(newType, x, z); + Heightmap.Types newType = type; + if (type == Heightmap.Types.OCEAN_FLOOR_WG) newType = Heightmap.Types.OCEAN_FLOOR; + else if (type == Heightmap.Types.WORLD_SURFACE_WG) newType = Heightmap.Types.WORLD_SURFACE; + return chunk.getHeight(newType, x, z); } - return chunk.sampleHeightmap(type, x, z); + return chunk.getHeight(type, x, z); } } diff --git a/src/main/java/carpet/mixins/World_tickMixin.java b/src/main/java/carpet/mixins/World_tickMixin.java index 76102f3a..ea508410 100644 --- a/src/main/java/carpet/mixins/World_tickMixin.java +++ b/src/main/java/carpet/mixins/World_tickMixin.java @@ -3,10 +3,6 @@ package carpet.mixins; import carpet.fakes.WorldInterface; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -17,11 +13,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; -@Mixin(World.class) +@Mixin(Level.class) public abstract class World_tickMixin implements WorldInterface { - @Shadow @Final public boolean isClient; + @Shadow @Final public boolean isClientSide; CarpetProfiler.ProfilerToken currentSection; CarpetProfiler.ProfilerToken entitySection; @@ -34,7 +34,7 @@ public abstract class World_tickMixin implements WorldInterface @Inject(method = "tickBlockEntities", at = @At("HEAD")) private void startBlockEntities(CallbackInfo ci) { - currentSection = CarpetProfiler.start_section((World) (Object) this, "Block Entities", CarpetProfiler.TYPE.GENERAL); + currentSection = CarpetProfiler.start_section((Level) (Object) this, "Block Entities", CarpetProfiler.TYPE.GENERAL); } @Inject(method = "tickBlockEntities", at = @At("TAIL")) @@ -74,15 +74,15 @@ public abstract class World_tickMixin implements WorldInterface CarpetProfiler.end_current_entity_section(entitySection); } */ - @Inject(method = "tickEntity", at = @At("HEAD"), cancellable = true) + @Inject(method = "guardEntityTick", at = @At("HEAD"), cancellable = true) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { - if (!(TickSpeed.process_entities || (e instanceof PlayerEntity) || (TickSpeed.is_superHot && isClient && e.getPrimaryPassenger() instanceof PlayerEntity))) + if (!(TickSpeed.process_entities || (e instanceof Player) || (TickSpeed.is_superHot && isClientSide && e.getControllingPassenger() instanceof Player))) ci.cancel(); - entitySection = CarpetProfiler.start_entity_section((World) (Object) this, e, CarpetProfiler.TYPE.ENTITY); + entitySection = CarpetProfiler.start_entity_section((Level) (Object) this, e, CarpetProfiler.TYPE.ENTITY); } - @Inject(method = "tickEntity", at = @At("TAIL")) + @Inject(method = "guardEntityTick", at = @At("TAIL")) private void endEntity(Consumer call, Entity e, CallbackInfo ci) { CarpetProfiler.end_current_entity_section(entitySection); } diff --git a/src/main/java/carpet/mixins/World_updateSuppressionCrashFixMixin.java b/src/main/java/carpet/mixins/World_updateSuppressionCrashFixMixin.java index 300b8c90..4ef14f78 100644 --- a/src/main/java/carpet/mixins/World_updateSuppressionCrashFixMixin.java +++ b/src/main/java/carpet/mixins/World_updateSuppressionCrashFixMixin.java @@ -2,24 +2,24 @@ package carpet.mixins; import carpet.CarpetSettings; import carpet.helpers.ThrowableSuppression; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; -@Mixin(World.class) +@Mixin(Level.class) public class World_updateSuppressionCrashFixMixin { @Inject( - method = "updateNeighbor", + method = "neighborChanged", at = @At( value="INVOKE", - target = "Lnet/minecraft/util/crash/CrashReport;create(Ljava/lang/Throwable;Ljava/lang/String;)Lnet/minecraft/util/crash/CrashReport;" + target = "Lnet/minecraft/CrashReport;forThrowable(Ljava/lang/Throwable;Ljava/lang/String;)Lnet/minecraft/CrashReport;" ), locals = LocalCapture.CAPTURE_FAILHARD, require = 0 diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index ac59bc26..03f8f1f8 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -3,12 +3,12 @@ package carpet.network; import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.script.utils.ShapesRenderer; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtElement; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; public class CarpetClient { @@ -18,12 +18,12 @@ public class CarpetClient public static final int DATA = 1; public static ShapesRenderer shapes = null; - private static ClientPlayerEntity clientPlayer = null; + private static LocalPlayer clientPlayer = null; private static boolean isServerCarpet = false; public static String serverCarpetVersion; - public static final Identifier CARPET_CHANNEL = new Identifier("carpet:hello"); + public static final ResourceLocation CARPET_CHANNEL = new ResourceLocation("carpet:hello"); - public static void gameJoined(ClientPlayerEntity player) + public static void gameJoined(LocalPlayer player) { synchronized (sync) { @@ -55,7 +55,7 @@ public class CarpetClient isServerCarpet = true; } - public static ClientPlayerEntity getPlayer() + public static LocalPlayer getPlayer() { return clientPlayer; } @@ -72,18 +72,18 @@ public class CarpetClient return true; } - public static void onClientCommand(NbtElement t) + public static void onClientCommand(Tag t) { CarpetSettings.LOG.info("Server Response:"); - NbtCompound tag = (NbtCompound)t; + CompoundTag tag = (CompoundTag)t; CarpetSettings.LOG.info(" - id: "+tag.getString("id")); CarpetSettings.LOG.info(" - code: "+tag.getInt("code")); if (tag.contains("error")) CarpetSettings.LOG.warn(" - error: "+tag.getString("error")); if (tag.contains("output")) { - NbtList outputTag = (NbtList) tag.get("output"); + ListTag outputTag = (ListTag) tag.get("output"); for (int i = 0; i < outputTag.size(); i++) - CarpetSettings.LOG.info(" - response: " + Text.Serializer.fromJson(outputTag.getString(i)).getString()); + CarpetSettings.LOG.info(" - response: " + Component.Serializer.fromJson(outputTag.getString(i)).getString()); } } } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 9a34ec2d..56f4a9c8 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -7,29 +7,28 @@ import carpet.helpers.TickSpeed; import carpet.settings.ParsedRule; import carpet.settings.SettingsManager; import io.netty.buffer.Unpooled; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.nbt.AbstractNbtNumber; -import net.minecraft.nbt.NbtByte; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtElement; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.c2s.play.CustomPayloadC2SPacket; - import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; public class ClientNetworkHandler { - private static final Map> dataHandlers = new HashMap>(); + private static final Map> dataHandlers = new HashMap>(); static { dataHandlers.put("Rules", (p, t) -> { - NbtCompound ruleset = (NbtCompound)t; - for (String ruleKey: ruleset.getKeys()) + CompoundTag ruleset = (CompoundTag)t; + for (String ruleKey: ruleset.getAllKeys()) { - NbtCompound ruleNBT = (NbtCompound) ruleset.get(ruleKey); + CompoundTag ruleNBT = (CompoundTag) ruleset.get(ruleKey); SettingsManager manager = null; String ruleName; if (ruleNBT.contains("Manager")) @@ -65,29 +64,29 @@ public class ClientNetworkHandler } } }); - dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrate(((AbstractNbtNumber)t).floatValue(), false)); + dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrate(((NumericTag)t).getAsFloat(), false)); dataHandlers.put("TickingState", (p, t) -> { - NbtCompound tickingState = (NbtCompound)t; + CompoundTag tickingState = (CompoundTag)t; TickSpeed.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickSpeed.is_superHot = ((NbtByte) t).equals(NbtByte.ONE); + TickSpeed.is_superHot = ((ByteTag) t).equals(ByteTag.ONE); }); - dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.player_active_timeout = ((AbstractNbtNumber)t).intValue()); + dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.player_active_timeout = ((NumericTag)t).getAsInt()); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 if (CarpetClient.shapes != null) - CarpetClient.shapes.addShape((NbtCompound)t); + CarpetClient.shapes.addShape((CompoundTag)t); }); dataHandlers.put("scShapes", (p, t) -> { if (CarpetClient.shapes != null) - CarpetClient.shapes.addShapes((NbtList) t); + CarpetClient.shapes.addShapes((ListTag) t); }); dataHandlers.put("clientCommand", (p, t) -> { CarpetClient.onClientCommand(t); }); }; - public static void handleData(PacketByteBuf data, ClientPlayerEntity player) + public static void handleData(FriendlyByteBuf data, LocalPlayer player) { if (data != null) { @@ -99,12 +98,12 @@ public class ClientNetworkHandler } } - private static void onHi(PacketByteBuf data) + private static void onHi(FriendlyByteBuf data) { synchronized (CarpetClient.sync) { CarpetClient.setCarpet(); - CarpetClient.serverCarpetVersion = data.readString(64); + CarpetClient.serverCarpetVersion = data.readUtf(64); if (CarpetSettings.carpetVersion.equals(CarpetClient.serverCarpetVersion)) { CarpetSettings.LOG.info("Joined carpet server with matching carpet version"); @@ -121,17 +120,17 @@ public class ClientNetworkHandler public static void respondHello() { - CarpetClient.getPlayer().networkHandler.sendPacket(new CustomPayloadC2SPacket( + CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HELLO).writeString(CarpetSettings.carpetVersion) + (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HELLO).writeUtf(CarpetSettings.carpetVersion) )); } - private static void onSyncData(PacketByteBuf data, ClientPlayerEntity player) + private static void onSyncData(FriendlyByteBuf data, LocalPlayer player) { - NbtCompound compound = data.readNbt(); + CompoundTag compound = data.readNbt(); if (compound == null) return; - for (String key: compound.getKeys()) + for (String key: compound.getAllKeys()) { if (dataHandlers.containsKey(key)) { try { @@ -149,14 +148,14 @@ public class ClientNetworkHandler public static void clientCommand(String command) { - NbtCompound tag = new NbtCompound(); + CompoundTag tag = new CompoundTag(); tag.putString("id", command); tag.putString("command", command); - NbtCompound outer = new NbtCompound(); + CompoundTag outer = new CompoundTag(); outer.put("clientCommand", tag); - CarpetClient.getPlayer().networkHandler.sendPacket(new CustomPayloadC2SPacket( + CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.DATA).writeNbt(outer) + (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.DATA).writeNbt(outer) )); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index aee49d03..44431fd7 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -7,17 +7,6 @@ import carpet.script.utils.SnoopyCommandSource; import carpet.settings.ParsedRule; import carpet.settings.SettingsManager; import io.netty.buffer.Unpooled; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; -import net.minecraft.server.network.ServerPlayerEntity; - -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -25,19 +14,28 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.server.level.ServerPlayer; public class ServerNetworkHandler { - private static Map remoteCarpetPlayers = new HashMap<>(); - private static Set validCarpetPlayers = new HashSet<>(); + private static Map remoteCarpetPlayers = new HashMap<>(); + private static Set validCarpetPlayers = new HashSet<>(); - private static Map> dataHandlers = new HashMap>(){{ + private static Map> dataHandlers = new HashMap>(){{ put("clientCommand", (p, t) -> { - handleClientCommand(p, (NbtCompound)t); + handleClientCommand(p, (CompoundTag)t); }); }}; - public static void handleData(PacketByteBuf data, ServerPlayerEntity player) + public static void handleData(FriendlyByteBuf data, ServerPlayer player) { if (data != null) { @@ -51,13 +49,13 @@ public class ServerNetworkHandler - public static void onPlayerJoin(ServerPlayerEntity playerEntity) + public static void onPlayerJoin(ServerPlayer playerEntity) { - if (!playerEntity.networkHandler.connection.isLocal()) + if (!playerEntity.connection.connection.isMemoryConnection()) { - playerEntity.networkHandler.sendPacket(new CustomPayloadS2CPacket( + playerEntity.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HI).writeString(CarpetSettings.carpetVersion) + (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HI).writeUtf(CarpetSettings.carpetVersion) )); } else @@ -67,11 +65,11 @@ public class ServerNetworkHandler } - public static void onHello(ServerPlayerEntity playerEntity, PacketByteBuf packetData) + public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData) { validCarpetPlayers.add(playerEntity); - String clientVersion = packetData.readString(64); + String clientVersion = packetData.readUtf(64); remoteCarpetPlayers.put(playerEntity, clientVersion); if (clientVersion.equals(CarpetSettings.carpetVersion)) CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); @@ -85,34 +83,34 @@ public class ServerNetworkHandler eManager.getRules().forEach(data::withRule); } }); - playerEntity.networkHandler.sendPacket(new CustomPayloadS2CPacket(CarpetClient.CARPET_CHANNEL, data.build() )); + playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); } - private static void handleClientCommand(ServerPlayerEntity player, NbtCompound commandData) + private static void handleClientCommand(ServerPlayer player, CompoundTag commandData) { String command = commandData.getString("command"); String id = commandData.getString("id"); - List output = new ArrayList<>(); - Text[] error = {null}; + List output = new ArrayList<>(); + Component[] error = {null}; int resultCode = -1; if (player.getServer() == null) { - error[0] = new LiteralText("No Server"); + error[0] = new TextComponent("No Server"); } else { - resultCode = player.getServer().getCommandManager().execute( + resultCode = player.getServer().getCommands().performCommand( new SnoopyCommandSource(player, error, output), command ); } - NbtCompound result = new NbtCompound(); + CompoundTag result = new CompoundTag(); result.putString("id", id); result.putInt("code", resultCode); - if (error[0] != null) result.putString("error", error[0].asString()); - NbtList outputResult = new NbtList(); - for (Text line: output) outputResult.add(NbtString.of(Text.Serializer.toJson(line))); + if (error[0] != null) result.putString("error", error[0].getContents()); + ListTag outputResult = new ListTag(); + for (Component line: output) outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); if (!output.isEmpty()) result.put("output", outputResult); - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withCustomNbt("clientCommand", result).build() )); @@ -120,11 +118,11 @@ public class ServerNetworkHandler } - private static void onClientData(ServerPlayerEntity player, PacketByteBuf data) + private static void onClientData(ServerPlayer player, FriendlyByteBuf data) { - NbtCompound compound = data.readNbt(); + CompoundTag compound = data.readNbt(); if (compound == null) return; - for (String key: compound.getKeys()) + for (String key: compound.getAllKeys()) { if (dataHandlers.containsKey(key)) dataHandlers.get(key).accept(player, compound.get(key)); @@ -136,9 +134,9 @@ public class ServerNetworkHandler public static void updateRuleWithConnectedClients(ParsedRule rule) { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withRule(rule).build() )); @@ -148,9 +146,9 @@ public class ServerNetworkHandler public static void updateTickSpeedToConnectedPlayers() { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withTickRate().build() )); @@ -160,9 +158,9 @@ public class ServerNetworkHandler public static void updateFrozenStateToConnectedPlayers() { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withFrozenState().build() )); @@ -172,9 +170,9 @@ public class ServerNetworkHandler public static void updateSuperHotStateToConnectedPlayers() { if(CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withSuperHotState().build() )); @@ -184,32 +182,32 @@ public class ServerNetworkHandler public static void updateTickPlayerActiveTimeoutToConnectedPlayers() { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withTickPlayerActiveTimeout().build() )); } } - public static void broadcastCustomCommand(String command, NbtElement data) + public static void broadcastCustomCommand(String command, Tag data) { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayerEntity player : validCarpetPlayers) + for (ServerPlayer player : validCarpetPlayers) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withCustomNbt(command, data).build() )); } } - public static void sendCustomCommand(ServerPlayerEntity player, String command, NbtElement data) + public static void sendCustomCommand(ServerPlayer player, String command, Tag data) { if (isValidCarpetPlayer(player)) { - player.networkHandler.sendPacket(new CustomPayloadS2CPacket( + player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, DataBuilder.create().withCustomNbt(command, data).build() )); @@ -217,10 +215,10 @@ public class ServerNetworkHandler } - public static void onPlayerLoggedOut(ServerPlayerEntity player) + public static void onPlayerLoggedOut(ServerPlayer player) { validCarpetPlayers.remove(player); - if (!player.networkHandler.connection.isLocal()) + if (!player.connection.connection.isMemoryConnection()) remoteCarpetPlayers.remove(player); } @@ -230,14 +228,14 @@ public class ServerNetworkHandler validCarpetPlayers.clear(); } - public static boolean isValidCarpetPlayer(ServerPlayerEntity player) + public static boolean isValidCarpetPlayer(ServerPlayer player) { if (CarpetSettings.superSecretSetting) return false; return validCarpetPlayers.contains(player); } - public static String getPlayerStatus(ServerPlayerEntity player) + public static String getPlayerStatus(ServerPlayer player) { if (remoteCarpetPlayers.containsKey(player)) return "carpet "+remoteCarpetPlayers.get(player); if (validCarpetPlayers.contains(player)) return "carpet "+CarpetSettings.carpetVersion; @@ -246,14 +244,14 @@ public class ServerNetworkHandler private static class DataBuilder { - private NbtCompound tag; + private CompoundTag tag; private static DataBuilder create() { return new DataBuilder(); } private DataBuilder() { - tag = new NbtCompound(); + tag = new CompoundTag(); } private DataBuilder withTickRate() { @@ -262,7 +260,7 @@ public class ServerNetworkHandler } private DataBuilder withFrozenState() { - NbtCompound tickingState = new NbtCompound(); + CompoundTag tickingState = new CompoundTag(); tickingState.putBoolean("is_paused", TickSpeed.isPaused()); tickingState.putBoolean("deepFreeze", TickSpeed.deeplyFrozen()); tag.put("TickingState", tickingState); @@ -280,16 +278,16 @@ public class ServerNetworkHandler } private DataBuilder withRule(ParsedRule rule) { - NbtCompound rules = (NbtCompound) tag.get("Rules"); + CompoundTag rules = (CompoundTag) tag.get("Rules"); if (rules == null) { - rules = new NbtCompound(); + rules = new CompoundTag(); tag.put("Rules", rules); } String identifier = rule.settingsManager.getIdentifier(); String key = rule.name; while (rules.contains(key)) { key = key+"2";} - NbtCompound ruleNBT = new NbtCompound(); + CompoundTag ruleNBT = new CompoundTag(); ruleNBT.putString("Value", rule.getAsString()); ruleNBT.putString("Manager",identifier); ruleNBT.putString("Rule",rule.name); @@ -297,15 +295,15 @@ public class ServerNetworkHandler return this; } - public DataBuilder withCustomNbt(String key, NbtElement value) + public DataBuilder withCustomNbt(String key, Tag value) { tag.put(key, value); return this; } - private PacketByteBuf build() + private FriendlyByteBuf build() { - PacketByteBuf packetBuf = new PacketByteBuf(Unpooled.buffer()); + FriendlyByteBuf packetBuf = new FriendlyByteBuf(Unpooled.buffer()); packetBuf.writeVarInt(CarpetClient.DATA); packetBuf.writeNbt(tag); return packetBuf; diff --git a/src/main/java/carpet/patches/CopyProfilerResult.java b/src/main/java/carpet/patches/CopyProfilerResult.java index 07a13782..c9c85315 100644 --- a/src/main/java/carpet/patches/CopyProfilerResult.java +++ b/src/main/java/carpet/patches/CopyProfilerResult.java @@ -1,13 +1,12 @@ package carpet.patches; -import net.minecraft.util.profiler.ProfileResult; -import net.minecraft.util.profiler.ProfilerTiming; - import java.nio.file.Path; import java.util.Collections; import java.util.List; +import net.minecraft.util.profiling.ProfileResults; +import net.minecraft.util.profiling.ResultField; -public class CopyProfilerResult implements ProfileResult { +public class CopyProfilerResult implements ProfileResults { int startI, endI; long startL, endL; public CopyProfilerResult(int startI, long startL, int endI, long endL) @@ -18,37 +17,37 @@ public class CopyProfilerResult implements ProfileResult { this.endL = endL; } @Override - public List getTimings(String parentPath) { + public List getTimes(String parentPath) { return Collections.emptyList(); } @Override - public boolean save(Path path) { + public boolean saveResults(Path path) { return false; } @Override - public long getStartTime() { + public long getStartTimeNano() { return startL; } @Override - public int getStartTick() { + public int getStartTimeTicks() { return startI; } @Override - public long getEndTime() { + public long getEndTimeNano() { return endL; } @Override - public int getEndTick() { + public int getEndTimeTicks() { return endI; } @Override - public String getRootTimings() { + public String getProfilerResults() { return ""; } } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 1c020131..96fd4cd6 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -2,48 +2,48 @@ package carpet.patches; import carpet.CarpetSettings; import com.mojang.authlib.GameProfile; -import net.minecraft.block.entity.SkullBlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket; -import net.minecraft.network.packet.s2c.play.EntitySetHeadYawS2CPacket; -import net.minecraft.network.packet.s2c.play.PlayerListS2CPacket; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.player.HungerManager; -import net.minecraft.network.NetworkSide; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerTask; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.UserCache; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.GameMode; -import net.minecraft.world.World; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.GameProfileCache; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.food.FoodData; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.SkullBlockEntity; import carpet.fakes.ServerPlayerEntityInterface; import carpet.utils.Messenger; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("EntityConstructor") -public class EntityPlayerMPFake extends ServerPlayerEntity +public class EntityPlayerMPFake extends ServerPlayer { public Runnable fixStartingPosition = () -> {}; public boolean isAShadow; - public static EntityPlayerMPFake createFake(String username, MinecraftServer server, double d0, double d1, double d2, double yaw, double pitch, RegistryKey dimensionId, GameMode gamemode, boolean flying) + public static EntityPlayerMPFake createFake(String username, MinecraftServer server, double d0, double d1, double d2, double yaw, double pitch, ResourceKey dimensionId, GameType gamemode, boolean flying) { //prolly half of that crap is not necessary, but it works - ServerWorld worldIn = server.getWorld(dimensionId); - UserCache.setUseRemote(false); + ServerLevel worldIn = server.getLevel(dimensionId); + GameProfileCache.setUsesAuthentication(false); GameProfile gameprofile; try { - gameprofile = server.getUserCache().findByName(username).orElse(null); //findByName .orElse(null) + gameprofile = server.getProfileCache().get(username).orElse(null); //findByName .orElse(null) } finally { - UserCache.setUseRemote(server.isDedicated() && server.isOnlineMode()); + GameProfileCache.setUsesAuthentication(server.isDedicatedServer() && server.usesAuthentication()); } if (gameprofile == null) { @@ -51,65 +51,65 @@ public class EntityPlayerMPFake extends ServerPlayerEntity { return null; } else { - gameprofile = new GameProfile(PlayerEntity.getOfflinePlayerUuid(username), username); + gameprofile = new GameProfile(Player.createPlayerUUID(username), username); } } if (gameprofile.getProperties().containsKey("textures")) { AtomicReference result = new AtomicReference<>(); - SkullBlockEntity.loadProperties(gameprofile, result::set); + SkullBlockEntity.updateGameprofile(gameprofile, result::set); gameprofile = result.get(); } EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, false); - instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(d0, d1, d2, (float) yaw, (float) pitch); - server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance); - instance.teleport(worldIn, d0, d1, d2, (float)yaw, (float)pitch); + instance.fixStartingPosition = () -> instance.moveTo(d0, d1, d2, (float) yaw, (float) pitch); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance); + instance.teleportTo(worldIn, d0, d1, d2, (float)yaw, (float)pitch); instance.setHealth(20.0F); instance.unsetRemoved(); - instance.stepHeight = 0.6F; - instance.interactionManager.changeGameMode(gamemode); - server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(instance, (byte) (instance.headYaw * 256 / 360)), dimensionId);//instance.dimension); - server.getPlayerManager().sendToDimension(new EntityPositionS2CPacket(instance), dimensionId);//instance.dimension); + instance.maxUpStep = 0.6F; + instance.gameMode.changeGameModeForPlayer(gamemode); + server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(instance, (byte) (instance.yHeadRot * 256 / 360)), dimensionId);//instance.dimension); + server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(instance), dimensionId);//instance.dimension); //instance.world.getChunkManager(). updatePosition(instance); - instance.dataTracker.set(PLAYER_MODEL_PARTS, (byte) 0x7f); // show all model layers (incl. capes) + instance.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f); // show all model layers (incl. capes) instance.getAbilities().flying = flying; return instance; } - public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlayerEntity player) + public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlayer player) { - player.getServer().getPlayerManager().remove(player); - player.networkHandler.disconnect(new TranslatableText("multiplayer.disconnect.duplicate_login")); - ServerWorld worldIn = player.getWorld();//.getWorld(player.dimension); + player.getServer().getPlayerList().remove(player); + player.connection.disconnect(new TranslatableComponent("multiplayer.disconnect.duplicate_login")); + ServerLevel worldIn = player.getLevel();//.getWorld(player.dimension); GameProfile gameprofile = player.getGameProfile(); EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, true); - server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), playerShadow); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow); playerShadow.setHealth(player.getHealth()); - playerShadow.networkHandler.requestTeleport(player.getX(), player.getY(), player.getZ(), player.getYaw(), player.getPitch()); - playerShadow.interactionManager.changeGameMode(player.interactionManager.getGameMode()); + playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + playerShadow.gameMode.changeGameModeForPlayer(player.gameMode.getGameModeForPlayer()); ((ServerPlayerEntityInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerEntityInterface) player).getActionPack()); - playerShadow.stepHeight = 0.6F; - playerShadow.dataTracker.set(PLAYER_MODEL_PARTS, player.getDataTracker().get(PLAYER_MODEL_PARTS)); + playerShadow.maxUpStep = 0.6F; + playerShadow.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, player.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION)); - server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(playerShadow, (byte) (player.headYaw * 256 / 360)), playerShadow.world.getRegistryKey()); - server.getPlayerManager().sendToAll(new PlayerListS2CPacket(PlayerListS2CPacket.Action.ADD_PLAYER, playerShadow)); + server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(playerShadow, (byte) (player.yHeadRot * 256 / 360)), playerShadow.level.dimension()); + server.getPlayerList().broadcastAll(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.ADD_PLAYER, playerShadow)); //player.world.getChunkManager().updatePosition(playerShadow); playerShadow.getAbilities().flying = player.getAbilities().flying; return playerShadow; } - private EntityPlayerMPFake(MinecraftServer server, ServerWorld worldIn, GameProfile profile, boolean shadow) + private EntityPlayerMPFake(MinecraftServer server, ServerLevel worldIn, GameProfile profile, boolean shadow) { super(server, worldIn, profile); isAShadow = shadow; } @Override - protected void onEquipStack(ItemStack stack) + protected void equipEventAndSound(ItemStack stack) { - if (!isUsingItem()) super.onEquipStack(stack); + if (!isUsingItem()) super.equipEventAndSound(stack); } @Override @@ -118,27 +118,27 @@ public class EntityPlayerMPFake extends ServerPlayerEntity kill(Messenger.s("Killed")); } - public void kill(Text reason) + public void kill(Component reason) { shakeOff(); - this.server.send(new ServerTask(this.server.getTicks(), () -> { - this.networkHandler.onDisconnected(reason); + this.server.tell(new TickTask(this.server.getTickCount(), () -> { + this.connection.onDisconnect(reason); })); } @Override public void tick() { - if (this.getServer().getTicks() % 10 == 0) + if (this.getServer().getTickCount() % 10 == 0) { - this.networkHandler.syncWithPlayerPosition(); - this.getWorld().getChunkManager().updatePosition(this); - onTeleportationDone(); //<- causes hard crash but would need to be done to enable portals // not as of 1.17 + this.connection.resetPosition(); + this.getLevel().getChunkSource().move(this); + hasChangedDimension(); //<- causes hard crash but would need to be done to enable portals // not as of 1.17 } try { super.tick(); - this.playerTick(); + this.doTick(); } catch (NullPointerException ignored) { @@ -151,25 +151,25 @@ public class EntityPlayerMPFake extends ServerPlayerEntity private void shakeOff() { - if (getVehicle() instanceof PlayerEntity) stopRiding(); - for (Entity passenger : getPassengersDeep()) + if (getVehicle() instanceof Player) stopRiding(); + for (Entity passenger : getIndirectPassengers()) { - if (passenger instanceof PlayerEntity) passenger.stopRiding(); + if (passenger instanceof Player) passenger.stopRiding(); } } @Override - public void onDeath(DamageSource cause) + public void die(DamageSource cause) { shakeOff(); - super.onDeath(cause); + super.die(cause); setHealth(20); - this.hungerManager = new HungerManager(); - kill(this.getDamageTracker().getDeathMessage()); + this.foodData = new FoodData(); + kill(this.getCombatTracker().getDeathMessage()); } @Override - public String getIp() + public String getIpAddress() { return "127.0.0.1"; } diff --git a/src/main/java/carpet/patches/FakeClientConnection.java b/src/main/java/carpet/patches/FakeClientConnection.java index 5ee1cb15..bb9e9ea8 100644 --- a/src/main/java/carpet/patches/FakeClientConnection.java +++ b/src/main/java/carpet/patches/FakeClientConnection.java @@ -2,12 +2,12 @@ package carpet.patches; import carpet.fakes.ClientConnectionInterface; import io.netty.channel.embedded.EmbeddedChannel; -import net.minecraft.network.ClientConnection; -import net.minecraft.network.NetworkSide; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.PacketFlow; -public class FakeClientConnection extends ClientConnection +public class FakeClientConnection extends Connection { - public FakeClientConnection(NetworkSide p) + public FakeClientConnection(PacketFlow p) { super(p); // compat with adventure-platform-fabric. This does NOT trigger other vanilla handlers for establishing a channel @@ -16,7 +16,7 @@ public class FakeClientConnection extends ClientConnection } @Override - public void disableAutoRead() + public void setReadOnly() { } diff --git a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java index e6882de4..65c236ff 100644 --- a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java +++ b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java @@ -1,28 +1,28 @@ package carpet.patches; -import net.minecraft.network.ClientConnection; -import net.minecraft.network.Packet; +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.protocol.Packet; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.server.network.ServerGamePacketListenerImpl; -public class NetHandlerPlayServerFake extends ServerPlayNetworkHandler +public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl { - public NetHandlerPlayServerFake(MinecraftServer server, ClientConnection cc, EntityPlayerMPFake playerIn) + public NetHandlerPlayServerFake(MinecraftServer server, Connection cc, EntityPlayerMPFake playerIn) { super(server, cc, playerIn); } @Override - public void sendPacket(final Packet packetIn) + public void send(final Packet packetIn) { } @Override - public void disconnect(Text message) + public void disconnect(Component message) { - if (message instanceof TranslatableText text && (text.getKey().equals("multiplayer.disconnect.idling") || text.getKey().equals("multiplayer.disconnect.duplicate_login"))) + if (message instanceof TranslatableComponent text && (text.getKey().equals("multiplayer.disconnect.idling") || text.getKey().equals("multiplayer.disconnect.duplicate_login"))) { ((EntityPlayerMPFake) player).kill(message); } diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java index 7ea1cc98..28e314ff 100644 --- a/src/main/java/carpet/script/CarpetContext.java +++ b/src/main/java/carpet/script/CarpetContext.java @@ -1,14 +1,14 @@ package carpet.script; import carpet.script.value.Value; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.math.BlockPos; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; public class CarpetContext extends Context { - public ServerCommandSource s; + public CommandSourceStack s; public final BlockPos origin; - public CarpetContext(ScriptHost host, ServerCommandSource source, BlockPos origin) + public CarpetContext(ScriptHost host, CommandSourceStack source, BlockPos origin) { super(host); s = source; diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index e6787b37..85302354 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -21,34 +21,6 @@ import carpet.settings.ParsedRule; import carpet.utils.CarpetProfiler; import carpet.utils.Messenger; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.block.BlockState; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.TntEntity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.passive.MerchantEntity; -import net.minecraft.entity.projectile.ProjectileEntity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.entity.Entity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.stat.Stat; -import net.minecraft.stat.Stats; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.village.Merchant; -import net.minecraft.village.TradeOffer; -import net.minecraft.world.World; -import net.minecraft.world.explosion.Explosion; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -67,6 +39,33 @@ import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.stats.Stat; +import net.minecraft.stats.Stats; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.entity.npc.AbstractVillager; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.trading.Merchant; +import net.minecraft.world.item.trading.MerchantOffer; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; public class CarpetEventServer { @@ -101,7 +100,7 @@ public class CarpetEventServer * @param sender - entity command source * @param runtimeArgs = options */ - public CallbackResult execute(ServerCommandSource sender, List runtimeArgs) + public CallbackResult execute(CommandSourceStack sender, List runtimeArgs) { if (!this.parametrizedArgs.isEmpty()) { @@ -110,7 +109,7 @@ public class CarpetEventServer } if (CarpetServer.scriptServer == null) return CallbackResult.FAIL; // already stopped return CarpetServer.scriptServer.events.runEventCall( - sender.withLevel(CarpetSettings.runPermissionLevel), + sender.withPermission(CarpetSettings.runPermissionLevel), host, optionalTarget, function, runtimeArgs); } @@ -120,10 +119,10 @@ public class CarpetEventServer * @param optionalRecipient - optional target player argument * @param runtimeArgs = options */ - public CallbackResult signal(ServerCommandSource sender, ServerPlayerEntity optionalRecipient, List runtimeArgs) + public CallbackResult signal(CommandSourceStack sender, ServerPlayer optionalRecipient, List runtimeArgs) { // recipent of the call doesn't match the handlingHost - if (optionalRecipient != null && !optionalRecipient.getEntityName().equals(optionalTarget)) + if (optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget)) return CallbackResult.FAIL; return execute(sender, runtimeArgs); } @@ -218,14 +217,14 @@ public class CarpetEventServer * @param argumentSupplier * @param cmdSourceSupplier */ - public void call(Supplier> argumentSupplier, Supplier cmdSourceSupplier) + public void call(Supplier> argumentSupplier, Supplier cmdSourceSupplier) { if (callList.size() > 0 && CarpetServer.scriptServer != null) { CarpetServer.scriptServer.events.handleEvents.runIfEnabled( () -> { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL); List argv = argumentSupplier.get(); // empty for onTickDone - ServerCommandSource source; + CommandSourceStack source; try { source = cmdSourceSupplier.get(); @@ -234,7 +233,7 @@ public class CarpetEventServer { return; } - String nameCheck = perPlayerDistribution ? source.getName() : null; + String nameCheck = perPlayerDistribution ? source.getTextName() : null; assert argv.size() == reqArgs; try { @@ -261,7 +260,7 @@ public class CarpetEventServer } } - public int signal(ServerCommandSource sender, ServerPlayerEntity optinoalReceipient, List callArg) + public int signal(CommandSourceStack sender, ServerPlayer optinoalReceipient, List callArg) { if (callList.isEmpty()) return 0; int successes = 0; @@ -281,7 +280,7 @@ public class CarpetEventServer return successes; } - public boolean addFromExternal(ServerCommandSource source, String hostName, String funName, Consumer hostOnEventHandler) + public boolean addFromExternal(CommandSourceStack source, String hostName, String funName, Consumer hostOnEventHandler) { ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName); if (host == null) @@ -303,7 +302,7 @@ public class CarpetEventServer { try { - target = source.getPlayer().getEntityName(); + target = source.getPlayerOrException().getScoreboardName(); } catch (CommandSyntaxException e) { @@ -382,8 +381,8 @@ public class CarpetEventServer public void onTick() { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.getCommandSource(). - withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD)) + CarpetServer.minecraft_server.createCommandSourceStack(). + withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) ); } }; @@ -394,8 +393,8 @@ public class CarpetEventServer public void onTick() { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.getCommandSource(). - withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD)) + CarpetServer.minecraft_server.createCommandSourceStack(). + withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) ); } }; @@ -406,8 +405,8 @@ public class CarpetEventServer public void onTick() { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.getCommandSource(). - withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD)) + CarpetServer.minecraft_server.createCommandSourceStack(). + withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) ); } }; @@ -423,8 +422,8 @@ public class CarpetEventServer public void onTick() { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.getCommandSource(). - withWorld(CarpetServer.minecraft_server.getWorld(World.NETHER)) + CarpetServer.minecraft_server.createCommandSourceStack(). + withLevel(CarpetServer.minecraft_server.getLevel(Level.NETHER)) ); } }; @@ -439,32 +438,32 @@ public class CarpetEventServer public void onTick() { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.getCommandSource(). - withWorld(CarpetServer.minecraft_server.getWorld(World.END)) + CarpetServer.minecraft_server.createCommandSourceStack(). + withLevel(CarpetServer.minecraft_server.getLevel(Level.END)) ); } }; public static final Event CHUNK_GENERATED = new Event("chunk_generated", 2, true) { @Override - public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { handler.call( () -> { return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)); - }, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; public static final Event CHUNK_LOADED = new Event("chunk_loaded", 2, true) { @Override - public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { handler.call( () -> { return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)); - }, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; @@ -472,49 +471,49 @@ public class CarpetEventServer public static final Event PLAYER_JUMPS = new Event("player_jumps", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_DEPLOYS_ELYTRA = new Event("player_deploys_elytra", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_WAKES_UP = new Event("player_wakes_up", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_ESCAPES_SLEEP = new Event("player_escapes_sleep", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_RIDES = new Event("player_rides", 5, false) { @Override - public void onMountControls(ServerPlayerEntity player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) + public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { handler.call( () -> Arrays.asList(new EntityValue(player), new NumericValue(forwardSpeed), new NumericValue(strafeSpeed), BooleanValue.of(jumping), BooleanValue.of(sneaking) - ), player::getCommandSource); + ), player::createCommandSourceStack); } }; public static final Event PLAYER_USES_ITEM = new Event("player_uses_item", 3, false) { @Override - public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) + public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { handler.call( () -> { @@ -522,42 +521,42 @@ public class CarpetEventServer return Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack), - StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand") + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ); - }, player::getCommandSource); + }, player::createCommandSourceStack); } }; public static final Event PLAYER_CLICKS_BLOCK = new Event("player_clicks_block", 3, false) { @Override - public void onBlockAction(ServerPlayerEntity player, BlockPos blockpos, Direction facing) + public void onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) { handler.call( () -> { return Arrays.asList( new EntityValue(player), - new BlockValue(null, player.getWorld(), blockpos), + new BlockValue(null, player.getLevel(), blockpos), StringValue.of(facing.getName()) ); - }, player::getCommandSource); + }, player::createCommandSourceStack); } }; public static final Event PLAYER_RIGHT_CLICKS_BLOCK = new Event("player_right_clicks_block", 6, false) { @Override - public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d) + public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d) { handler.call( () -> { - ItemStack itemstack = player.getStackInHand(enumhand); + ItemStack itemstack = player.getItemInHand(enumhand); BlockPos blockpos = hitRes.getBlockPos(); - Direction enumfacing = hitRes.getSide(); - Vec3d vec3d = hitRes.getPos().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + Direction enumfacing = hitRes.getDirection(); + Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack), - StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"), - new BlockValue(null, player.getWorld(), blockpos), + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), + new BlockValue(null, player.getLevel(), blockpos), StringValue.of(enumfacing.getName()), ListValue.of( new NumericValue(vec3d.x), @@ -565,23 +564,23 @@ public class CarpetEventServer new NumericValue(vec3d.z) ) ); - }, player::getCommandSource); + }, player::createCommandSourceStack); } }; public static final Event PLAYER_INTERACTS_WITH_BLOCK = new Event("player_interacts_with_block", 5, false) { @Override - public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes) + public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { handler.call( () -> { BlockPos blockpos = hitRes.getBlockPos(); - Direction enumfacing = hitRes.getSide(); - Vec3d vec3d = hitRes.getPos().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + Direction enumfacing = hitRes.getDirection(); + Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), - StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"), - new BlockValue(null, player.getWorld(), blockpos), + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), + new BlockValue(null, player.getLevel(), blockpos), StringValue.of(enumfacing.getName()), ListValue.of( new NumericValue(vec3d.x), @@ -589,167 +588,167 @@ public class CarpetEventServer new NumericValue(vec3d.z) ) ); - }, player::getCommandSource); + }, player::createCommandSourceStack); } }; public static final Event PLAYER_PLACES_BLOCK = new Event("player_places_block", 4, false) { @Override - public void onBlockPlaced(ServerPlayerEntity player, BlockPos pos, Hand enumhand, ItemStack itemstack) + public void onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { handler.call( () -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack), - StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"), - new BlockValue(null, player.getWorld(), pos) - ), player::getCommandSource); + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), + new BlockValue(null, player.getLevel(), pos) + ), player::createCommandSourceStack); } }; public static final Event PLAYER_BREAK_BLOCK = new Event("player_breaks_block", 2, false) { @Override - public void onBlockBroken(ServerPlayerEntity player, BlockPos pos, BlockState previousBS) + public void onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) { handler.call( - () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getWorld(), pos)), - player::getCommandSource + () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)), + player::createCommandSourceStack ); } }; public static final Event PLAYER_INTERACTS_WITH_ENTITY = new Event("player_interacts_with_entity", 3, false) { @Override - public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) + public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { handler.call( () -> Arrays.asList( - new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==Hand.MAIN_HAND?"mainhand":"offhand") - ), player::getCommandSource); + new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==InteractionHand.MAIN_HAND?"mainhand":"offhand") + ), player::createCommandSourceStack); } }; public static final Event PLAYER_TRADES = new Event("player_trades", 5, false) { @Override - public void onTrade(ServerPlayerEntity player, Merchant merchant, TradeOffer tradeOffer) + public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) { handler.call( () -> Arrays.asList( new EntityValue(player), - merchant instanceof MerchantEntity ? new EntityValue((MerchantEntity) merchant) : Value.NULL, - ValueConversions.of(tradeOffer.getOriginalFirstBuyItem()), - ValueConversions.of(tradeOffer.getSecondBuyItem()), - ValueConversions.of(tradeOffer.getSellItem()) - ), player::getCommandSource); + merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL, + ValueConversions.of(tradeOffer.getBaseCostA()), + ValueConversions.of(tradeOffer.getCostB()), + ValueConversions.of(tradeOffer.getResult()) + ), player::createCommandSourceStack); } }; public static final Event PLAYER_PICKS_UP_ITEM = new Event("player_picks_up_item", 2, false) { @Override - public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) { - handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::getCommandSource); + public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { + handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::createCommandSourceStack); } }; public static final Event PLAYER_ATTACKS_ENTITY = new Event("player_attacks_entity", 2, false) { @Override - public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) + public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { - handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::getCommandSource); + handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); } }; public static final Event PLAYER_STARTS_SNEAKING = new Event("player_starts_sneaking", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_STOPS_SNEAKING = new Event("player_stops_sneaking", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_STARTS_SPRINTING = new Event("player_starts_sprinting", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_STOPS_SPRINTING = new Event("player_stops_sprinting", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_RELEASED_ITEM = new Event("player_releases_item", 3, false) { @Override - public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) + public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) handler.call( () -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack), - StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand") - ), player::getCommandSource); + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") + ), player::createCommandSourceStack); } }; public static final Event PLAYER_FINISHED_USING_ITEM = new Event("player_finishes_using_item", 3, false) { @Override - public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) + public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) handler.call( () -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack), - new StringValue(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand") - ), player::getCommandSource); + new StringValue(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") + ), player::createCommandSourceStack); } }; public static final Event PLAYER_DROPS_ITEM = new Event("player_drops_item", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_DROPS_STACK = new Event("player_drops_stack", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_CHOOSES_RECIPE = new Event("player_chooses_recipe", 3, false) { @Override - public void onRecipeSelected(ServerPlayerEntity player, Identifier recipe, boolean fullStack) + public void onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) { handler.call( () -> Arrays.asList( new EntityValue(player), StringValue.of(NBTSerializableValue.nameFromRegistryId(recipe)), BooleanValue.of(fullStack) - ), player::getCommandSource); + ), player::createCommandSourceStack); } }; public static final Event PLAYER_SWITCHES_SLOT = new Event("player_switches_slot", 3, false) { @Override - public void onSlotSwitch(ServerPlayerEntity player, int from, int to) + public void onSlotSwitch(ServerPlayer player, int from, int to) { if (from == to) return; // initial slot update handler.call( () -> @@ -757,27 +756,27 @@ public class CarpetEventServer new EntityValue(player), new NumericValue(from), new NumericValue(to) - ), player::getCommandSource); + ), player::createCommandSourceStack); } }; public static final Event PLAYER_SWAPS_HANDS = new Event("player_swaps_hands", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_SWINGS_HAND = new Event("player_swings_hand", 2, false) { @Override - public void onHandAction(ServerPlayerEntity player, Hand hand) + public void onHandAction(ServerPlayer player, InteractionHand hand) { handler.call( () -> Arrays.asList( new EntityValue(player), - StringValue.of(hand == Hand.MAIN_HAND ? "mainhand" : "offhand") + StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ) - , player::getCommandSource); + , player::createCommandSourceStack); } }; public static final Event PLAYER_TAKES_DAMAGE = new Event("player_takes_damage", 4, false) @@ -789,9 +788,9 @@ public class CarpetEventServer Arrays.asList( new EntityValue(target), new NumericValue(amount), - StringValue.of(source.getName()), - source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker()) - ), target::getCommandSource); + StringValue.of(source.getMsgId()), + source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) + ), target::createCommandSourceStack); } }; public static final Event PLAYER_DEALS_DAMAGE = new Event("player_deals_damage", 3, false) @@ -800,70 +799,70 @@ public class CarpetEventServer public void onDamage(Entity target, float amount, DamageSource source) { handler.call( () -> - Arrays.asList(new EntityValue(source.getAttacker()), new NumericValue(amount), new EntityValue(target)), - () -> source.getAttacker().getCommandSource() + Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)), + () -> source.getEntity().createCommandSourceStack() ); } }; public static final Event PLAYER_COLLIDES_WITH_ENTITY = new Event("player_collides_with_entity", 2, false) { @Override - public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) { - handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::getCommandSource); + public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { + handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); } }; public static final Event PLAYER_DIES = new Event("player_dies", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_RESPAWNS = new Event("player_respawns", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_CHANGES_DIMENSION = new Event("player_changes_dimension", 5, false) { @Override - public void onDimensionChange(ServerPlayerEntity player, Vec3d from, Vec3d to, RegistryKey fromDim, RegistryKey dimTo) + public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) { // eligibility already checked in mixin Value fromValue = ListValue.fromTriple(from.x, from.y, from.z); Value toValue = (to == null)?Value.NULL:ListValue.fromTriple(to.x, to.y, to.z); - Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.getValue())); - Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.getValue())); + Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location())); + Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location())); - handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::getCommandSource); + handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack); } }; public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) { @Override - public void onPlayerEvent(ServerPlayerEntity player) + public void onPlayerEvent(ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource); + handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) { @Override - public void onPlayerMessage(ServerPlayerEntity player, String message) + public void onPlayerMessage(ServerPlayer player, String message) { - handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::getCommandSource); + handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); } }; public static final Event STATISTICS = new Event("statistic", 4, false) { - private Identifier getStatId(Stat stat) + private ResourceLocation getStatId(Stat stat) { - return stat.getType().getRegistry().getId(stat.getValue()); + return stat.getType().getRegistry().getKey(stat.getValue()); } - private final Set skippedStats = new HashSet(){{ + private final Set skippedStats = new HashSet(){{ add(Stats.TIME_SINCE_DEATH); add(Stats.TIME_SINCE_REST); //add(Stats.PLAY_ONE_MINUTE); @@ -871,35 +870,35 @@ public class CarpetEventServer add(Stats.TOTAL_WORLD_TIME); }}; @Override - public void onPlayerStatistic(ServerPlayerEntity player, Stat stat, int amount) + public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { - Identifier id = getStatId(stat); + ResourceLocation id = getStatId(stat); if (skippedStats.contains(id)) return; handler.call( () -> Arrays.asList( new EntityValue(player), - StringValue.of(NBTSerializableValue.nameFromRegistryId(Registry.STAT_TYPE.getId(stat.getType()))), + StringValue.of(NBTSerializableValue.nameFromRegistryId(Registry.STAT_TYPE.getKey(stat.getType()))), StringValue.of(NBTSerializableValue.nameFromRegistryId(id)), new NumericValue(amount) - ), player::getCommandSource); + ), player::createCommandSourceStack); } }; public static final Event LIGHTNING = new Event("lightning", 2, true) { @Override - public void onWorldEventFlag(ServerWorld world, BlockPos pos, int flag) + public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { handler.call( () -> Arrays.asList( new BlockValue(null, world, pos), flag>0?Value.TRUE:Value.FALSE - ), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; public static final Event CARPET_RULE_CHANGES = new Event("carpet_rule_changes", 2, true) { @Override - public void onCarpetRuleChanges(ParsedRule rule, ServerCommandSource source) + public void onCarpetRuleChanges(ParsedRule rule, CommandSourceStack source) { String identifier = rule.settingsManager.getIdentifier(); final String namespace; @@ -919,10 +918,10 @@ public class CarpetEventServer private static LivingEntity getExplosionCausingEntity(Entity entity) { if (entity == null) return null; - else if (entity instanceof TntEntity) return ((TntEntity)entity).getCausingEntity(); + else if (entity instanceof PrimedTnt) return ((PrimedTnt)entity).getOwner(); else if (entity instanceof LivingEntity) return (LivingEntity)entity; - else if (entity instanceof ProjectileEntity) { - Entity owner = ((ProjectileEntity)entity).getOwner(); + else if (entity instanceof Projectile) { + Entity owner = ((Projectile)entity).getOwner(); if (owner instanceof LivingEntity) return (LivingEntity)owner; } return null; @@ -931,7 +930,7 @@ public class CarpetEventServer public static final Event EXPLOSION_OUTCOME = new Event("explosion_outcome", 8, true) { @Override - public void onExplosion(ServerWorld world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.DestructionType type) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( @@ -941,11 +940,11 @@ public class CarpetEventServer EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)), StringValue.of(type.name().toLowerCase(Locale.ROOT)), BooleanValue.of(createFire), - new ListValue(affectedBlocks.stream().filter(b -> !world.isAir(b)). map( // da heck they send air blocks + new ListValue(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks b -> new BlockValue(world.getBlockState(b),world,b) ).collect(Collectors.toList())), new ListValue(affectedEntities.stream().map(EntityValue::of).collect(Collectors.toList())) - ), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; @@ -954,7 +953,7 @@ public class CarpetEventServer public static final Event EXPLOSION = new Event("explosion", 6, true) { @Override - public void onExplosion(ServerWorld world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.DestructionType type) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( @@ -964,7 +963,7 @@ public class CarpetEventServer EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)), StringValue.of(type.name().toLowerCase(Locale.ROOT)), BooleanValue.of(createFire) - ), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; @@ -972,13 +971,13 @@ public class CarpetEventServer @Deprecated public static String getEntityLoadEventName(EntityType et) { - return "entity_loaded_" + ValueConversions.of(Registry.ENTITY_TYPE.getId(et)).getString(); + return "entity_loaded_" + ValueConversions.of(Registry.ENTITY_TYPE.getKey(et)).getString(); } @Deprecated public static final Map, Event> ENTITY_LOAD= new HashMap<>() {{ - EntityType.get("zombie"); + EntityType.byString("zombie"); Registry.ENTITY_TYPE.forEach(et -> { put(et, new Event(getEntityLoadEventName(et), 1, true, false) { @@ -987,7 +986,7 @@ public class CarpetEventServer { handler.call( () -> Collections.singletonList(new EntityValue(entity)), - () -> CarpetServer.minecraft_server.getCommandSource().withWorld((ServerWorld) entity.world).withLevel(CarpetSettings.runPermissionLevel) + () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel) ); } }); @@ -996,12 +995,12 @@ public class CarpetEventServer public static String getEntityHandlerEventName(EntityType et) { - return "entity_handler_" + ValueConversions.of(Registry.ENTITY_TYPE.getId(et)).getString(); + return "entity_handler_" + ValueConversions.of(Registry.ENTITY_TYPE.getKey(et)).getString(); } public static final Map, Event> ENTITY_HANDLER= new HashMap<>() {{ - EntityType.get("zombie"); + EntityType.byString("zombie"); Registry.ENTITY_TYPE.forEach(et -> { put(et, new Event(getEntityHandlerEventName(et), 2, true, false) { @@ -1010,7 +1009,7 @@ public class CarpetEventServer { handler.call( () -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)), - () -> CarpetServer.minecraft_server.getCommandSource().withWorld((ServerWorld) entity.world).withLevel(CarpetSettings.runPermissionLevel) + () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel) ); } }); @@ -1092,30 +1091,30 @@ public class CarpetEventServer public boolean deprecated() {return false;} //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types public void onTick() { } - public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated) { } - public void onPlayerEvent(ServerPlayerEntity player) { } - public void onPlayerMessage(ServerPlayerEntity player, String message) { } - public void onPlayerStatistic(ServerPlayerEntity player, Stat stat, int amount) { } - public void onMountControls(ServerPlayerEntity player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { } - public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) { } - public void onBlockAction(ServerPlayerEntity player, BlockPos blockpos, Direction facing) { } - public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes) { } - public void onBlockBroken(ServerPlayerEntity player, BlockPos pos, BlockState previousBS) { } - public void onBlockPlaced(ServerPlayerEntity player, BlockPos pos, Hand enumhand, ItemStack itemstack) { } - public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) { } - public void onHandAction(ServerPlayerEntity player, Hand enumhand) { } + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { } + public void onPlayerEvent(ServerPlayer player) { } + public void onPlayerMessage(ServerPlayer player, String message) { } + public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { } + public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { } + public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { } + public void onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) { } + public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { } + public void onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) { } + public void onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { } + public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { } + public void onHandAction(ServerPlayer player, InteractionHand enumhand) { } public void onEntityAction(Entity entity, boolean created) { } - public void onDimensionChange(ServerPlayerEntity player, Vec3d from, Vec3d to, RegistryKey fromDim, RegistryKey dimTo) {} + public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) {} public void onDamage(Entity target, float amount, DamageSource source) { } - public void onRecipeSelected(ServerPlayerEntity player, Identifier recipe, boolean fullStack) {} - public void onSlotSwitch(ServerPlayerEntity player, int from, int to) {} - public void onTrade(ServerPlayerEntity player, Merchant merchant, TradeOffer tradeOffer) {} + public void onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) {} + public void onSlotSwitch(ServerPlayer player, int from, int to) {} + public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) {} - public void onExplosion(ServerWorld world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.DestructionType type) { } - public void onWorldEvent(ServerWorld world, BlockPos pos) { } - public void onWorldEventFlag(ServerWorld world, BlockPos pos, int flag) { } - public void onCarpetRuleChanges(ParsedRule rule, ServerCommandSource source) { } - public void onCustomPlayerEvent(ServerPlayerEntity player, Object ... args) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { } + public void onWorldEvent(ServerLevel world, BlockPos pos) { } + public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { } + public void onCarpetRuleChanges(ParsedRule rule, CommandSourceStack source) { } + public void onCustomPlayerEvent(ServerPlayer player, Object ... args) { if (handler.reqArgs != (args.length+1)) throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+(args.length+1)); @@ -1125,13 +1124,13 @@ public class CarpetEventServer valArgs.add(EntityValue.of(player)); for (Object o: args) { - valArgs.add(ValueConversions.guess(player.getWorld(), o)); + valArgs.add(ValueConversions.guess(player.getLevel(), o)); } return valArgs; - }, player::getCommandSource + }, player::createCommandSourceStack ); } - public void onCustomWorldEvent(ServerWorld world, Object ... args) + public void onCustomWorldEvent(ServerLevel world, Object ... args) { if (handler.reqArgs != args.length) throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+args.length); @@ -1143,7 +1142,7 @@ public class CarpetEventServer valArgs.add(ValueConversions.guess(world, o)); } return valArgs; - }, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world) + }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } } @@ -1182,7 +1181,7 @@ public class CarpetEventServer scheduledCalls.add(new ScheduledCall(context, function, args, due)); } - public void runScheduledCall(BlockPos origin, ServerCommandSource source, String hostname, CarpetScriptHost host, FunctionValue udf, List argv) + public void runScheduledCall(BlockPos origin, CommandSourceStack source, String hostname, CarpetScriptHost host, FunctionValue udf, List argv) { if (hostname != null && !scriptServer.modules.containsKey(hostname)) // well - scheduled call app got unloaded return; @@ -1193,25 +1192,25 @@ public class CarpetEventServer catch (NullPointerException | InvalidCallbackException | IntegrityException ignored) { } } - public CallbackResult runEventCall(ServerCommandSource sender, String hostname, String optionalTarget, FunctionValue udf, List argv) + public CallbackResult runEventCall(CommandSourceStack sender, String hostname, String optionalTarget, FunctionValue udf, List argv) { CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname); // no such app if (appHost == null) return CallbackResult.FAIL; // dummy call for player apps that reside on the global copy - do not run them, but report as passes. if (appHost.isPerUser() && optionalTarget==null) return CallbackResult.PASS; - ServerPlayerEntity target = null; + ServerPlayer target = null; if (optionalTarget != null) { - target = sender.getServer().getPlayerManager().getPlayer(optionalTarget); + target = sender.getServer().getPlayerList().getPlayerByName(optionalTarget); if (target == null) return CallbackResult.FAIL; } - ServerCommandSource source = sender.withLevel(CarpetSettings.runPermissionLevel); + CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel); CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); if (executingHost == null) return CallbackResult.FAIL; try { - executingHost.callUDF(BlockPos.ORIGIN, source.withLevel(CarpetSettings.runPermissionLevel), udf, argv); + executingHost.callUDF(BlockPos.ZERO, source.withPermission(CarpetSettings.runPermissionLevel), udf, argv); return CallbackResult.SUCCESS; } catch (NullPointerException | InvalidCallbackException | IntegrityException error) @@ -1221,7 +1220,7 @@ public class CarpetEventServer } } - public boolean addEventFromCommand(ServerCommandSource source, String event, String host, String funName) + public boolean addEventFromCommand(CommandSourceStack source, String event, String host, String funName) { Event ev = Event.getEvent(event, CarpetServer.scriptServer); if (ev == null) @@ -1249,7 +1248,7 @@ public class CarpetEventServer return ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args); } - public int signalEvent(String event, CarpetContext cc, ServerPlayerEntity optionalTarget, List callArgs) + public int signalEvent(String event, CarpetContext cc, ServerPlayer optionalTarget, List callArgs) { Event ev = Event.getEvent(event, ((CarpetScriptHost)cc.host).getScriptServer()); if (ev == null) return -1; @@ -1262,7 +1261,7 @@ public class CarpetEventServer //return !(event.globalOnly && (host.perUser || host.parent != null)); } - public boolean removeEventFromCommand(ServerCommandSource source, String event, String funName) + public boolean removeEventFromCommand(CommandSourceStack source, String event, String funName) { Event ev = Event.getEvent(event, CarpetServer.scriptServer); if (ev == null) diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java index 60da9003..05989076 100644 --- a/src/main/java/carpet/script/CarpetExpression.java +++ b/src/main/java/carpet/script/CarpetExpression.java @@ -17,21 +17,21 @@ import carpet.script.value.BlockValue; import carpet.script.value.EntityValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; -import net.minecraft.entity.Entity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.math.BlockPos; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; public class CarpetExpression { - private final ServerCommandSource source; + private final CommandSourceStack source; private final BlockPos origin; private final Expression expr; // these are for extensions public Expression getExpr() {return expr;} - public ServerCommandSource getSource() {return source;} + public CommandSourceStack getSource() {return source;} public BlockPos getOrigin() {return origin;} - public CarpetExpression(Module module, String expression, ServerCommandSource source, BlockPos origin) + public CarpetExpression(Module module, String expression, CommandSourceStack source, BlockPos origin) { this.origin = origin; this.source = source; @@ -60,7 +60,7 @@ public class CarpetExpression with("x", (c, t) -> new NumericValue(x - origin.getX()).bindTo("x")). with("y", (c, t) -> new NumericValue(y - origin.getY()).bindTo("y")). with("z", (c, t) -> new NumericValue(z - origin.getZ()).bindTo("z")). - with("_", (c, t) -> new BlockValue(null, source.getWorld(), new BlockPos(x, y, z)).bindTo("_")); + with("_", (c, t) -> new BlockValue(null, source.getLevel(), new BlockPos(x, y, z)).bindTo("_")); Entity e = source.getEntity(); if (e==null) { diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 25ea3f57..7074fc21 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -39,16 +39,16 @@ import net.fabricmc.loader.api.SemanticVersion; import net.fabricmc.loader.api.Version; import net.fabricmc.loader.api.VersionParsingException; import net.fabricmc.loader.api.metadata.version.VersionPredicate; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.nbt.NbtElement; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.BaseText; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; import org.apache.commons.lang3.tuple.Pair; import java.math.BigInteger; @@ -68,26 +68,26 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.Math.max; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; public class CarpetScriptHost extends ScriptHost { private final CarpetScriptServer scriptServer; - public ServerCommandSource responsibleSource; + public CommandSourceStack responsibleSource; - private NbtElement globalState; + private Tag globalState; private int saveTimeout; public boolean persistenceRequired; public Map appConfig; public Map appArgTypes; - Predicate commandValidator; + Predicate commandValidator; boolean isRuleApp; public AppStoreManager.StoreNode storeSource; - private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp) + private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp) { super(code, perUser, parent); this.saveTimeout = 0; @@ -109,7 +109,7 @@ public class CarpetScriptHost extends ScriptHost storeSource = null; } - public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, ServerCommandSource source, Predicate commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource) + public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, CommandSourceStack source, Predicate commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource) { CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp); // parse code and convert to expression @@ -150,13 +150,13 @@ public class CarpetScriptHost extends ScriptHost return host; } - private static int execute(CommandContext ctx, String hostName, FunctionArgument funcSpec, List paramNames) throws CommandSyntaxException + private static int execute(CommandContext ctx, String hostName, FunctionArgument funcSpec, List paramNames) throws CommandSyntaxException { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); List argNames = funcSpec.function.getArguments(); if ((argNames.size()-funcSpec.args.size()) != paramNames.size()) - throw new SimpleCommandExceptionType(new LiteralText("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create(); + throw new SimpleCommandExceptionType(new TextComponent("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create(); List args = new ArrayList<>(argNames.size()); for (String s : paramNames) { @@ -171,8 +171,8 @@ public class CarpetScriptHost extends ScriptHost return intres; } - public LiteralArgumentBuilder addPathToCommand( - LiteralArgumentBuilder command, + public LiteralArgumentBuilder addPathToCommand( + LiteralArgumentBuilder command, List path, FunctionArgument functionSpec ) throws CommandSyntaxException @@ -187,7 +187,7 @@ public class CarpetScriptHost extends ScriptHost } List reversedPath = new ArrayList<>(path); Collections.reverse(reversedPath); - ArgumentBuilder argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs)); + ArgumentBuilder argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs)); for (int i = 1; i < reversedPath.size(); i++) { argChain = reversedPath.get(i).getCommandNode(this).then(argChain); @@ -195,13 +195,13 @@ public class CarpetScriptHost extends ScriptHost return command.then(argChain); } - public LiteralArgumentBuilder getNewCommandTree( - List,FunctionArgument>> entries, Predicate useValidator + public LiteralArgumentBuilder getNewCommandTree( + List,FunctionArgument>> entries, Predicate useValidator ) throws CommandSyntaxException { String hostName = main.getName(); - Predicate configValidator = getCommandConfigPermissions(); - LiteralArgumentBuilder command = literal(hostName). + Predicate configValidator = getCommandConfigPermissions(); + LiteralArgumentBuilder command = literal(hostName). requires((player) -> CarpetServer.scriptServer.modules.containsKey(hostName) && useValidator.test(player) && configValidator.test(player)); for (Pair,FunctionArgument> commandData : entries) { @@ -210,7 +210,7 @@ public class CarpetScriptHost extends ScriptHost return command; } - public Predicate getCommandConfigPermissions() throws CommandSyntaxException + public Predicate getCommandConfigPermissions() throws CommandSyntaxException { Value confValue = appConfig.get(StringValue.of("command_permission")); if (confValue == null) return s -> true; @@ -218,16 +218,16 @@ public class CarpetScriptHost extends ScriptHost { int level = ((NumericValue) confValue).getInt(); if (level < 1 || level > 4) throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4"); - return s -> s.hasPermissionLevel(level); + return s -> s.hasPermission(level); } if (!(confValue instanceof FunctionValue)) { String perm = confValue.getString().toLowerCase(Locale.ROOT); switch (perm) { - case "ops": return s -> s.hasPermissionLevel(2); - case "server": return s -> !(s.getEntity() instanceof ServerPlayerEntity); - case "players": return s -> s.getEntity() instanceof ServerPlayerEntity; + case "ops": return s -> s.hasPermission(2); + case "server": return s -> !(s.getEntity() instanceof ServerPlayer); + case "players": return s -> s.getEntity() instanceof ServerPlayer; case "all": return s -> true; default: throw CommandArgument.error("Unknown command permission: "+perm); } @@ -242,7 +242,7 @@ public class CarpetScriptHost extends ScriptHost CarpetScriptHost cHost = null; cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s); Value response = cHost.handleCommand(s, fun, Collections.singletonList( - (s.getEntity() instanceof ServerPlayerEntity)?new EntityValue(s.getEntity()):Value.NULL) + (s.getEntity() instanceof ServerPlayer)?new EntityValue(s.getEntity()):Value.NULL) ); boolean res = response.getBoolean(); CarpetProfiler.end_current_section(currentSection); @@ -385,7 +385,7 @@ public class CarpetScriptHost extends ScriptHost } } - public Boolean addAppCommands(Consumer notifier) + public Boolean addAppCommands(Consumer notifier) { try { @@ -400,10 +400,10 @@ public class CarpetScriptHost extends ScriptHost { try { - LiteralArgumentBuilder command = readCommands(commandValidator); + LiteralArgumentBuilder command = readCommands(commandValidator); if (command != null) { - scriptServer.server.getCommandManager().getDispatcher().register(command); + scriptServer.server.getCommands().getDispatcher().register(command); return true; } else { @@ -453,7 +453,7 @@ public class CarpetScriptHost extends ScriptHost } } - private Boolean addLegacyCommand(Consumer notifier) + private Boolean addLegacyCommand(Consumer notifier) { if (main == null) return false; if (getFunction("__command") == null) return false; @@ -464,7 +464,7 @@ public class CarpetScriptHost extends ScriptHost return null; } - Predicate configValidator; + Predicate configValidator; try { configValidator = getCommandConfigPermissions(); @@ -475,7 +475,7 @@ public class CarpetScriptHost extends ScriptHost return null; } String hostName = getName(); - LiteralArgumentBuilder command = literal(hostName). + LiteralArgumentBuilder command = literal(hostName). requires((player) -> scriptServer.modules.containsKey(hostName) && commandValidator.test(player) && configValidator.test(player)). executes( (c) -> { @@ -525,11 +525,11 @@ public class CarpetScriptHost extends ScriptHost }))); } } - scriptServer.server.getCommandManager().getDispatcher().register(command); + scriptServer.server.getCommands().getDispatcher().register(command); return true; } - public LiteralArgumentBuilder readCommands(Predicate useValidator) throws CommandSyntaxException + public LiteralArgumentBuilder readCommands(Predicate useValidator) throws CommandSyntaxException { Value commands = appConfig.get(StringValue.of("commands")); @@ -599,7 +599,7 @@ public class CarpetScriptHost extends ScriptHost } } - public CarpetScriptHost retrieveForExecution(ServerCommandSource source, ServerPlayerEntity player) + public CarpetScriptHost retrieveForExecution(CommandSourceStack source, ServerPlayer player) { CarpetScriptHost target = null; if (!perUser) @@ -608,13 +608,13 @@ public class CarpetScriptHost extends ScriptHost } else if (player != null) { - target = (CarpetScriptHost) retrieveForExecution(player.getEntityName()); + target = (CarpetScriptHost) retrieveForExecution(player.getScoreboardName()); } if (target != null && target.errorSnooper == null) target.setChatErrorSnooper(source); return target; } - public CarpetScriptHost retrieveOwnForExecution(ServerCommandSource source) throws CommandSyntaxException + public CarpetScriptHost retrieveOwnForExecution(CommandSourceStack source) throws CommandSyntaxException { if (!perUser) { @@ -622,21 +622,21 @@ public class CarpetScriptHost extends ScriptHost return this; } // user based - ServerPlayerEntity player; + ServerPlayer player; try { - player = source.getPlayer(); + player = source.getPlayerOrException(); } catch (CommandSyntaxException ignored) { - throw new SimpleCommandExceptionType(new LiteralText("Cannot run player based apps without the player context")).create(); + throw new SimpleCommandExceptionType(new TextComponent("Cannot run player based apps without the player context")).create(); } - CarpetScriptHost userHost = (CarpetScriptHost)retrieveForExecution(player.getEntityName()); + CarpetScriptHost userHost = (CarpetScriptHost)retrieveForExecution(player.getScoreboardName()); if (userHost.errorSnooper == null) userHost.setChatErrorSnooper(source); return userHost; } - public Value handleCommandLegacy(ServerCommandSource source, String call, List coords, String arg) + public Value handleCommandLegacy(CommandSourceStack source, String call, List coords, String arg) { try { @@ -660,7 +660,7 @@ public class CarpetScriptHost extends ScriptHost return Value.NULL; } - public Value handleCommand(ServerCommandSource source, FunctionValue function, List args) + public Value handleCommand(CommandSourceStack source, FunctionValue function, List args) { try { @@ -681,7 +681,7 @@ public class CarpetScriptHost extends ScriptHost return Value.NULL; } - public Value callLegacy(ServerCommandSource source, String call, List coords, String arg) + public Value callLegacy(CommandSourceStack source, String call, List coords, String arg) { if (CarpetServer.scriptServer.stopAll) throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); @@ -768,7 +768,7 @@ public class CarpetScriptHost extends ScriptHost { // TODO: this is just for now - invoke would be able to invoke other hosts scripts assertAppIntegrity(function.getModule()); - Context context = new CarpetContext(this, source, BlockPos.ORIGIN); + Context context = new CarpetContext(this, source, BlockPos.ZERO); return scriptServer.events.handleEvents.getWhileDisabled(() -> function.getExpression().evalValue( () -> function.lazyEval(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, @@ -781,7 +781,7 @@ public class CarpetScriptHost extends ScriptHost } } - public Value call(ServerCommandSource source, FunctionValue function, List argv) + public Value call(CommandSourceStack source, FunctionValue function, List argv) { if (CarpetServer.scriptServer.stopAll) throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); @@ -799,7 +799,7 @@ public class CarpetScriptHost extends ScriptHost try { assertAppIntegrity(function.getModule()); - Context context = new CarpetContext(this, source, BlockPos.ORIGIN); + Context context = new CarpetContext(this, source, BlockPos.ZERO); return function.getExpression().evalValue( () -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, @@ -812,7 +812,7 @@ public class CarpetScriptHost extends ScriptHost } } - public Value callUDF(BlockPos pos, ServerCommandSource source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException + public Value callUDF(BlockPos pos, CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException { if (CarpetServer.scriptServer.stopAll) return Value.NULL; @@ -843,12 +843,12 @@ public class CarpetScriptHost extends ScriptHost public Value callNow(FunctionValue fun, List arguments) { - ServerPlayerEntity player = (user==null)?null:scriptServer.server.getPlayerManager().getPlayer(user); - ServerCommandSource source = (player != null)?player.getCommandSource():scriptServer.server.getCommandSource(); + ServerPlayer player = (user==null)?null:scriptServer.server.getPlayerList().getPlayerByName(user); + CommandSourceStack source = (player != null)?player.createCommandSourceStack():scriptServer.server.createCommandSourceStack(); return scriptServer.events.handleEvents.getWhileDisabled(()->{ try { - return callUDF(BlockPos.ORIGIN, source, fun, arguments); + return callUDF(BlockPos.ZERO, source, fun, arguments); } catch (InvalidCallbackException ignored) { @@ -873,9 +873,9 @@ public class CarpetScriptHost extends ScriptHost { String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName()); - for (ServerWorld world : scriptServer.server.getWorlds()) + for (ServerLevel world : scriptServer.server.getAllLevels()) { - for (Entity e : world.getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName))) + for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { e.discard(); } @@ -890,12 +890,12 @@ public class CarpetScriptHost extends ScriptHost Module.saveData(main, globalState); } - private NbtElement loadState() + private Tag loadState() { return Module.getData(main); } - public NbtElement readFileTag(FileArgument fdesc) + public Tag readFileTag(FileArgument fdesc) { if (getName() == null && !fdesc.isShared) return null; if (fdesc.resource != null) @@ -905,7 +905,7 @@ public class CarpetScriptHost extends ScriptHost return ((CarpetScriptHost)parent).globalState; } - public boolean writeTagFile(NbtElement tag, FileArgument fdesc) + public boolean writeTagFile(Tag tag, FileArgument fdesc) { if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host. @@ -973,14 +973,14 @@ public class CarpetScriptHost extends ScriptHost } } - public void setChatErrorSnooper(ServerCommandSource source) + public void setChatErrorSnooper(CommandSourceStack source) { responsibleSource = source; errorSnooper = (expr, /*Nullable*/ token, ctx, message) -> { try { - source.getPlayer(); + source.getPlayerOrException(); } catch (CommandSyntaxException e) { @@ -1021,7 +1021,7 @@ public class CarpetScriptHost extends ScriptHost } /** - *

Creates a {@link BaseText} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over + *

Creates a {@link BaseComponent} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over * tooltip with the value of the local at that location

* @param line The line to find references to locals on * @param context The {@link Context} to extract the locals from @@ -1031,7 +1031,7 @@ public class CarpetScriptHost extends ScriptHost * @implNote The implementation of this method is far from perfect, and won't detect actual references to variables, but try to find the strings * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions */ - private static BaseText withLocals(String format, String line, Context context) + private static BaseComponent withLocals(String format, String line, Context context) { format += " "; List stringsToFormat = new ArrayList<>(); diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index 99597247..dc5d3c8b 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -30,10 +30,10 @@ import com.mojang.brigadier.tree.CommandNode; import net.fabricmc.api.EnvType; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.WorldSavePath; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.storage.LevelResource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -123,7 +123,7 @@ public class CarpetScriptServer unloadableModules = new HashSet<>(); tickStart = 0L; stopAll = false; - holyMoly = server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet()); + holyMoly = server.getCommands().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet()); globalHost = CarpetScriptHost.create(this, null, false, null, p -> true, false, null); } @@ -139,7 +139,7 @@ public class CarpetScriptServer { for (String moduleName: listAvailableModules(false)) { - addScriptHost(server.getCommandSource(), moduleName, null, true, true, false, null); + addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null); } } CarpetEventServer.Event.START.onTick(); @@ -148,7 +148,7 @@ public class CarpetScriptServer public Module getModule(String name, boolean allowLibraries) { try { - Path folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts"); + Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); if (!Files.exists(folder)) Files.createDirectories(folder); Optional @@ -208,7 +208,7 @@ public class CarpetScriptServer } } try { - Path worldScripts = server.getSavePath(WorldSavePath.ROOT).resolve("scripts"); + Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); if (!Files.exists(worldScripts)) Files.createDirectories(worldScripts); Files.list(worldScripts) @@ -237,7 +237,7 @@ public class CarpetScriptServer return modules.get(name); } - public boolean addScriptHost(ServerCommandSource source, String name, Predicate commandValidator, + public boolean addScriptHost(CommandSourceStack source, String name, Predicate commandValidator, boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer) { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL); @@ -312,9 +312,9 @@ public class CarpetScriptServer if (newHost.isPerUser()) { // that will provide player hosts right at the startup - for (ServerPlayerEntity player : source.getServer().getPlayerManager().getPlayerList()) + for (ServerPlayer player : source.getServer().getPlayerList().getPlayers()) { - newHost.retrieveForExecution(player.getCommandSource(), player); + newHost.retrieveForExecution(player.createCommandSourceStack(), player); } } else @@ -335,7 +335,7 @@ public class CarpetScriptServer } - public boolean removeScriptHost(ServerCommandSource source, String name, boolean notifySource, boolean isRuleApp) + public boolean removeScriptHost(CommandSourceStack source, String name, boolean notifySource, boolean isRuleApp) { name = name.toLowerCase(Locale.ROOT); if (!modules.containsKey(name) || (!isRuleApp && !unloadableModules.contains(name))) @@ -353,12 +353,12 @@ public class CarpetScriptServer return true; } - public boolean uninstallApp(ServerCommandSource source, String name) + public boolean uninstallApp(CommandSourceStack source, String name) { try { name = name.toLowerCase(Locale.ROOT); - Path folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts/trash"); + Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash"); if (!Files.exists(folder)) Files.createDirectories(folder); if (!Files.exists(folder.getParent().resolve(name+".sc"))) { @@ -401,7 +401,7 @@ public class CarpetScriptServer } } - public void onPlayerJoin(ServerPlayerEntity player) + public void onPlayerJoin(ServerPlayer player) { modules.values().forEach(h -> { @@ -409,7 +409,7 @@ public class CarpetScriptServer { try { - h.retrieveOwnForExecution(player.getCommandSource()); + h.retrieveOwnForExecution(player.createCommandSourceStack()); } catch (CommandSyntaxException ignored) { @@ -418,7 +418,7 @@ public class CarpetScriptServer }); } - private static record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) + private static record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) { private TransferData(CarpetScriptHost host) { @@ -430,10 +430,10 @@ public class CarpetScriptServer { Map apps = new HashMap<>(); modules.forEach((s, h) -> apps.put(s, new TransferData(h))); - apps.keySet().forEach(s -> removeScriptHost(server.getCommandSource(), s, false, false)); + apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false)); CarpetEventServer.Event.clearAllBuiltinEvents(); init(); - apps.forEach((s, data) -> addScriptHost(server.getCommandSource(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null)); + apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null)); } public void reAddCommands() diff --git a/src/main/java/carpet/script/EntityEventsGroup.java b/src/main/java/carpet/script/EntityEventsGroup.java index 5e51278f..a249f67c 100644 --- a/src/main/java/carpet/script/EntityEventsGroup.java +++ b/src/main/java/carpet/script/EntityEventsGroup.java @@ -8,16 +8,15 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import net.minecraft.entity.Entity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.util.math.Vec3d; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; public class EntityEventsGroup { @@ -48,7 +47,7 @@ public class EntityEventsGroup } if (key.user() != null) { - if (entity.getServer().getPlayerManager().getPlayer(key.user())==null) + if (entity.getServer().getPlayerList().getPlayerByName(key.user())==null) { iterator.remove(); continue; @@ -105,8 +104,8 @@ public class EntityEventsGroup return Arrays.asList( new EntityValue(entity), new NumericValue(amount), - new StringValue(source.getName()), - source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker()) + new StringValue(source.getMsgId()), + source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) ); } }; @@ -117,9 +116,9 @@ public class EntityEventsGroup { return Arrays.asList( new EntityValue(entity), - ValueConversions.of((Vec3d) providedArgs[0]), - ValueConversions.of((Vec3d) providedArgs[1]), - ValueConversions.of((Vec3d) providedArgs[2]) + ValueConversions.of((Vec3) providedArgs[0]), + ValueConversions.of((Vec3) providedArgs[1]), + ValueConversions.of((Vec3) providedArgs[2]) ); } }; @@ -143,7 +142,7 @@ public class EntityEventsGroup public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args) { assert args.length == argcount-1; - return tickCall.execute(entity.getCommandSource(), makeArgs(entity, args)); + return tickCall.execute(entity.createCommandSourceStack(), makeArgs(entity, args)); } protected List makeArgs(Entity entity, Object ... args) { diff --git a/src/main/java/carpet/script/annotation/FunctionsTestClass.java b/src/main/java/carpet/script/annotation/FunctionsTestClass.java index 93aa1b35..005ee54e 100644 --- a/src/main/java/carpet/script/annotation/FunctionsTestClass.java +++ b/src/main/java/carpet/script/annotation/FunctionsTestClass.java @@ -3,11 +3,6 @@ package carpet.script.annotation; import carpet.logging.HUDController; import carpet.script.annotation.Param.AllowSingleton; import carpet.script.exception.InternalExpressionException; -import net.minecraft.network.packet.s2c.play.TitleS2CPacket; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.text.Text; - import java.util.List; import java.util.Locale; import java.util.Map; diff --git a/src/main/java/carpet/script/annotation/Locator.java b/src/main/java/carpet/script/annotation/Locator.java index d4d90e6a..50eea6d3 100644 --- a/src/main/java/carpet/script/annotation/Locator.java +++ b/src/main/java/carpet/script/annotation/Locator.java @@ -5,7 +5,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedType; import java.util.Iterator; - +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.state.BlockState; import com.google.common.collect.Lists; import carpet.script.CarpetContext; @@ -18,8 +19,6 @@ import carpet.script.bundled.Module; import carpet.script.value.BlockValue; import carpet.script.value.FunctionValue; import carpet.script.value.Value; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; @@ -62,7 +61,7 @@ public interface Locator /** *

Represents that the annotated argument must be gotten by passing the arguments in there into a {@link Vector3Argument} locator.

* - *

Must be used in either a {@link Vector3Argument} or a {@link net.minecraft.util.math.Vec3d Vec3d} parameter.

+ *

Must be used in either a {@link Vector3Argument} or a {@link net.minecraft.world.phys.Vec3 Vec3d} parameter.

*/ @Documented @Retention(RUNTIME) @@ -71,7 +70,7 @@ public interface Locator { /** *

Whether or not should the {@link Vector3Argument} locator accept an optional direction aside from the - * {@link net.minecraft.util.math.Vec3d}

This parameter can only be used in a {@link Vector3Argument} type, since else there is no way + * {@link net.minecraft.world.phys.Vec3}

This parameter can only be used in a {@link Vector3Argument} type, since else there is no way * to get the direction too.

*/ boolean optionalDirection() default false; @@ -187,7 +186,7 @@ public interface Locator { this.optionalDirection = annotation.optionalDirection(); this.optionalEntity = annotation.optionalEntity(); - this.returnVec3d = type == net.minecraft.util.math.Vec3d.class; // Because of the locator + this.returnVec3d = type == net.minecraft.world.phys.Vec3.class; // Because of the locator if (returnVec3d && optionalDirection) throw new IllegalArgumentException("optionalDirection Locator.Vec3d cannot be used for Vec3d type, use Vector3Argument instead"); if (!returnVec3d && type != Vector3Argument.class) diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index da4f64ee..c9de72ca 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -4,8 +4,14 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Function; - -import net.minecraft.nbt.NbtElement; +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.ClassUtils; import carpet.script.LazyValue; @@ -16,13 +22,6 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import net.minecraft.entity.Entity; -import net.minecraft.item.ItemStack; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.dynamic.GlobalPos; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; /** *

A converter from a given {@link Object} of type T into a {@link LazyValue}, used in order to convert the outputs of methods into usable Scarpet @@ -47,12 +46,12 @@ public final class OutputConverter registerToValue(Long.class, NumericValue::of); registerToValue(String.class, StringValue::new); registerToValue(Entity.class, EntityValue::new); - registerToValue(Text.class, FormattedTextValue::new); - registerToValue(NbtElement.class, NBTSerializableValue::new); + registerToValue(Component.class, FormattedTextValue::new); + registerToValue(Tag.class, NBTSerializableValue::new); registerToValue(BlockPos.class, ValueConversions::of); - registerToValue(Vec3d.class, ValueConversions::of); + registerToValue(Vec3.class, ValueConversions::of); registerToValue(ItemStack.class, ValueConversions::of); - registerToValue(Identifier.class, ValueConversions::of); + registerToValue(ResourceLocation.class, ValueConversions::of); registerToValue(GlobalPos.class, ValueConversions::of); } diff --git a/src/main/java/carpet/script/annotation/Param.java b/src/main/java/carpet/script/annotation/Param.java index 4078669f..89ac37fd 100644 --- a/src/main/java/carpet/script/annotation/Param.java +++ b/src/main/java/carpet/script/annotation/Param.java @@ -20,9 +20,9 @@ import carpet.script.value.FormattedTextValue; import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; +import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.server.level.ServerPlayer; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; @@ -97,7 +97,7 @@ public interface Param } /** - *

Defines that a parameter of type {@link String}, {@link Text}, {@link ServerPlayerEntity}, {@link Boolean} or other registered strict type + *

Defines that a parameter of type {@link String}, {@link Component}, {@link ServerPlayer}, {@link Boolean} or other registered strict type * must be of its corresponding {@link Value} in order to be accepted (respectively {@link StringValue}, {@link FormattedTextValue}, * {@link EntityValue} or {@link BooleanValue}).

* @@ -105,7 +105,7 @@ public interface Param * {@code new LiteralText(Value#getString())}, {@link EntityValue#getPlayerByValue(MinecraftServer, Value)} or {@link Value#getBoolean()}.

* *

You can define "shallow strictness" ({@link #shallow()}) if you want to allow passing both a {@link StringValue} or a - * {@link FormattedTextValue} to a {@link Text} parameter or a {@link NumericValue} to a {@link BooleanValue}, but not any {@link Value}.

+ * {@link FormattedTextValue} to a {@link Component} parameter or a {@link NumericValue} to a {@link BooleanValue}, but not any {@link Value}.

* */ @Documented @@ -114,7 +114,7 @@ public interface Param public @interface Strict { /** - *

Defines whether this parameter can accept types with "shallow strictness", that is, in order to get a {@link Text}, accepting either a + *

Defines whether this parameter can accept types with "shallow strictness", that is, in order to get a {@link Component}, accepting either a * {@link StringValue} or a {@link FormattedTextValue} as the parameter, or in order to get a {@link Boolean}, accepting either a * {@link NumericValue} or a {@link BooleanValue}.

* @@ -198,9 +198,9 @@ public interface Param static { // TODO Specify strictness in name? registerStrictConverter(String.class, false, new SimpleTypeConverter<>(StringValue.class, StringValue::getString, "string")); - registerStrictConverter(Text.class, false, new SimpleTypeConverter<>(FormattedTextValue.class, FormattedTextValue::getText, "text")); - registerStrictConverter(Text.class, true, new SimpleTypeConverter<>(StringValue.class, FormattedTextValue::getTextByValue, "text")); - registerStrictConverter(ServerPlayerEntity.class, false, new SimpleTypeConverter<>(EntityValue.class, + registerStrictConverter(Component.class, false, new SimpleTypeConverter<>(FormattedTextValue.class, FormattedTextValue::getText, "text")); + registerStrictConverter(Component.class, true, new SimpleTypeConverter<>(StringValue.class, FormattedTextValue::getTextByValue, "text")); + registerStrictConverter(ServerPlayer.class, false, new SimpleTypeConverter<>(EntityValue.class, v -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, v), "online player entity")); registerStrictConverter(Boolean.class, false, new SimpleTypeConverter<>(BooleanValue.class, BooleanValue::getBoolean, "boolean")); registerStrictConverter(Boolean.class, true, new SimpleTypeConverter<>(NumericValue.class, NumericValue::getBoolean, "boolean")); diff --git a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java index b0711a2e..9d915c53 100644 --- a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java +++ b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java @@ -3,7 +3,10 @@ package carpet.script.annotation; import java.util.HashMap; import java.util.Map; import java.util.function.Function; - +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; import carpet.CarpetServer; import carpet.script.exception.InternalExpressionException; import carpet.script.value.EntityValue; @@ -11,10 +14,6 @@ import carpet.script.value.FormattedTextValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import net.minecraft.entity.Entity; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; -import net.minecraft.world.World; /** *

A simple {@link ValueConverter} implementation that converts from a specified subclass of {@link Value} into {@code } by using a given @@ -32,10 +31,10 @@ public final class SimpleTypeConverter implements ValueConve private static final Map, SimpleTypeConverter> byResult = new HashMap<>(); static { - registerType(Value.class, ServerPlayerEntity.class, val -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, val), "online player"); + registerType(Value.class, ServerPlayer.class, val -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, val), "online player"); registerType(EntityValue.class, Entity.class, EntityValue::getEntity, "entity"); - registerType(Value.class, World.class, val -> ValueConversions.dimFromValue(val, CarpetServer.minecraft_server), "dimension"); - registerType(Value.class, Text.class, FormattedTextValue::getTextByValue, "text"); + registerType(Value.class, Level.class, val -> ValueConversions.dimFromValue(val, CarpetServer.minecraft_server), "dimension"); + registerType(Value.class, Component.class, FormattedTextValue::getTextByValue, "text"); registerType(Value.class, String.class, Value::getString, "string"); // Check out @Param.Strict for more specific types // Primitives are also query those classes diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index f2f1a90d..8d37f78f 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -41,68 +41,64 @@ import carpet.script.value.ValueConversions; import carpet.utils.Messenger; import com.google.common.collect.Lists; import net.minecraft.SharedConstants; -import net.minecraft.block.BlockState; -import net.minecraft.command.DataCommandStorage; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.decoration.ArmorStandEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtHelper; +import net.minecraft.Util; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.Rotations; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.network.Packet; -import net.minecraft.network.packet.s2c.play.ClearTitleS2CPacket; -import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; -import net.minecraft.network.packet.s2c.play.PlaySoundIdS2CPacket; -import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket; -//import net.minecraft.network.packet.s2c.play.TitleS2CPacket; -//import net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action; -import net.minecraft.network.packet.s2c.play.SubtitleS2CPacket; -import net.minecraft.network.packet.s2c.play.TitleFadeS2CPacket; -import net.minecraft.network.packet.s2c.play.TitleS2CPacket; -import net.minecraft.particle.ParticleEffect; -import net.minecraft.resource.DataPackSettings; -import net.minecraft.resource.ReloadableResourceManagerImpl; -import net.minecraft.resource.ResourcePackManager; -import net.minecraft.resource.ResourcePackProfile; -import net.minecraft.resource.ServerResourceManager; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket; +import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket; +import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket; +import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket; +import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket; +import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket; +import net.minecraft.resources.RegistryReadOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.sound.SoundCategory; -import net.minecraft.stat.Stat; -import net.minecraft.stat.StatType; -import net.minecraft.text.BaseText; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; -import net.minecraft.util.Util; -import net.minecraft.util.WorldSavePath; -import net.minecraft.util.dynamic.RegistryOps; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.EulerAngle; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.DynamicRegistryManager; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.SaveProperties; -import net.minecraft.world.World; -import net.minecraft.world.biome.source.BiomeAccess; -import net.minecraft.world.border.WorldBorderListener; -import net.minecraft.world.dimension.DimensionOptions; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.GeneratorOptions; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.level.UnmodifiableLevelProperties; -import net.minecraft.world.level.storage.LevelStorage; +import net.minecraft.server.ServerResources; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.packs.repository.Pack; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.resources.SimpleReloadableResourceManager; +import net.minecraft.sounds.SoundSource; +import net.minecraft.stats.Stat; +import net.minecraft.stats.StatType; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.BorderChangeListener; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.storage.CommandStorage; +import net.minecraft.world.level.storage.DerivedLevelData; +import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.WorldData; +import net.minecraft.world.phys.Vec3; import org.apache.commons.io.FileUtils; import com.google.gson.Gson; @@ -136,7 +132,7 @@ import static java.lang.Math.min; public class Auxiliary { public static final String MARKER_STRING = "__scarpet_marker"; - private static final Map mixerMap = Arrays.stream(SoundCategory.values()).collect(Collectors.toMap(SoundCategory::getName, k -> k)); + private static final Map mixerMap = Arrays.stream(SoundSource.values()).collect(Collectors.toMap(SoundSource::getName, k -> k)); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().registerTypeAdapter(Value.class, new ScarpetJsonDeserializer()).create(); @Deprecated @@ -158,16 +154,16 @@ public class Auxiliary { CarpetContext cc = (CarpetContext)c; if (lv.size() == 0) { - return ListValue.wrap(Registry.SOUND_EVENT.getIds().stream().map(ValueConversions::of)); + return ListValue.wrap(Registry.SOUND_EVENT.keySet().stream().map(ValueConversions::of)); } String rawString = lv.get(0).getString(); - Identifier soundName = InputValidator.identifierOf(rawString); + ResourceLocation soundName = InputValidator.identifierOf(rawString); Vector3Argument locator = Vector3Argument.findIn(lv, 1); if (Registry.SOUND_EVENT.get(soundName) == null) throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND); float volume = 1.0F; float pitch = 1.0F; - SoundCategory mixer = SoundCategory.MASTER; + SoundSource mixer = SoundSource.MASTER; if (lv.size() > 0+locator.offset) { volume = (float) NumericValue.asNumber(lv.get(0+locator.offset)).getDouble(); @@ -182,13 +178,13 @@ public class Auxiliary { } } } - Vec3d vec = locator.vec; + Vec3 vec = locator.vec; double d0 = Math.pow(volume > 1.0F ? (double)(volume * 16.0F) : 16.0D, 2.0D); int count = 0; - for (ServerPlayerEntity player : cc.s.getWorld().getPlayers( (p) -> p.squaredDistanceTo(vec) < d0)) + for (ServerPlayer player : cc.s.getLevel().getPlayers( (p) -> p.distanceToSqr(vec) < d0)) { count++; - player.networkHandler.sendPacket(new PlaySoundIdS2CPacket(soundName, mixer, vec, volume, pitch)); + player.connection.send(new ClientboundCustomSoundPacket(soundName, mixer, vec, volume, pitch)); } return new NumericValue(count); }); @@ -196,15 +192,15 @@ public class Auxiliary { expression.addContextFunction("particle", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.getIds().stream().map(ValueConversions::of)); + if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of)); MinecraftServer ms = cc.s.getServer(); - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); String particleName = lv.get(0).getString(); int count = 10; double speed = 0; float spread = 0.5f; - ServerPlayerEntity player = null; + ServerPlayer player = null; if (lv.size() > locator.offset) { count = (int) NumericValue.asNumber(lv.get(locator.offset)).getLong(); @@ -216,24 +212,24 @@ public class Auxiliary { speed = NumericValue.asNumber(lv.get(2 + locator.offset)).getDouble(); if (lv.size() > 3 + locator.offset) // should accept entity as well as long as it is player { - player = ms.getPlayerManager().getPlayer(lv.get(3 + locator.offset).getString()); + player = ms.getPlayerList().getPlayerByName(lv.get(3 + locator.offset).getString()); } } } } - ParticleEffect particle = ShapeDispatcher.getParticleData(particleName); - Vec3d vec = locator.vec; + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName); + Vec3 vec = locator.vec; if (player == null) { - for (PlayerEntity p : (world.getPlayers())) + for (Player p : (world.players())) { - world.spawnParticles((ServerPlayerEntity)p, particle, true, vec.x, vec.y, vec.z, count, + world.sendParticles((ServerPlayer)p, particle, true, vec.x, vec.y, vec.z, count, spread, spread, spread, speed); } } else { - world.spawnParticles(player, + world.sendParticles(player, particle, true, vec.x, vec.y, vec.z, count, spread, spread, spread, speed); } @@ -244,13 +240,13 @@ public class Auxiliary { expression.addContextFunction("particle_line", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); String particleName = lv.get(0).getString(); - ParticleEffect particle = ShapeDispatcher.getParticleData(particleName); + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName); Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; - ServerPlayerEntity player = null; + ServerPlayer player = null; if (lv.size() > pos2.offset+0 ) { density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble(); @@ -264,18 +260,18 @@ public class Auxiliary { if (playerValue instanceof EntityValue) { Entity e = ((EntityValue) playerValue).getEntity(); - if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_line' player argument has to be a player"); - player = (ServerPlayerEntity) e; + if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_line' player argument has to be a player"); + player = (ServerPlayer) e; } else { - player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString()); + player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString()); } } } return new NumericValue(ShapeDispatcher.drawParticleLine( - (player == null)?world.getPlayers(): Collections.singletonList(player), + (player == null)?world.players(): Collections.singletonList(player), particle, pos1.vec, pos2.vec, density )); }); @@ -283,14 +279,14 @@ public class Auxiliary { expression.addContextFunction("particle_box", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); String particleName = lv.get(0).getString(); - ParticleEffect particle = ShapeDispatcher.getParticleData(particleName); + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName); Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; - ServerPlayerEntity player = null; + ServerPlayer player = null; if (lv.size() > pos2.offset+0 ) { density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble(); @@ -304,21 +300,21 @@ public class Auxiliary { if (playerValue instanceof EntityValue) { Entity e = ((EntityValue) playerValue).getEntity(); - if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_box' player argument has to be a player"); - player = (ServerPlayerEntity) e; + if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_box' player argument has to be a player"); + player = (ServerPlayer) e; } else { - player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString()); + player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString()); } } } - Vec3d a = pos1.vec; - Vec3d b = pos2.vec; - Vec3d from = new Vec3d(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); - Vec3d to = new Vec3d(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); + Vec3 a = pos1.vec; + Vec3 b = pos2.vec; + Vec3 from = new Vec3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); + Vec3 to = new Vec3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); int particleCount = ShapeDispatcher.Box.particleMesh( - player==null?world.getPlayers():Collections.singletonList(player), + player==null?world.players():Collections.singletonList(player), particle, density, from, to ); return new NumericValue(particleCount); @@ -330,9 +326,9 @@ public class Auxiliary { expression.addContextFunction("draw_shape", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); MinecraftServer server = world.getServer(); - Set playerTargets = new HashSet<>(); + Set playerTargets = new HashSet<>(); List shapes = new ArrayList<>(); if (lv.size() == 1) // bulk { @@ -350,7 +346,7 @@ public class Auxiliary { } ShapeDispatcher.sendShape( - (playerTargets.isEmpty())?cc.s.getWorld().getPlayers():playerTargets, + (playerTargets.isEmpty())?cc.s.getLevel().players():playerTargets, shapes ); return Value.TRUE; @@ -382,7 +378,7 @@ public class Auxiliary { throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head"); } - ArmorStandEntity armorstand = new ArmorStandEntity(EntityType.ARMOR_STAND, cc.s.getWorld()); + ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, cc.s.getLevel()); double yoffset; if (targetBlock == null && name.isEmpty()) { @@ -396,14 +392,14 @@ public class Auxiliary { { if (targetBlock==null) { - yoffset = -armorstand.getHeight()-0.41; + yoffset = -armorstand.getBbHeight()-0.41; } else { - yoffset = -armorstand.getHeight()+0.3; + yoffset = -armorstand.getBbHeight()+0.3; } } - armorstand.refreshPositionAndAngles( + armorstand.moveTo( pointLocator.vec.x, //pointLocator.vec.y - ((!interactable && targetBlock == null)?0.41f:((targetBlock==null)?(armorstand.getHeight()+0.41):(armorstand.getHeight()-0.3))), pointLocator.vec.y + yoffset, @@ -411,21 +407,21 @@ public class Auxiliary { (float)pointLocator.yaw, (float) pointLocator.pitch ); - armorstand.addScoreboardTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName())); - armorstand.addScoreboardTag(MARKER_STRING); + armorstand.addTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName())); + armorstand.addTag(MARKER_STRING); if (targetBlock != null) - armorstand.equipStack(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem())); + armorstand.setItemSlot(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem())); if (!name.isEmpty()) { - armorstand.setCustomName(new LiteralText(name)); + armorstand.setCustomName(new TextComponent(name)); armorstand.setCustomNameVisible(true); } - armorstand.setHeadRotation(new EulerAngle((int)pointLocator.pitch,0,0)); + armorstand.setHeadPose(new Rotations((int)pointLocator.pitch,0,0)); armorstand.setNoGravity(true); armorstand.setInvisible(true); armorstand.setInvulnerable(true); - armorstand.getDataTracker().set(ArmorStandEntity.ARMOR_STAND_FLAGS, (byte)(interactable?8 : 16|8)); - cc.s.getWorld().spawnEntity(armorstand); + armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte)(interactable?8 : 16|8)); + cc.s.getLevel().addFreshEntity(armorstand); return new EntityValue(armorstand); }); @@ -433,7 +429,7 @@ public class Auxiliary { CarpetContext cc = (CarpetContext)c; int total = 0; String markerName = MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()); - for (Entity e : cc.s.getWorld().getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName))) + for (Entity e : cc.s.getLevel().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { total ++; e.discard(); // discard // remove(); @@ -443,7 +439,7 @@ public class Auxiliary { expression.addUnaryFunction("nbt", NBTSerializableValue::fromValue); - expression.addUnaryFunction("escape_nbt", v -> new StringValue(NbtString.escape(v.getString()))); + expression.addUnaryFunction("escape_nbt", v -> new StringValue(StringTag.quoteAndEscape(v.getString()))); expression.addUnaryFunction("parse_nbt", v -> { if (v instanceof NBTSerializableValue) return ((NBTSerializableValue) v).toValue(); @@ -457,9 +453,9 @@ public class Auxiliary { if (numParam != 2 && numParam != 3) throw new InternalExpressionException("'tag_matches' requires 2 or 3 arguments"); if (lv.get(1).isNull()) return Value.TRUE; if (lv.get(0).isNull()) return Value.FALSE; - NbtElement source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag(); - NbtElement match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag(); - return BooleanValue.of(NbtHelper.matches(match, source, numParam == 2 || lv.get(2).getBoolean())); + Tag source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag(); + Tag match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag(); + return BooleanValue.of(NbtUtils.compareNbt(match, source, numParam == 2 || lv.get(2).getBoolean())); }); expression.addFunction("encode_nbt", lv -> { @@ -467,7 +463,7 @@ public class Auxiliary { if (argSize==0 || argSize > 2) throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters"); Value v = lv.get(0); boolean force = (argSize > 1) && lv.get(1).getBoolean(); - NbtElement tag; + Tag tag; try { tag = v.toTag(force); @@ -483,30 +479,30 @@ public class Auxiliary { expression.addContextFunction("print", -1, (c, t, lv) -> { if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments"); - ServerCommandSource s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).s; MinecraftServer server = s.getServer(); Value res = lv.get(0); - List targets = null; + List targets = null; if (lv.size() == 2) { List playerValues = (res instanceof ListValue)?((ListValue) res).getItems():Collections.singletonList(res); - List playerTargets = new ArrayList<>(); + List playerTargets = new ArrayList<>(); playerValues.forEach(pv -> { - ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pv); + ServerPlayer player = EntityValue.getPlayerByValue(server, pv); if (player == null) throw new InternalExpressionException("Cannot target player "+pv.getString()+" in print"); playerTargets.add(player); }); targets = playerTargets; res = lv.get(1); } - Text message = FormattedTextValue.getTextByValue(res); + Component message = FormattedTextValue.getTextByValue(res); if (targets == null) { - s.sendFeedback(message, false); + s.sendSuccess(message, false); } else { - targets.forEach(p -> p.getCommandSource().sendFeedback(message, false)); + targets.forEach(p -> p.createCommandSourceStack().sendSuccess(message, false)); } return res; // pass through for variables }); @@ -516,40 +512,40 @@ public class Auxiliary { Value pVal = lv.get(0); if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal); MinecraftServer server = ((CarpetContext)c).s.getServer(); - Stream targets = ((ListValue) pVal).getItems().stream().map(v -> + Stream targets = ((ListValue) pVal).getItems().stream().map(v -> { - ServerPlayerEntity player = EntityValue.getPlayerByValue(server, v); + ServerPlayer player = EntityValue.getPlayerByValue(server, v); if (player == null) throw new InternalExpressionException("'display_title' requires a valid online player or a list of players as first argument. "+v.getString()+" is not a player."); return player; }); - Function> packetGetter = null; + Function> packetGetter = null; //TitleS2CPacket.Action action; String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); switch (actionString) { case "title": - packetGetter = TitleS2CPacket::new; + packetGetter = ClientboundSetTitleTextPacket::new; //action = Action.TITLE; if (lv.size() < 3) throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); break; case "subtitle": - packetGetter = SubtitleS2CPacket::new; + packetGetter = ClientboundSetSubtitleTextPacket::new; if (lv.size() < 3) throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); //action = Action.SUBTITLE; break; case "actionbar": - packetGetter = OverlayMessageS2CPacket::new; + packetGetter = ClientboundSetActionBarTextPacket::new; if (lv.size() < 3) throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); //action = Action.ACTIONBAR; break; case "clear": - packetGetter = (x) -> new ClearTitleS2CPacket(true); // resetting default fade + packetGetter = (x) -> new ClientboundClearTitlesPacket(true); // resetting default fade //action = Action.CLEAR; break; case "player_list_header": @@ -560,7 +556,7 @@ public class Auxiliary { } //if (action != Action.CLEAR && lv.size() < 3) // throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); - Text title; + Component title; boolean soundsTrue = false; if (lv.size() > 2) { @@ -571,35 +567,35 @@ public class Auxiliary { else title = null; // Will never happen, just to make lambda happy if (packetGetter == null) { - Map map; + Map map; if (actionString.equals("player_list_header")) map = HUDController.scarpet_headers; else map = HUDController.scarpet_footers; AtomicInteger total = new AtomicInteger(0); - List targetList = targets.collect(Collectors.toList()); + List targetList = targets.collect(Collectors.toList()); if (!soundsTrue) // null or empty string targetList.forEach(target -> { - map.remove(target.getEntityName()); + map.remove(target.getScoreboardName()); total.getAndIncrement(); }); else targetList.forEach(target -> { - map.put(target.getEntityName(), (BaseText) title); + map.put(target.getScoreboardName(), (BaseComponent) title); total.getAndIncrement(); }); HUDController.update_hud(((CarpetContext)c).s.getServer(), targetList); return NumericValue.of(total.get()); } - TitleFadeS2CPacket timesPacket; // TimesPacket + ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket if (lv.size() > 3) { if (lv.size() != 6) throw new InternalExpressionException("'display_title' needs all fade-in, stay and fade-out times"); int in = NumericValue.asNumber(lv.get(3),"fade in for display_title" ).getInt(); int stay = NumericValue.asNumber(lv.get(4),"stay for display_title" ).getInt(); int out = NumericValue.asNumber(lv.get(5),"fade out for display_title" ).getInt(); - timesPacket = new TitleFadeS2CPacket(in, stay, out); + timesPacket = new ClientboundSetTitlesAnimationPacket(in, stay, out); //timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out); } else timesPacket = null; @@ -608,8 +604,8 @@ public class Auxiliary { //TitleS2CPacket packet = new TitleS2CPacket(action, title); AtomicInteger total = new AtomicInteger(0); targets.forEach(p -> { - if (timesPacket != null) p.networkHandler.sendPacket(timesPacket); - p.networkHandler.sendPacket(packet); + if (timesPacket != null) p.connection.send(timesPacket); + p.connection.send(packet); total.getAndIncrement(); }); return NumericValue.of(total.get()); @@ -624,12 +620,12 @@ public class Auxiliary { expression.addContextFunction("run", 1, (c, t, lv) -> { - ServerCommandSource s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).s; try { - Text[] error = {null}; - List output = new ArrayList<>(); - Value retval = new NumericValue(s.getServer().getCommandManager().execute( + Component[] error = {null}; + List output = new ArrayList<>(); + Value retval = new NumericValue(s.getServer().getCommands().performCommand( new SnoopyCommandSource(s, error, output), lv.get(0).getString()) ); @@ -641,39 +637,39 @@ public class Auxiliary { } catch (Exception exc) { - return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new LiteralText(exc.getMessage()))); + return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new TextComponent(exc.getMessage()))); } }); expression.addContextFunction("save", 0, (c, t, lv) -> { - ServerCommandSource s = ((CarpetContext)c).s; - s.getServer().getPlayerManager().saveAllPlayerData(); - s.getServer().save(true,true,true); - for (ServerWorld world : s.getServer().getWorlds()) + CommandSourceStack s = ((CarpetContext)c).s; + s.getServer().getPlayerList().saveAll(); + s.getServer().saveAllChunks(true,true,true); + for (ServerLevel world : s.getServer().getAllLevels()) { - world.getChunkManager().tick(() -> true, false); + world.getChunkSource().tick(() -> true, false); } CarpetScriptServer.LOG.warn("Saved chunks"); return Value.TRUE; }); expression.addContextFunction("tick_time", 0, (c, t, lv) -> - new NumericValue(((CarpetContext) c).s.getServer().getTicks())); + new NumericValue(((CarpetContext) c).s.getServer().getTickCount())); expression.addContextFunction("world_time", 0, (c, t, lv) -> { c.host.issueDeprecation("world_time()"); - return new NumericValue(((CarpetContext) c).s.getWorld().getTime()); + return new NumericValue(((CarpetContext) c).s.getLevel().getGameTime()); }); expression.addContextFunction("day_time", -1, (c, t, lv) -> { - Value time = new NumericValue(((CarpetContext) c).s.getWorld().getTimeOfDay()); + Value time = new NumericValue(((CarpetContext) c).s.getLevel().getDayTime()); if (lv.size() > 0) { long newTime = NumericValue.asNumber(lv.get(0)).getLong(); if (newTime < 0) newTime = 0; - ((CarpetContext) c).s.getWorld().setTimeOfDay(newTime);// setTimeOfDay(newTime); + ((CarpetContext) c).s.getLevel().setDayTime(newTime);// setTimeOfDay(newTime); } return time; }); @@ -687,9 +683,9 @@ public class Auxiliary { expression.addContextFunction("game_tick", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerCommandSource s = cc.s; + CommandSourceStack s = cc.s; if (CarpetServer.scriptServer == null) return Value.NULL; - if (!s.getServer().isOnThread()) throw new InternalExpressionException("Unable to run ticks from threads"); + if (!s.getServer().isSameThread()) throw new InternalExpressionException("Unable to run ticks from threads"); if (CarpetServer.scriptServer.tickDepth > 16) throw new InternalExpressionException("'game_tick' function caused other 'game_tick' functions to run. You should not allow that."); try { @@ -725,9 +721,9 @@ public class Auxiliary { }); expression.addContextFunction("seed", -1, (c, t, lv) -> { - ServerCommandSource s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).s; c.host.issueDeprecation("seed()"); - return new NumericValue(s.getWorld().getSeed()); + return new NumericValue(s.getLevel().getSeed()); }); expression.addContextFunction("relight", -1, (c, t, lv) -> @@ -735,28 +731,28 @@ public class Auxiliary { CarpetContext cc = (CarpetContext) c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockPos pos = locator.block.getPos(); - ServerWorld world = cc.s.getWorld(); - ((ThreadedAnvilChunkStorageInterface) world.getChunkManager().threadedAnvilChunkStorage).relightChunk(new ChunkPos(pos)); + ServerLevel world = cc.s.getLevel(); + ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos)); WorldTools.forceChunkUpdate(pos, world); return Value.TRUE; }); // Should this be deprecated for system_info('source_dimension')? expression.addContextFunction("current_dimension", 0, (c, t, lv) -> - ValueConversions.of( ((CarpetContext)c).s.getWorld())); + ValueConversions.of( ((CarpetContext)c).s.getLevel())); expression.addContextFunction("view_distance", 0, (c, t, lv) -> { c.host.issueDeprecation("view_distance()"); - return new NumericValue(((CarpetContext)c).s.getServer().getPlayerManager().getViewDistance()); + return new NumericValue(((CarpetContext)c).s.getServer().getPlayerList().getViewDistance()); }); // lazy due to passthrough and context changing ability expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> { - ServerCommandSource outerSource = ((CarpetContext)c).s; + CommandSourceStack outerSource = ((CarpetContext)c).s; Value dimensionValue = lv.get(0).evalValue(c); - World world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); - if (world == outerSource.getWorld()) return lv.get(1); - ServerCommandSource innerSource = outerSource.withWorld((ServerWorld)world); + Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); + if (world == outerSource.getLevel()) return lv.get(1); + CommandSourceStack innerSource = outerSource.withLevel((ServerLevel)world); Context newCtx = c.recreate(); ((CarpetContext) newCtx).s = innerSource; newCtx.variables = c.variables; @@ -769,21 +765,21 @@ public class Auxiliary { { Map plopData = new HashMap<>(); CarpetContext cc = (CarpetContext)c; - DynamicRegistryManager registryManager = cc.s.getWorld().getRegistryManager(); + RegistryAccess registryManager = cc.s.getLevel().registryAccess(); plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("features"), - ListValue.wrap(Registry.FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(Registry.FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_features"), - ListValue.wrap(registryManager.get(Registry.CONFIGURED_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structures"), - ListValue.wrap(Registry.STRUCTURE_FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(Registry.STRUCTURE_FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_structures"), - ListValue.wrap(registryManager.get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); return MapValue.wrap(plopData); } @@ -792,14 +788,14 @@ public class Auxiliary { throw new InternalExpressionException("'plop' needs extra argument indicating what to plop"); String what = lv.get(locator.offset).getString(); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().executeBlocking( () -> { - Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getWorld(), locator.block.getPos()); + Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getLevel(), locator.block.getPos()); if (res == null) return; if (what.equalsIgnoreCase("boulder")) // there might be more of those - WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getWorld()); + WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getLevel()); result[0] = BooleanValue.of(res); }); return result[0]; @@ -861,7 +857,7 @@ public class Auxiliary { Value retVal; if (fdesc.type == FileArgument.Type.NBT) { - NbtElement state = ((CarpetScriptHost) c.host).readFileTag(fdesc); + Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); if (state == null) return Value.NULL; retVal = new NBTSerializableValue(state); } @@ -898,7 +894,7 @@ public class Auxiliary { NBTSerializableValue tagValue = (val instanceof NBTSerializableValue) ? (NBTSerializableValue) val : new NBTSerializableValue(val.getString()); - NbtElement tag = tagValue.getTag(); + Tag tag = tagValue.getTag(); success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc); } else if (fdesc.type == FileArgument.Type.JSON) @@ -970,17 +966,17 @@ public class Auxiliary { expression.addContextFunction("statistic", 3, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerPlayerEntity player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0)); + ServerPlayer player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0)); if (player == null) return Value.NULL; - Identifier category; - Identifier statName; + ResourceLocation category; + ResourceLocation statName; category = InputValidator.identifierOf(lv.get(1).getString()); statName = InputValidator.identifierOf(lv.get(2).getString()); StatType type = Registry.STAT_TYPE.get(category); if (type == null) return Value.NULL; Stat stat = getStat(type, statName); if (stat == null) return Value.NULL; - return new NumericValue(player.getStatHandler().getStat(stat)); + return new NumericValue(player.getStats().getValue(stat)); }); //handle_event('event', function...) @@ -1006,7 +1002,7 @@ public class Auxiliary { String eventName = lv.get(0).getString(); // no such event yet if (CarpetEventServer.Event.getEvent(eventName, server) == null) return Value.NULL; - ServerPlayerEntity player = null; + ServerPlayer player = null; List args = Collections.emptyList(); if (lv.size() > 1) { @@ -1024,11 +1020,11 @@ public class Auxiliary { expression.addContextFunction("nbt_storage", -1, (c, t, lv) -> { if (lv.size() > 2) throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments."); CarpetContext cc = (CarpetContext) c; - DataCommandStorage storage = cc.s.getServer().getDataCommandStorage(); + CommandStorage storage = cc.s.getServer().getCommandStorage(); if (lv.size() == 0) - return ListValue.wrap(storage.getIds().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList())); + return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList())); String key = lv.get(0).getString(); - NbtCompound old_nbt = storage.get(InputValidator.identifierOf(key)); + CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key)); if (lv.size() == 2) { Value nbt = lv.get(1); NBTSerializableValue new_nbt = (nbt instanceof NBTSerializableValue) ? (NBTSerializableValue) nbt @@ -1044,7 +1040,7 @@ public class Auxiliary { String origName = lv.get(0).getString(); String name = InputValidator.validateSimpleString(origName, true); MinecraftServer server = cc.s.getServer(); - for (String dpName : server.getDataPackManager().getNames()) + for (String dpName : server.getPackRepository().getAvailableIds()) { if (dpName.equalsIgnoreCase("file/"+name+".zip") || dpName.equalsIgnoreCase("file/"+name)) @@ -1054,12 +1050,12 @@ public class Auxiliary { Value dpdata = lv.get(1); if (!(dpdata instanceof MapValue)) throw new InternalExpressionException("datapack data needs to be a valid map type"); - ResourcePackManager packManager = server.getDataPackManager(); - Path dbFloder = server.getSavePath(WorldSavePath.DATAPACKS); + PackRepository packManager = server.getPackRepository(); + Path dbFloder = server.getWorldPath(LevelResource.DATAPACK_DIR); Path packFloder = dbFloder.resolve(name+".zip"); if (Files.exists(packFloder) || Files.exists(dbFloder.resolve(name))) return Value.NULL; Boolean [] successful = new Boolean[]{true}; - server.submitAndJoin( () -> + server.executeBlocking( () -> { try { //Files.createDirectory(packFloder); @@ -1067,23 +1063,23 @@ public class Auxiliary { Path zipRoot = zipfs.getPath("/"); zipValueToJson(zipRoot.resolve("pack.mcmeta"), MapValue.wrap( Map.of(StringValue.of("pack"), MapValue.wrap(Map.of( - StringValue.of("pack_format"), new NumericValue(SharedConstants.getGameVersion().getPackVersion()), + StringValue.of("pack_format"), new NumericValue(SharedConstants.getCurrentVersion().getPackVersion()), StringValue.of("description"), StringValue.of(name), StringValue.of("source"), StringValue.of("scarpet") ))) )); walkTheDPMap((MapValue) dpdata, zipRoot); } - packManager.scanPacks(); - ResourcePackProfile resourcePackProfile = packManager.getProfile("file/" + name + ".zip"); - if (resourcePackProfile == null || packManager.getEnabledProfiles().contains(resourcePackProfile)) { + packManager.reload(); + Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip"); + if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) { throw new IOException(); } - List list = Lists.newArrayList(packManager.getEnabledProfiles()); - resourcePackProfile.getInitialPosition().insert(list, resourcePackProfile, p -> p, false); + List list = Lists.newArrayList(packManager.getSelectedPacks()); + resourcePackProfile.getDefaultPosition().insert(list, resourcePackProfile, p -> p, false); - server.reloadResources(list.stream().map(ResourcePackProfile::getName).collect(Collectors.toList())). + server.reloadResources(list.stream().map(Pack::getId).collect(Collectors.toList())). exceptionally(exc -> { successful[0] = false; return null; @@ -1109,44 +1105,44 @@ public class Auxiliary { CarpetContext cc = (CarpetContext)c; // from minecraft.server.Main.main MinecraftServer server = cc.s.getServer(); - LevelStorage.Session session = ((MinecraftServerInterface)server).getCMSession(); - DataPackSettings dataPackSettings = session.getDataPackSettings(); - ResourcePackManager resourcePackManager = server.getDataPackManager(); - DataPackSettings dataPackSettings2 = MinecraftServer.loadDataPacks(resourcePackManager, dataPackSettings == null ? DataPackSettings.SAFE_MODE : dataPackSettings, false); - ServerResourceManager serverRM = ((MinecraftServerInterface)server).getResourceManager(); - ReloadableResourceManagerImpl resourceManager = (ReloadableResourceManagerImpl) serverRM.getResourceManager(); + LevelStorageSource.LevelStorageAccess session = ((MinecraftServerInterface)server).getCMSession(); + DataPackConfig dataPackSettings = session.getDataPacks(); + PackRepository resourcePackManager = server.getPackRepository(); + DataPackConfig dataPackSettings2 = MinecraftServer.configurePackRepository(resourcePackManager, dataPackSettings == null ? DataPackConfig.DEFAULT : dataPackSettings, false); + ServerResources serverRM = ((MinecraftServerInterface)server).getResourceManager(); + SimpleReloadableResourceManager resourceManager = (SimpleReloadableResourceManager) serverRM.getResourceManager(); //believe the other one will fillup based on the datapacks only. resourceManager.close(); - resourcePackManager.createResourcePacks().forEach(resourceManager::addPack); + resourcePackManager.openAllSelected().forEach(resourceManager::add); //not sure its needed, but doesn't seem to have a negative effect and might be used in some custom shtuff - serverRM.loadRegistryTags(); + serverRM.updateGlobals(); - RegistryOps registryOps = RegistryOps.of(NbtOps.INSTANCE, serverRM.getResourceManager(), (DynamicRegistryManager.Impl) server.getRegistryManager()); - SaveProperties saveProperties = session.readLevelProperties(registryOps, dataPackSettings2); + RegistryReadOps registryOps = RegistryReadOps.create(NbtOps.INSTANCE, serverRM.getResourceManager(), (RegistryAccess.RegistryHolder) server.registryAccess()); + WorldData saveProperties = session.getDataTag(registryOps, dataPackSettings2); if (saveProperties == null) return Value.NULL; //session.backupLevelDataFile(server.getRegistryManager(), saveProperties); // no need // MinecraftServer.createWorlds // save properties should now contain dimension settings - GeneratorOptions generatorOptions = saveProperties.getGeneratorOptions(); - boolean bl = generatorOptions.isDebugWorld(); - long l = generatorOptions.getSeed(); - long m = BiomeAccess.hashSeed(l); - Map, ServerWorld> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds(); + WorldGenSettings generatorOptions = saveProperties.worldGenSettings(); + boolean bl = generatorOptions.isDebug(); + long l = generatorOptions.seed(); + long m = BiomeManager.obfuscateSeed(l); + Map, ServerLevel> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds(); List addeds = new ArrayList<>(); - for (Map.Entry, DimensionOptions> entry : generatorOptions.getDimensions().getEntries()) { - RegistryKey registryKey = entry.getKey(); + for (Map.Entry, LevelStem> entry : generatorOptions.dimensions().entrySet()) { + ResourceKey registryKey = entry.getKey(); if (!existing_worlds.containsKey(registryKey)) { - addeds.add(ValueConversions.of(registryKey.getValue())); - RegistryKey registryKey2 = RegistryKey.of(Registry.WORLD_KEY, registryKey.getValue()); - DimensionType dimensionType3 = entry.getValue().getDimensionType(); - ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator(); - UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM()); - ServerWorld serverWorld2 = new ServerWorld(server, Util.getMainWorkerExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false); - server.getOverworld().getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld2.getWorldBorder())); + addeds.add(ValueConversions.of(registryKey.location())); + ResourceKey registryKey2 = ResourceKey.create(Registry.DIMENSION_REGISTRY, registryKey.location()); + DimensionType dimensionType3 = entry.getValue().type(); + ChunkGenerator chunkGenerator3 = entry.getValue().generator(); + DerivedLevelData unmodifiableLevelProperties = new DerivedLevelData(saveProperties, ((ServerWorldInterface) server.overworld()).getWorldPropertiesCM()); + ServerLevel serverWorld2 = new ServerLevel(server, Util.backgroundExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false); + server.overworld().getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld2.getWorldBorder())); existing_worlds.put(registryKey2, serverWorld2); } } @@ -1240,14 +1236,14 @@ public class Auxiliary { NBTSerializableValue tagValue = (output instanceof NBTSerializableValue) ? (NBTSerializableValue) output : new NBTSerializableValue(output.getString()); - NbtElement tag = tagValue.getTag(); + Tag tag = tagValue.getTag(); Files.createDirectories(path.getParent()); try { - if (tag instanceof NbtCompound) - NbtIo.writeCompressed((NbtCompound) tag, Files.newOutputStream(path)); + if (tag instanceof CompoundTag) + NbtIo.writeCompressed((CompoundTag) tag, Files.newOutputStream(path)); } catch (Throwable shitHappened) { @@ -1282,11 +1278,11 @@ public class Auxiliary { } } - private static Stat getStat(StatType type, Identifier id) + private static Stat getStat(StatType type, ResourceLocation id) { T key = type.getRegistry().get(id); - if (key == null || !type.hasStat(key)) + if (key == null || !type.contains(key)) return null; - return type.getOrCreateStat(key); + return type.get(key); } } diff --git a/src/main/java/carpet/script/api/BlockIterators.java b/src/main/java/carpet/script/api/BlockIterators.java index 27c15452..05f09565 100644 --- a/src/main/java/carpet/script/api/BlockIterators.java +++ b/src/main/java/carpet/script/api/BlockIterators.java @@ -15,14 +15,13 @@ import carpet.script.value.LazyListValue; import carpet.script.value.ListValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3i; - import java.util.ArrayList; import java.util.List; import java.util.Locale; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Vec3i; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.Mth; import static java.lang.Math.abs; import static java.lang.Math.max; @@ -217,11 +216,11 @@ public class BlockIterators { expression.addContextFunction("neighbours", -1, (c, t, lv)-> { BlockPos center = BlockArgument.findIn((CarpetContext) c, lv,0).block.getPos(); - ServerWorld world = ((CarpetContext) c).s.getWorld(); + ServerLevel world = ((CarpetContext) c).s.getLevel(); List neighbours = new ArrayList<>(); - neighbours.add(new BlockValue(null, world, center.up())); - neighbours.add(new BlockValue(null, world, center.down())); + neighbours.add(new BlockValue(null, world, center.above())); + neighbours.add(new BlockValue(null, world, center.below())); neighbours.add(new BlockValue(null, world, center.north())); neighbours.add(new BlockValue(null, world, center.south())); neighbours.add(new BlockValue(null, world, center.east())); @@ -245,30 +244,30 @@ public class BlockIterators { Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset); if (diffLocator.fromBlock) { - sminx = MathHelper.floor(abs(diffLocator.vec.x - cx)); - sminy = MathHelper.floor(abs(diffLocator.vec.y - cx)); - sminz = MathHelper.floor(abs(diffLocator.vec.z - cx)); + sminx = Mth.floor(abs(diffLocator.vec.x - cx)); + sminy = Mth.floor(abs(diffLocator.vec.y - cx)); + sminz = Mth.floor(abs(diffLocator.vec.z - cx)); } else { - sminx = MathHelper.floor(abs(diffLocator.vec.x)); - sminy = MathHelper.floor(abs(diffLocator.vec.y)); - sminz = MathHelper.floor(abs(diffLocator.vec.z)); + sminx = Mth.floor(abs(diffLocator.vec.x)); + sminy = Mth.floor(abs(diffLocator.vec.y)); + sminz = Mth.floor(abs(diffLocator.vec.z)); } if (lv.size() > diffLocator.offset) { Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset); if (posDiff.fromBlock) { - smaxx = MathHelper.floor(abs(posDiff.vec.x - cx)); - smaxy = MathHelper.floor(abs(posDiff.vec.y - cx)); - smaxz = MathHelper.floor(abs(posDiff.vec.z - cx)); + smaxx = Mth.floor(abs(posDiff.vec.x - cx)); + smaxy = Mth.floor(abs(posDiff.vec.y - cx)); + smaxz = Mth.floor(abs(posDiff.vec.z - cx)); } else { - smaxx = MathHelper.floor(abs(posDiff.vec.x)); - smaxy = MathHelper.floor(abs(posDiff.vec.y)); - smaxz = MathHelper.floor(abs(posDiff.vec.z)); + smaxx = Mth.floor(abs(posDiff.vec.x)); + smaxy = Mth.floor(abs(posDiff.vec.y)); + smaxz = Mth.floor(abs(posDiff.vec.z)); } } else diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index 4ad079ac..7131c99f 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -15,21 +15,6 @@ import carpet.script.value.NumericValue; import carpet.script.value.Value; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; - import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -39,11 +24,25 @@ import java.util.Set; import java.util.UUID; import java.util.function.Predicate; import java.util.stream.Collectors; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySelector; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; public class Entities { - private static ListValue getPlayersFromWorldMatching(Context c, Predicate condition) { + private static ListValue getPlayersFromWorldMatching(Context c, Predicate condition) { List ret = new ArrayList<>(); - for (ServerPlayerEntity player: ((CarpetContext) c).s.getWorld().getPlayers()) { + for (ServerPlayer player: ((CarpetContext) c).s.getLevel().players()) { if (condition.test(player)) { ret.add(new EntityValue(player)); } @@ -60,30 +59,30 @@ public class Entities { CarpetContext cc = (CarpetContext)c; if (cc.host.user != null) { - ServerPlayerEntity player = cc.s.getServer().getPlayerManager().getPlayer(cc.host.user); + ServerPlayer player = cc.s.getServer().getPlayerList().getPlayerByName(cc.host.user); return EntityValue.of(player); } Entity callingEntity = cc.s.getEntity(); - if (callingEntity instanceof PlayerEntity) return EntityValue.of(callingEntity); - Vec3d pos = ((CarpetContext)c).s.getPosition(); - PlayerEntity closestPlayer = ((CarpetContext)c).s.getWorld().getClosestPlayer(pos.x, pos.y, pos.z, -1.0, EntityPredicates.VALID_ENTITY); + if (callingEntity instanceof Player) return EntityValue.of(callingEntity); + Vec3 pos = ((CarpetContext)c).s.getPosition(); + Player closestPlayer = ((CarpetContext)c).s.getLevel().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE); return EntityValue.of(closestPlayer); } String playerName = lv.get(0).getString(); return switch (playerName) { case "all" -> { List ret = new ArrayList<>(); - for (ServerPlayerEntity player: ((CarpetContext)c).s.getServer().getPlayerManager().getPlayerList()) + for (ServerPlayer player: ((CarpetContext)c).s.getServer().getPlayerList().getPlayers()) ret.add(new EntityValue(player)); yield ListValue.wrap(ret); } case "*" -> getPlayersFromWorldMatching(c, p -> true); - case "survival" -> getPlayersFromWorldMatching(c, p -> p.interactionManager.isSurvivalLike()); - case "creative" -> getPlayersFromWorldMatching(c, PlayerEntity::isCreative); - case "spectating" -> getPlayersFromWorldMatching(c, PlayerEntity::isSpectator); + case "survival" -> getPlayersFromWorldMatching(c, p -> p.gameMode.isSurvival()); // todo assert correct + case "creative" -> getPlayersFromWorldMatching(c, ServerPlayer::isCreative); + case "spectating" -> getPlayersFromWorldMatching(c, ServerPlayer::isSpectator); case "!spectating" -> getPlayersFromWorldMatching(c, p -> !p.isSpectator()); default -> { - ServerPlayerEntity player = ((CarpetContext) c).s.getServer().getPlayerManager().getPlayer(playerName); + ServerPlayer player = ((CarpetContext) c).s.getServer().getPlayerList().getPlayerByName(playerName); if (player != null) { yield new EntityValue(player); } @@ -98,12 +97,12 @@ public class Entities { if (lv.size() < 2) throw new InternalExpressionException("'spawn' function takes mob name, and position to spawn"); String entityString = lv.get(0).getString(); - Identifier entityId; + ResourceLocation entityId; try { - entityId = Identifier.fromCommandInput(new StringReader(entityString)); - EntityType type = Registry.ENTITY_TYPE.getOrEmpty(entityId).orElse(null); - if (type == null || !type.isSummonable()) + entityId = ResourceLocation.read(new StringReader(entityString)); + EntityType type = Registry.ENTITY_TYPE.getOptional(entityId).orElse(null); + if (type == null || !type.canSummon()) return Value.NULL; } catch (CommandSyntaxException exception) @@ -114,7 +113,7 @@ public class Entities { Vector3Argument position = Vector3Argument.findIn(lv, 1); if (position.fromBlock) position.vec = position.vec.subtract(0, 0.5, 0); - NbtCompound tag = new NbtCompound(); + CompoundTag tag = new CompoundTag(); boolean hasTag = false; if (lv.size() > position.offset) { @@ -126,18 +125,18 @@ public class Entities { } tag.putString("id", entityId.toString()); - Vec3d vec3d = position.vec; + Vec3 vec3d = position.vec; - ServerWorld serverWorld = cc.s.getWorld(); - Entity entity_1 = EntityType.loadEntityWithPassengers(tag, serverWorld, (entity_1x) -> { - entity_1x.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYaw(), entity_1x.getPitch()); - return !serverWorld.tryLoadEntity(entity_1x) ? null : entity_1x; + ServerLevel serverWorld = cc.s.getLevel(); + Entity entity_1 = EntityType.loadEntityRecursive(tag, serverWorld, (entity_1x) -> { + entity_1x.moveTo(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYRot(), entity_1x.getXRot()); + return !serverWorld.addWithUUID(entity_1x) ? null : entity_1x; }); if (entity_1 == null) { return Value.NULL; } else { - if (!hasTag && entity_1 instanceof MobEntity) { - ((MobEntity)entity_1).initialize(serverWorld, serverWorld.getLocalDifficulty(entity_1.getBlockPos()), SpawnReason.COMMAND, null, null); + if (!hasTag && entity_1 instanceof Mob) { + ((Mob)entity_1).finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(entity_1.blockPosition()), MobSpawnType.COMMAND, null, null); } return new EntityValue(entity_1); } @@ -147,16 +146,16 @@ public class Entities { { Value who = lv.get(0); if (who instanceof NumericValue) - return EntityValue.of(((CarpetContext)c).s.getWorld().getEntityById((int)((NumericValue) who).getLong())); - return EntityValue.of(((CarpetContext)c).s.getWorld().getEntity(UUID.fromString(who.getString()))); + return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity((int)((NumericValue) who).getLong())); + return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity(UUID.fromString(who.getString()))); }); expression.addContextFunction("entity_list", 1, (c, t, lv) -> { String who = lv.get(0).getString(); - ServerCommandSource source = ((CarpetContext)c).s; + CommandSourceStack source = ((CarpetContext)c).s; EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); - List entityList = source.getWorld().getEntitiesByType(eDesc.directType, eDesc.filteringPredicate); + List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); }); @@ -167,24 +166,24 @@ public class Entities { CarpetContext cc = (CarpetContext)c; Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true); - Box centerBox; + AABB centerBox; if (centerLocator.entity != null) { centerBox = centerLocator.entity.getBoundingBox(); } else { - Vec3d center = centerLocator.vec; + Vec3 center = centerLocator.vec; if (centerLocator.fromBlock) center.add(0.5, 0.5, 0.5); - centerBox = new Box(center, center); + centerBox = new AABB(center, center); } Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); if (rangeLocator.fromBlock) throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument"); - Vec3d range = rangeLocator.vec; - Box area = centerBox.expand(range.x, range.y, range.z); + Vec3 range = rangeLocator.vec; + AABB area = centerBox.inflate(range.x, range.y, range.z); EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getServer()); - List entityList = cc.s.getWorld().getEntitiesByType(eDesc.directType, area,eDesc.filteringPredicate); + List entityList = cc.s.getLevel().getEntities(eDesc.directType, area,eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); }); diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index cfe700cd..91d029e6 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -23,70 +23,69 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; import com.google.common.collect.Sets; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.ItemStackArgument; -import net.minecraft.entity.ItemEntity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.packet.s2c.play.ScreenHandlerSlotUpdateS2CPacket; -import net.minecraft.recipe.AbstractCookingRecipe; -import net.minecraft.recipe.CuttingRecipe; -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeType; -import net.minecraft.recipe.ShapedRecipe; -import net.minecraft.recipe.ShapelessRecipe; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.tag.TagManager; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; - import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; +import net.minecraft.commands.arguments.item.ItemInput; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.TagContainer; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.AbstractCookingRecipe; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.item.crafting.ShapelessRecipe; +import net.minecraft.world.item.crafting.SingleItemRecipe; +import net.minecraft.world.phys.Vec3; public class Inventories { public static void apply(Expression expression) { expression.addUnaryFunction("stack_limit", v -> - new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxCount())); + new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxStackSize())); expression.addUnaryFunction("item_category", v -> { - ItemStackArgument item = NBTSerializableValue.parseItem(v.getString()); - ItemGroup ig = item.getItem().getGroup(); - return (ig==null)?Value.NULL:new StringValue(ig.getName()); + ItemInput item = NBTSerializableValue.parseItem(v.getString()); + CreativeModeTab ig = item.getItem().getItemCategory(); + return (ig==null)?Value.NULL:new StringValue(ig.getRecipeFolderName()); }); expression.addContextFunction("item_list", -1, (c, t, lv) -> { if (lv.size() == 0) - return ListValue.wrap(Registry.ITEM.getIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(Registry.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getServer().getTagManager(); + TagContainer tagManager = cc.s.getServer().getTags(); String tag = lv.get(0).getString(); - net.minecraft.tag.Tag itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag)); + net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag)); if (itemTag == null) return Value.NULL; - return ListValue.wrap(itemTag.values().stream().map(b -> ValueConversions.of(Registry.ITEM.getId(b))).collect(Collectors.toList())); + return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b))).collect(Collectors.toList())); }); expression.addContextFunction("item_tags", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getServer().getTagManager(); + TagContainer tagManager = cc.s.getServer().getTags(); if (lv.size() == 0) - return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList())); Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem(); if (lv.size() == 1) - return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); String tag = lv.get(1).getString(); - net.minecraft.tag.Tag itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag)); + net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag)); if (itemTag == null) return Value.NULL; return BooleanValue.of(itemTag.contains(item)); }); @@ -109,7 +108,7 @@ public class Inventories { List recipesOutput = new ArrayList<>(); for (Recipe recipe: recipes) { - ItemStack result = recipe.getOutput(); + ItemStack result = recipe.getResultItem(); List ingredientValue = new ArrayList<>(); recipe.getIngredients().forEach( ingredient -> @@ -147,15 +146,15 @@ public class Inventories { { recipeSpec = ListValue.of( new StringValue("smelting"), - new NumericValue(((AbstractCookingRecipe) recipe).getCookTime()), + new NumericValue(((AbstractCookingRecipe) recipe).getCookingTime()), new NumericValue(((AbstractCookingRecipe) recipe).getExperience()) ); } - else if (recipe instanceof CuttingRecipe) + else if (recipe instanceof SingleItemRecipe) { recipeSpec = ListValue.of(new StringValue("cutting")); } - else if (recipe instanceof SpecialCraftingRecipe) + else if (recipe instanceof CustomRecipe) { recipeSpec = ListValue.of(new StringValue("special")); } @@ -173,10 +172,10 @@ public class Inventories { { String itemStr = v.getString(); Item item; - Identifier id = InputValidator.identifierOf(itemStr); - item = Registry.ITEM.getOrEmpty(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); - if (!item.hasRecipeRemainder()) return Value.NULL; - return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getId(item.getRecipeRemainder()))); + ResourceLocation id = InputValidator.identifierOf(itemStr); + item = Registry.ITEM.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); + if (!item.hasCraftingRemainingItem()) return Value.NULL; + return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getKey(item.getCraftingRemainingItem()))); }); expression.addContextFunction("inventory_size", -1, (c, t, lv) -> @@ -184,7 +183,7 @@ public class Inventories { CarpetContext cc = (CarpetContext) c; NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) return Value.NULL; - return new NumericValue(inventoryLocator.inventory().size()); + return new NumericValue(inventoryLocator.inventory().getContainerSize()); }); expression.addContextFunction("inventory_has_items", -1, (c, t, lv) -> @@ -204,14 +203,14 @@ public class Inventories { if (lv.size() == inventoryLocator.offset()) { List fullInventory = new ArrayList<>(); - for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++) - fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getStack(i))); + for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) + fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i))); return ListValue.wrap(fullInventory); } int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().size()) return Value.NULL; - return ValueConversions.of(inventoryLocator.inventory().getStack(slot)); + if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; + return ValueConversions.of(inventoryLocator.inventory().getItem(slot)); }); //inventory_set(, , , , ) @@ -224,26 +223,26 @@ public class Inventories { throw new InternalExpressionException("'inventory_set' requires at least slot number and new stack size, and optional new item"); int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+0)).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().size()) return Value.NULL; + if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); if (count == 0) { // clear slot - ItemStack removedStack = inventoryLocator.inventory().removeStack(slot); + ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); syncPlayerInventory(inventoryLocator, slot); //Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares return ValueConversions.of(removedStack); } if (lv.size() < inventoryLocator.offset()+3) { - ItemStack previousStack = inventoryLocator.inventory().getStack(slot); + ItemStack previousStack = inventoryLocator.inventory().getItem(slot); ItemStack newStack = previousStack.copy(); newStack.setCount(count); - inventoryLocator.inventory().setStack(slot, newStack); + inventoryLocator.inventory().setItem(slot, newStack); syncPlayerInventory(inventoryLocator, slot); return ValueConversions.of(previousStack); } - NbtCompound nbt = null; // skipping one argument + CompoundTag nbt = null; // skipping one argument if (lv.size() > inventoryLocator.offset()+3) { Value nbtValue = lv.get(inventoryLocator.offset()+3); @@ -254,11 +253,11 @@ public class Inventories { else nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag(); } - ItemStackArgument newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt); - ItemStack previousStack = inventoryLocator.inventory().getStack(slot); + ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt); + ItemStack previousStack = inventoryLocator.inventory().getItem(slot); try { - inventoryLocator.inventory().setStack(slot, newitem.createStack(count, false)); + inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false)); syncPlayerInventory(inventoryLocator, slot); } catch (CommandSyntaxException e) @@ -274,7 +273,7 @@ public class Inventories { CarpetContext cc = (CarpetContext) c; NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) return Value.NULL; - ItemStackArgument itemArg = null; + ItemInput itemArg = null; if (lv.size() > inventoryLocator.offset()) { Value secondArg = lv.get(inventoryLocator.offset()+0); @@ -287,9 +286,9 @@ public class Inventories { startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); } startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory()); - for (int i = startIndex, maxi = inventoryLocator.inventory().size(); i < maxi; i++) + for (int i = startIndex, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - ItemStack stack = inventoryLocator.inventory().getStack(i); + ItemStack stack = inventoryLocator.inventory().getItem(i); if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) ) return new NumericValue(i); } @@ -304,16 +303,16 @@ public class Inventories { if (inventoryLocator == null) return Value.NULL; if (lv.size() <= inventoryLocator.offset()) throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed"); - ItemStackArgument searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString()); + ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString()); int amount = 1; if (lv.size() > inventoryLocator.offset()+1) amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); // not enough - if (((amount == 1) && (!inventoryLocator.inventory().containsAny(Sets.newHashSet(searchItem.getItem())))) - || (inventoryLocator.inventory().count(searchItem.getItem()) < amount)) return Value.FALSE; - for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++) + if (((amount == 1) && (!inventoryLocator.inventory().hasAnyOf(Sets.newHashSet(searchItem.getItem())))) + || (inventoryLocator.inventory().countItem(searchItem.getItem()) < amount)) return Value.FALSE; + for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - ItemStack stack = inventoryLocator.inventory().getStack(i); + ItemStack stack = inventoryLocator.inventory().getItem(i); if (stack.isEmpty()) continue; if (!stack.getItem().equals(searchItem.getItem())) @@ -322,13 +321,13 @@ public class Inventories { if (left > 0) { stack.setCount(left); - inventoryLocator.inventory().setStack(i, stack); + inventoryLocator.inventory().setItem(i, stack); syncPlayerInventory(inventoryLocator, i); return Value.TRUE; } else { - inventoryLocator.inventory().removeStack(i); + inventoryLocator.inventory().removeItemNoUpdate(i); syncPlayerInventory(inventoryLocator, i); amount -= stack.getCount(); } @@ -348,51 +347,51 @@ public class Inventories { throw new InternalExpressionException("Slot number is required for inventory_drop"); int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().size()) return Value.NULL; + if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; int amount = 0; if (lv.size() > inventoryLocator.offset()+1) amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); if (amount < 0) throw new InternalExpressionException("Cannot throw negative number of items"); - ItemStack stack = inventoryLocator.inventory().getStack(slot); + ItemStack stack = inventoryLocator.inventory().getItem(slot); if (stack == null || stack.isEmpty()) return Value.ZERO; if (amount == 0) amount = stack.getCount(); - ItemStack droppedStack = inventoryLocator.inventory().removeStack(slot, amount); + ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount); if (droppedStack.isEmpty()) return Value.ZERO; Object owner = inventoryLocator.owner(); ItemEntity item; - if (owner instanceof PlayerEntity) + if (owner instanceof Player) { - item = ((PlayerEntity) owner).dropItem(droppedStack, false, true); + item = ((Player) owner).drop(droppedStack, false, true); } else if (owner instanceof LivingEntity villager) { // stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner); - double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getStandingEyeHeight(); - item = new ItemEntity(villager.world, villager.getX(), double_1, villager.getZ(), droppedStack); - Vec3d vec3d_1 = villager.getRotationVec(1.0F).normalize().multiply(0.3);// new Vec3d(0, 0.3, 0); - item.setVelocity(vec3d_1); - item.setToDefaultPickupDelay(); - cc.s.getWorld().spawnEntity(item); + double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getEyeHeight(); + item = new ItemEntity(villager.level, villager.getX(), double_1, villager.getZ(), droppedStack); + Vec3 vec3d_1 = villager.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0); + item.setDeltaMovement(vec3d_1); + item.setDefaultPickUpDelay(); + cc.s.getLevel().addFreshEntity(item); } else { - Vec3d point = Vec3d.ofCenter(inventoryLocator.position()); //pos+0.5v - item = new ItemEntity(cc.s.getWorld(), point.x, point.y, point.z, droppedStack); - item.setToDefaultPickupDelay(); - cc.s.getWorld().spawnEntity(item); + Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v + item = new ItemEntity(cc.s.getLevel(), point.x, point.y, point.z, droppedStack); + item.setDefaultPickUpDelay(); + cc.s.getLevel().addFreshEntity(item); } - return new NumericValue(item.getStack().getCount()); + return new NumericValue(item.getItem().getCount()); }); expression.addContextFunction("create_screen",-1, (c, t, lv) -> { if(lv.size() < 3) throw new InternalExpressionException("'create_screen' requires at least three arguments"); Value playerValue = lv.get(0); - ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue); if(player == null) throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument."); String type = lv.get(1).getString(); - Text name = FormattedTextValue.getTextByValue(lv.get(2)); + Component name = FormattedTextValue.getTextByValue(lv.get(2)); FunctionValue function = null; if(lv.size() > 3) function = FunctionArgument.findIn(c, expression.module, lv, 3, true, false).function; @@ -427,12 +426,12 @@ public class Inventories { private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1) { - if (inventory.owner() instanceof ServerPlayerEntity player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) + if (inventory.owner() instanceof ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) { - player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket( + player.connection.send(new ClientboundContainerSetSlotPacket( -2, 0, // resolve mystery argument int_1, - inventory.inventory().getStack(int_1) + inventory.inventory().getItem(int_1) )); } } diff --git a/src/main/java/carpet/script/api/Monitoring.java b/src/main/java/carpet/script/api/Monitoring.java index becfe31e..0778620c 100644 --- a/src/main/java/carpet/script/api/Monitoring.java +++ b/src/main/java/carpet/script/api/Monitoring.java @@ -12,13 +12,12 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.utils.SpawnReporter; import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.world.SpawnHelper; - import java.util.HashMap; import java.util.Locale; import java.util.Map; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.NaturalSpawner; public class Monitoring { @@ -42,19 +41,19 @@ public class Monitoring { expression.addContextFunction("get_mob_counts", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); - SpawnHelper.Info info = world.getChunkManager().getSpawnInfo(); + ServerLevel world = cc.s.getLevel(); + NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); if (info == null) return Value.NULL; - Object2IntMap mobcounts = info.getGroupToCount(); + Object2IntMap mobcounts = info.getMobCategoryCounts(); int chunks = ((SpawnHelperInnerInterface)info).cmGetChunkCount(); if (lv.size() == 0) { Map retDict = new HashMap<>(); - for (SpawnGroup category: mobcounts.keySet()) + for (MobCategory category: mobcounts.keySet()) { - int currentCap = (int)(category.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER); + int currentCap = (int)(category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER); retDict.put( - new StringValue(category.asString().toLowerCase(Locale.ROOT)), + new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)), ListValue.of( new NumericValue(mobcounts.getInt(category)), new NumericValue(currentCap)) @@ -63,11 +62,11 @@ public class Monitoring { return MapValue.wrap(retDict); } String catString = lv.get(0).getString(); - SpawnGroup cat = SpawnGroup.byName(catString.toLowerCase(Locale.ROOT)); + MobCategory cat = MobCategory.byName(catString.toLowerCase(Locale.ROOT)); if (cat == null) throw new InternalExpressionException("Unreconized mob category: "+catString); return ListValue.of( new NumericValue(mobcounts.getInt(cat)), - new NumericValue((int)(cat.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER)) + new NumericValue((int)(cat.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER)) ); }); } diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index 435736ba..9d9029db 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -19,28 +19,26 @@ import carpet.script.value.StringValue; import carpet.script.value.FormattedTextValue; import carpet.script.value.Value; import com.google.common.collect.Lists; -import net.minecraft.entity.Entity; -import net.minecraft.entity.boss.BossBar; -import net.minecraft.entity.boss.BossBarManager; -import net.minecraft.entity.boss.CommandBossBar; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.scoreboard.ServerScoreboard; -import net.minecraft.scoreboard.ScoreboardCriterion; -import net.minecraft.scoreboard.ScoreboardObjective; -import net.minecraft.scoreboard.ScoreboardPlayerScore; -import net.minecraft.scoreboard.Team; -import net.minecraft.scoreboard.AbstractTeam; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.ServerScoreboard; +import net.minecraft.server.bossevents.CustomBossEvent; +import net.minecraft.server.bossevents.CustomBossEvents; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.BossEvent; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.PlayerTeam; +import net.minecraft.world.scores.Score; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.Team; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; public class Scoreboards { private static String getScoreboardKeyFromValue(Value keyValue) @@ -48,13 +46,13 @@ public class Scoreboards { if (keyValue instanceof EntityValue) { Entity e = ((EntityValue) keyValue).getEntity(); - if (e instanceof PlayerEntity) + if (e instanceof Player) { return e.getName().getString(); } else { - return e.getUuidAsString(); + return e.getStringUUID(); } } else @@ -74,25 +72,25 @@ public class Scoreboards { if (lv.size()==0) return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList())); String objectiveName = lv.get(0).getString(); - ScoreboardObjective objective = scoreboard.getObjective(objectiveName); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective == null) return Value.NULL; if (lv.size()==1) - return ListValue.wrap(scoreboard.getAllPlayerScores(objective).stream().map(s -> new StringValue(s.getPlayerName())).collect(Collectors.toList())); + return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner())).collect(Collectors.toList())); String key = getScoreboardKeyFromValue(lv.get(1)); if(lv.size()==2) { - if(!scoreboard.playerHasObjective(key, objective)) return Value.NULL; - return NumericValue.of(scoreboard.getPlayerScore(key,objective).getScore()); + if(!scoreboard.hasPlayerScore(key, objective)) return Value.NULL; + return NumericValue.of(scoreboard.getOrCreatePlayerScore(key,objective).getScore()); } Value value = lv.get(2); if(value.isNull()) { - ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective); + Score score = scoreboard.getOrCreatePlayerScore(key, objective); scoreboard.resetPlayerScore(key,objective); return NumericValue.of(score.getScore()); } if (value instanceof NumericValue) { - ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective); + Score score = scoreboard.getOrCreatePlayerScore(key, objective); score.setScore(NumericValue.asNumber(value).getInt()); return NumericValue.of(score.getScore()); } @@ -105,7 +103,7 @@ public class Scoreboards { CarpetContext cc = (CarpetContext)c; Scoreboard scoreboard = cc.s.getServer().getScoreboard(); String objectiveName = lv.get(0).getString(); - ScoreboardObjective objective = scoreboard.getObjective(objectiveName); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective == null) return Value.FALSE; if (lv.size() == 1) { @@ -113,8 +111,8 @@ public class Scoreboards { return Value.TRUE; } String key = getScoreboardKeyFromValue(lv.get(1)); - if (!scoreboard.playerHasObjective(key, objective)) return Value.NULL; - ScoreboardPlayerScore scoreboardPlayerScore = scoreboard.getPlayerScore(key, objective); + if (!scoreboard.hasPlayerScore(key, objective)) return Value.NULL; + Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective); Value previous = new NumericValue(scoreboardPlayerScore.getScore()); scoreboard.resetPlayerScore(key, objective); return previous; @@ -129,34 +127,34 @@ public class Scoreboards { Scoreboard scoreboard = cc.s.getServer().getScoreboard(); if (lv.size() == 0 || lv.size()>2) throw new InternalExpressionException("'scoreboard_add' should have one or two parameters"); String objectiveName = lv.get(0).getString(); - ScoreboardCriterion criterion; + ObjectiveCriteria criterion; if (lv.size() == 1 ) { - criterion = ScoreboardCriterion.DUMMY; + criterion = ObjectiveCriteria.DUMMY; } else { String critetionName = lv.get(1).getString(); - criterion = ScoreboardCriterion.getOrCreateStatCriterion(critetionName).orElse(null); + criterion = ObjectiveCriteria.byName(critetionName).orElse(null); if (criterion==null) { throw new ThrowStatement(critetionName, Throwables.UNKNOWN_CRITERION); } } - ScoreboardObjective objective = scoreboard.getObjective(objectiveName); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective != null) { c.host.issueDeprecation("reading or modifying an objective's criterion with scoreboard_add"); - if(lv.size() == 1) return StringValue.of(objective.getCriterion().getName()); - if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.NULL; - ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective); + if(lv.size() == 1) return StringValue.of(objective.getCriteria().getName()); + if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.NULL; + ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); ((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion); (((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); - scoreboard.updateObjective(objective); + scoreboard.onObjectiveAdded(objective); return Value.FALSE; } - scoreboard.addObjective(objectiveName, criterion, new LiteralText(objectiveName), criterion.getDefaultRenderType()); + scoreboard.addObjective(objectiveName, criterion, new TextComponent(objectiveName), criterion.getDefaultRenderType()); return Value.TRUE; }); @@ -165,7 +163,7 @@ public class Scoreboards { if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); CarpetContext cc = (CarpetContext)c; Scoreboard scoreboard = cc.s.getServer().getScoreboard(); - ScoreboardObjective objective = scoreboard.getObjective(lv.get(0).getString()); + Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); if(objective == null) return Value.NULL; boolean modify = lv.size() > 2; @@ -177,37 +175,37 @@ public class Scoreboards { switch (property) { case "criterion": if(modify) { - ScoreboardCriterion criterion = ScoreboardCriterion.getOrCreateStatCriterion(setValue.getString()).orElse(null); + ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null); if (criterion==null) throw new InternalExpressionException("Unknown scoreboard criterion: "+ setValue.getString()); - if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.FALSE; - ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective); + if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.FALSE; + ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); ((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion); (((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); - scoreboard.updateObjective(objective); + scoreboard.onObjectiveAdded(objective); return Value.TRUE; } - return StringValue.of(objective.getCriterion().getName()); + return StringValue.of(objective.getCriteria().getName()); case "display_name": if(modify) { - Text text = FormattedTextValue.getTextByValue(setValue); + Component text = FormattedTextValue.getTextByValue(setValue); objective.setDisplayName(text); return Value.TRUE; } return new FormattedTextValue(objective.getDisplayName()); case "display_slot": if(modify) { - int slotId = Scoreboard.getDisplaySlotId(setValue.getString()); + int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); if(slotId == -1) throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString()); - if(objective.equals(scoreboard.getObjectiveForSlot(slotId))) { + if(objective.equals(scoreboard.getDisplayObjective(slotId))) { return Value.FALSE; } - scoreboard.setObjectiveSlot(slotId,objective); + scoreboard.setDisplayObjective(slotId,objective); return Value.TRUE; } List slots = new ArrayList<>(); for(int i = 0; i < 19; i++) { - if (scoreboard.getObjectiveForSlot(i) == objective) { + if (scoreboard.getDisplayObjective(i) == objective) { String slotName = Scoreboard.getDisplaySlotName(i); slots.add(StringValue.of(slotName)); } @@ -215,12 +213,12 @@ public class Scoreboards { return ListValue.wrap(slots); case "render_type": if(modify) { - ScoreboardCriterion.RenderType renderType = ScoreboardCriterion.RenderType.getType(setValue.getString().toLowerCase()); + ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase()); if(objective.getRenderType().equals(renderType)) return Value.FALSE; objective.setRenderType(renderType); return Value.TRUE; } - return StringValue.of(objective.getRenderType().getName()); + return StringValue.of(objective.getRenderType().getId()); default: throw new InternalExpressionException("scoreboard property '" + property + "' is not a valid property"); } @@ -231,18 +229,18 @@ public class Scoreboards { CarpetContext cc = (CarpetContext)c; Scoreboard scoreboard = cc.s.getServer().getScoreboard(); String location = lv.get(0).getString(); - int slot = Scoreboard.getDisplaySlotId(location); + int slot = Scoreboard.getDisplaySlotByName(location); if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location); Value target = lv.get(1); if (target instanceof NullValue) { - scoreboard.setObjectiveSlot(slot, null); + scoreboard.setDisplayObjective(slot, null); return new NumericValue(slot); } String objectiveString = target.getString(); - ScoreboardObjective objective = scoreboard.getObjective(objectiveString); + Objective objective = scoreboard.getOrCreateObjective(objectiveString); if (objective == null) return Value.NULL; - scoreboard.setObjectiveSlot(slot, objective); + scoreboard.setDisplayObjective(slot, objective); return new NumericValue(slot); }); @@ -254,9 +252,9 @@ public class Scoreboards { if(lv.size() == 0) return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList())); if (lv.size() != 1) return Value.NULL; - Team team = scoreboard.getTeam(lv.get(0).getString()); + PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString()); if(team == null) return Value.NULL; - return ListValue.wrap(team.getPlayerList().stream().map(StringValue::of).collect(Collectors.toList())); + return ListValue.wrap(team.getPlayers().stream().map(StringValue::of).collect(Collectors.toList())); }); @@ -270,18 +268,18 @@ public class Scoreboards { if(lv.size() == 1) { - if (scoreboard.getTeam(teamName) != null) return Value.NULL; - scoreboard.addTeam(teamName); + if (scoreboard.getPlayerTeam(teamName) != null) return Value.NULL; + scoreboard.addPlayerTeam(teamName); return new StringValue(teamName); } if(lv.size() != 2) return Value.NULL; Value playerVal = lv.get(1); String player = EntityValue.getPlayerNameByValue(playerVal); if(player == null) return Value.NULL; - Team team = scoreboard.getTeam(teamName); + PlayerTeam team = scoreboard.getPlayerTeam(teamName); if(team == null) return Value.NULL; - if(team.isEqual(scoreboard.getPlayerTeam(player))) return Value.FALSE; - scoreboard.addPlayerToTeam(player,scoreboard.getTeam(teamName)); + if(team.isAlliedTo(scoreboard.getPlayersTeam(player))) return Value.FALSE; + scoreboard.addPlayerToTeam(player,scoreboard.getPlayerTeam(teamName)); return Value.TRUE; }); @@ -291,8 +289,8 @@ public class Scoreboards { ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); Value teamVal = lv.get(0); String team = teamVal.getString(); - if(scoreboard.getTeam(team) == null) return Value.NULL; - scoreboard.removeTeam(scoreboard.getTeam(team)); + if(scoreboard.getPlayerTeam(team) == null) return Value.NULL; + scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(team)); return Value.TRUE; }); @@ -304,7 +302,7 @@ public class Scoreboards { Value playerVal = lv.get(0); String player = EntityValue.getPlayerNameByValue(playerVal); if(player == null) return Value.NULL; - return BooleanValue.of(scoreboard.clearPlayerTeam(player)); + return BooleanValue.of(scoreboard.removePlayerFromTeam(player)); }); expression.addContextFunction("team_property", -1, (c, t, lv) -> @@ -325,7 +323,7 @@ public class Scoreboards { settingVal = lv.get(2); } - Team team = scoreboard.getTeam(teamVal.getString()); + PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString()); if(team == null) return Value.NULL; if(!(propertyVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the second argument"); @@ -334,64 +332,64 @@ public class Scoreboards { case "collisionRule": if(!modifying) return new StringValue(team.getCollisionRule().name); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - AbstractTeam.CollisionRule collisionRule = AbstractTeam.CollisionRule.getRule(settingVal.getString()); + Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString()); if(collisionRule == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); team.setCollisionRule(collisionRule); break; case "color": if(!modifying) return new StringValue(((Team_scarpetMixin) team).getColor().getName()); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - Formatting color = Formatting.byName(settingVal.getString().toUpperCase()); + ChatFormatting color = ChatFormatting.getByName(settingVal.getString().toUpperCase()); if(color == null || !color.isColor()) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); team.setColor(color); break; case "deathMessageVisibility": - if(!modifying) return new StringValue(team.getDeathMessageVisibilityRule().name); + if(!modifying) return new StringValue(team.getDeathMessageVisibility().name); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - AbstractTeam.VisibilityRule deathMessageVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString()); + Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString()); if(deathMessageVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); - team.setDeathMessageVisibilityRule(deathMessageVisibility); + team.setDeathMessageVisibility(deathMessageVisibility); break; case "displayName": if(!modifying) return new FormattedTextValue(team.getDisplayName()); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString()); - Text displayName; + Component displayName; displayName = FormattedTextValue.getTextByValue(settingVal); team.setDisplayName(displayName); break; case "friendlyFire": - if(!modifying) return BooleanValue.of(team.isFriendlyFireAllowed()); + if(!modifying) return BooleanValue.of(team.isAllowFriendlyFire()); if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString()); boolean friendlyFire = settingVal.getBoolean(); - team.setFriendlyFireAllowed(friendlyFire); + team.setAllowFriendlyFire(friendlyFire); break; case "nametagVisibility": - if(!modifying) return new StringValue(team.getNameTagVisibilityRule().name); + if(!modifying) return new StringValue(team.getNameTagVisibility().name); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - AbstractTeam.VisibilityRule nametagVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString()); + Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString()); if(nametagVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); - team.setNameTagVisibilityRule(nametagVisibility); + team.setNameTagVisibility(nametagVisibility); break; case "prefix": - if(!modifying) return new FormattedTextValue(team.getPrefix()); + if(!modifying) return new FormattedTextValue(team.getPlayerPrefix()); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property ' requires a string or formatted text as the third argument for the property " + propertyVal.getString()); - Text prefix; + Component prefix; prefix = FormattedTextValue.getTextByValue(settingVal); - team.setPrefix(prefix); + team.setPlayerPrefix(prefix); break; case "seeFriendlyInvisibles": - if(!modifying) return BooleanValue.of(team.shouldShowFriendlyInvisibles()); + if(!modifying) return BooleanValue.of(team.canSeeFriendlyInvisibles()); if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString()); boolean seeFriendlyInvisibles = settingVal.getBoolean(); - team.setShowFriendlyInvisibles(seeFriendlyInvisibles); + team.setSeeFriendlyInvisibles(seeFriendlyInvisibles); break; case "suffix": - if(!modifying) return new FormattedTextValue(team.getSuffix()); + if(!modifying) return new FormattedTextValue(team.getPlayerSuffix()); if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString()); - Text suffix; + Component suffix; suffix = FormattedTextValue.getTextByValue(settingVal); - team.setSuffix(suffix); + team.setPlayerSuffix(suffix); break; default: throw new InternalExpressionException("team property '" + propertyVal.getString() + "' is not a valid property"); @@ -401,24 +399,24 @@ public class Scoreboards { expression.addContextFunction("bossbar", -1, (c, t, lv) -> { - BossBarManager bossBarManager = ((CarpetContext)c).s.getServer().getBossBarManager(); + CustomBossEvents bossBarManager = ((CarpetContext)c).s.getServer().getCustomBossEvents(); if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments"); - if(lv.size() == 0) return ListValue.wrap(bossBarManager.getAll().stream().map(CommandBossBar::getId).map(Identifier::toString).map(StringValue::of).collect(Collectors.toList())); + if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of).collect(Collectors.toList())); String id = lv.get(0).getString(); - Identifier identifier; + ResourceLocation identifier; identifier = InputValidator.identifierOf(id); if(lv.size() == 1) { if(bossBarManager.get(identifier) != null) return Value.FALSE; - return StringValue.of(bossBarManager.add(identifier,new LiteralText(id)).getId().toString()); + return StringValue.of(bossBarManager.create(identifier,new TextComponent(id)).getTextId().toString()); } String property = lv.get(1).getString(); - CommandBossBar bossBar = bossBarManager.get(identifier); + CustomBossEvent bossBar = bossBarManager.get(identifier); if(bossBar == null) return Value.NULL; Value propertyValue = (lv.size() == 3)?lv.get(2):null; @@ -426,20 +424,20 @@ public class Scoreboards { switch (property) { case "color": if(propertyValue == null) { - BossBar.Color color = (bossBar).getColor(); + BossEvent.BossBarColor color = (bossBar).getColor(); if(color == null) return Value.NULL; return StringValue.of(color.getName()); } - BossBar.Color color = BossBar.Color.byName(propertyValue.getString()); + BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString()); if(color == null) return Value.NULL; - bossBar.setColor(BossBar.Color.byName(propertyValue.getString())); + bossBar.setColor(BossEvent.BossBarColor.byName(propertyValue.getString())); return Value.TRUE; case "max": - if(propertyValue == null) return NumericValue.of(bossBar.getMaxValue()); + if(propertyValue == null) return NumericValue.of(bossBar.getMax()); if(!(propertyValue instanceof NumericValue)) throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property); - bossBar.setMaxValue(((NumericValue) propertyValue).getInt()); + bossBar.setMax(((NumericValue) propertyValue).getInt()); return Value.TRUE; case "name": if(propertyValue == null) return new FormattedTextValue(bossBar.getName()); @@ -451,13 +449,13 @@ public class Scoreboards { if(propertyValue instanceof ListValue) { ((ListValue) propertyValue).getItems().forEach((v)->{ - ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue); if(player != null) bossBar.addPlayer(player); }); return Value.TRUE; } - ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); if(player != null) { bossBar.addPlayer(player); return Value.TRUE; @@ -467,27 +465,27 @@ public class Scoreboards { if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new).collect(Collectors.toList())); if(propertyValue instanceof ListValue) { - bossBar.clearPlayers(); + bossBar.removeAllPlayers(); ((ListValue) propertyValue).getItems().forEach((v) -> { - ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v); + ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v); if (p != null) bossBar.addPlayer(p); }); return Value.TRUE; } - ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); - bossBar.clearPlayers(); + ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); + bossBar.removeAllPlayers(); if (p != null) { bossBar.addPlayer(p); return Value.TRUE; } return Value.FALSE; case "style": - if(propertyValue == null) return StringValue.of(bossBar.getStyle().getName()); - BossBar.Style style = BossBar.Style.byName(propertyValue.getString()); + if(propertyValue == null) return StringValue.of(bossBar.getOverlay().getName()); + BossEvent.BossBarOverlay style = BossEvent.BossBarOverlay.byName(propertyValue.getString()); if(style == null) throw new InternalExpressionException("'" + propertyValue.getString() + "' is not a valid value for property " + property); - bossBar.setStyle(style); + bossBar.setOverlay(style); return Value.TRUE; case "value": if(propertyValue == null) return NumericValue.of(bossBar.getValue()); diff --git a/src/main/java/carpet/script/api/Threading.java b/src/main/java/carpet/script/api/Threading.java index 257f4084..e62c504e 100644 --- a/src/main/java/carpet/script/api/Threading.java +++ b/src/main/java/carpet/script/api/Threading.java @@ -16,7 +16,7 @@ public class Threading { //"overidden" native call to cancel if on main thread expression.addContextFunction("task_join", 1, (c, t, lv) -> { - if (((CarpetContext)c).s.getServer().isOnThread()) + if (((CarpetContext)c).s.getServer().isSameThread()) throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks"); Value v = lv.get(0); if (!(v instanceof ThreadValue)) @@ -28,12 +28,12 @@ public class Threading expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> { CarpetContext cc = (CarpetContext)c; MinecraftServer server = cc.s.getServer(); - if (server.isOnThread()) return lv.get(0); // pass through for on thread tasks + if (server.isSameThread()) return lv.get(0); // pass through for on thread tasks Value[] result = new Value[]{Value.NULL}; RuntimeException[] internal = new RuntimeException[]{null}; try { - ((CarpetContext) c).s.getServer().submitAndJoin(() -> + ((CarpetContext) c).s.getServer().executeBlocking(() -> { try { diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 5f1b96ba..e67c66f7 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -42,75 +42,6 @@ import carpet.utils.BlockInfo; import com.mojang.brigadier.exceptions.CommandSyntaxException; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.CommandBlock; -import net.minecraft.block.JigsawBlock; -import net.minecraft.block.StructureBlock; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.command.argument.ItemStackArgument; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.enchantment.Enchantments; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.FallingBlockEntity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.ai.pathing.NavigationType; -import net.minecraft.item.BlockItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.item.MiningToolItem; -import net.minecraft.item.ShearsItem; -import net.minecraft.item.SwordItem; -import net.minecraft.item.TridentItem; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; -import net.minecraft.network.packet.s2c.play.ExplosionS2CPacket; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ChunkTicket; -import net.minecraft.server.world.ChunkTicketType; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.sound.BlockSoundGroup; -import net.minecraft.sound.SoundCategory; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.Property; -import net.minecraft.structure.StructureStart; -import net.minecraft.tag.Tag; -import net.minecraft.tag.TagManager; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Clearable; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.SortedArraySet; -import net.minecraft.util.math.BlockBox; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.Heightmap; -import net.minecraft.world.LightType; -import net.minecraft.world.SpawnHelper; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.source.BiomeCoords; -import net.minecraft.world.biome.source.BiomeSource; -import net.minecraft.world.biome.source.MultiNoiseBiomeSource; -import net.minecraft.world.biome.source.util.MultiNoiseUtil; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.chunk.WorldChunk; -import net.minecraft.world.explosion.Explosion; -import net.minecraft.world.gen.random.ChunkRandom; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.feature.ConfiguredStructureFeature; -import net.minecraft.world.gen.feature.StructureFeature; -import net.minecraft.world.level.ServerWorldProperties; -import net.minecraft.world.poi.PointOfInterest; -import net.minecraft.world.poi.PointOfInterestStorage; -import net.minecraft.world.poi.PointOfInterestType; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -127,6 +58,71 @@ import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; +import net.minecraft.commands.arguments.item.ItemInput; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.QuartPos; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.Ticket; +import net.minecraft.server.level.TicketType; +import net.minecraft.sounds.SoundSource; +import net.minecraft.tags.TagContainer; +import net.minecraft.util.Mth; +import net.minecraft.util.SortedArraySet; +import net.minecraft.world.Clearable; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.village.poi.PoiManager; +import net.minecraft.world.entity.ai.village.poi.PoiRecord; +import net.minecraft.world.entity.ai.village.poi.PoiType; +import net.minecraft.world.entity.item.FallingBlockEntity; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.DiggerItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.ShearsItem; +import net.minecraft.world.item.SwordItem; +import net.minecraft.world.item.TridentItem; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.Climate; +import net.minecraft.world.level.biome.MultiNoiseBiomeSource; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.WorldgenRandom; +import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.pathfinder.PathComputationType; +import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.phys.Vec3; import static carpet.script.utils.WorldTools.canHasChunk; @@ -138,10 +134,10 @@ public class WorldAccess { DIRECTION_MAP.put("x", Direction.EAST); } - private final static Map> ticketTypes = new HashMap>(){{ - put("portal", ChunkTicketType.PORTAL); - put("teleport", ChunkTicketType.POST_TELEPORT); - put("unknown", ChunkTicketType.UNKNOWN); // unknown + private final static Map> ticketTypes = new HashMap>(){{ + put("portal", TicketType.PORTAL); + put("teleport", TicketType.POST_TELEPORT); + put("unknown", TicketType.UNKNOWN); // unknown }}; // dummy entity for dummy requirements in the loot tables (see snowball) private static FallingBlockEntity DUMMY_ENTITY = null; @@ -189,7 +185,7 @@ public class WorldAccess { Context c, String name, List params, - Fluff.TriFunction test + Fluff.TriFunction test ) { CarpetContext cc = (CarpetContext) c; @@ -200,7 +196,7 @@ public class WorldAccess { { try { - return test.apply(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos(), cc.s.getWorld()); + return test.apply(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos(), cc.s.getLevel()); } catch (NullPointerException ignored) { @@ -208,17 +204,17 @@ public class WorldAccess { } } BlockValue block = BlockArgument.findIn(cc, params, 0).block; - return test.apply(block.getBlockState(), block.getPos(), cc.s.getWorld()); + return test.apply(block.getBlockState(), block.getPos(), cc.s.getLevel()); } private static > BlockState setProperty(Property property, String name, String value, BlockState bs) { - Optional optional = property.parse(value); + Optional optional = property.getValue(value); if (optional.isPresent()) { - bs = bs.with(property, optional.get()); + bs = bs.setValue(property, optional.get()); } else { @@ -269,7 +265,7 @@ public class WorldAccess { { if (lv.size() == 0) throw new InternalExpressionException("Block requires at least one parameter"); - NbtCompound tag = BlockArgument.findIn( (CarpetContext) c, lv, 0, true).block.getData(); + CompoundTag tag = BlockArgument.findIn( (CarpetContext) c, lv, 0, true).block.getData(); return NBTSerializableValue.of(tag); }); @@ -280,39 +276,39 @@ public class WorldAccess { if (lv.size() == 0) throw new InternalExpressionException("'poi' requires at least one parameter"); BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); BlockPos pos = locator.block.getPos(); - PointOfInterestStorage store = cc.s.getWorld().getPointOfInterestStorage(); + PoiManager store = cc.s.getLevel().getPoiManager(); if (lv.size() == locator.offset) { - PointOfInterestType poiType = store.getType(pos).orElse(null); + PoiType poiType = store.getType(pos).orElse(null); if (poiType == null) return Value.NULL; // this feels wrong, but I don't want to mix-in more than I really need to. // also distance adds 0.5 to each point which screws up accurate distance calculations // you shoudn't be using POI with that in mind anyways, so I am not worried about it. - PointOfInterest poi = store.getInCircle( - poiType.getCompletionCondition(), + PoiRecord poi = store.getInRange( + poiType.getPredicate(), pos, 1, - PointOfInterestStorage.OccupationStatus.ANY + PoiManager.Occupancy.ANY ).filter(p -> p.getPos().equals(pos)).findFirst().orElse(null); if (poi == null) return Value.NULL; return ListValue.of( - new StringValue(poi.getType().toString()), - new NumericValue(poiType.getTicketCount() - ((PointOfInterest_scarpetMixin)poi).getFreeTickets()) + new StringValue(poi.getPoiType().toString()), + new NumericValue(poiType.getMaxTickets() - ((PointOfInterest_scarpetMixin)poi).getFreeTickets()) ); } int radius = NumericValue.asNumber(lv.get(locator.offset+0)).getInt(); if (radius < 0) return ListValue.of(); - Predicate condition = PointOfInterestType.ALWAYS_TRUE; - PointOfInterestStorage.OccupationStatus status = PointOfInterestStorage.OccupationStatus.ANY; + Predicate condition = PoiType.ALL; + PoiManager.Occupancy status = PoiManager.Occupancy.ANY; boolean inColumn = false; if (locator.offset + 1 < lv.size()) { String poiType = lv.get(locator.offset+1).getString().toLowerCase(Locale.ROOT); if (!"any".equals(poiType)) { - PointOfInterestType type = Registry.POINT_OF_INTEREST_TYPE.getOrEmpty(InputValidator.identifierOf(poiType)) + PoiType type = Registry.POINT_OF_INTEREST_TYPE.getOptional(InputValidator.identifierOf(poiType)) .orElseThrow(() -> new ThrowStatement(poiType, Throwables.UNKNOWN_POI)); condition = (tt) -> tt == type; } @@ -320,9 +316,9 @@ public class WorldAccess { { String statusString = lv.get(locator.offset+2).getString().toLowerCase(Locale.ROOT); if ("occupied".equals(statusString)) - status = PointOfInterestStorage.OccupationStatus.IS_OCCUPIED; + status = PoiManager.Occupancy.IS_OCCUPIED; else if ("available".equals(statusString)) - status = PointOfInterestStorage.OccupationStatus.HAS_SPACE; + status = PoiManager.Occupancy.HAS_SPACE; else if (!("any".equals(statusString))) throw new InternalExpressionException( "Incorrect POI occupation status "+status+ " use `any`, " + "`occupied` or `available`" @@ -333,13 +329,13 @@ public class WorldAccess { } } } - Stream pois = inColumn? + Stream pois = inColumn? store.getInSquare(condition, pos, radius, status): - store.getInCircle(condition, pos, radius, status); - return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().getSquaredDistance(pos))).map(p -> + store.getInRange(condition, pos, radius, status); + return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> ListValue.of( - new StringValue(p.getType().toString()), - new NumericValue(p.getType().getTicketCount() - ((PointOfInterest_scarpetMixin)p).getFreeTickets()), + new StringValue(p.getPoiType().toString()), + new NumericValue(p.getPoiType().getMaxTickets() - ((PointOfInterest_scarpetMixin)p).getFreeTickets()), ListValue.of(new NumericValue(p.getPos().getX()), new NumericValue(p.getPos().getY()), new NumericValue(p.getPos().getZ())) ) ).collect(Collectors.toList())); @@ -354,7 +350,7 @@ public class WorldAccess { BlockPos pos = locator.block.getPos(); if (lv.size() < locator.offset) throw new InternalExpressionException("'set_poi' requires the new poi type or null, after position argument"); Value poi = lv.get(locator.offset+0); - PointOfInterestStorage store = cc.s.getWorld().getPointOfInterestStorage(); + PoiManager store = cc.s.getLevel().getPoiManager(); if (poi.isNull()) { // clear poi information if (!store.getType(pos).isPresent()) return Value.FALSE; @@ -362,7 +358,7 @@ public class WorldAccess { return Value.TRUE; } String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); - PointOfInterestType type = Registry.POINT_OF_INTEREST_TYPE.getOrEmpty(InputValidator.identifierOf(poiTypeString)) + PoiType type = Registry.POINT_OF_INTEREST_TYPE.getOptional(InputValidator.identifierOf(poiTypeString)) .orElseThrow(() -> new ThrowStatement(poiTypeString, Throwables.UNKNOWN_POI)); int occupancy = 0; if (locator.offset + 1 < lv.size()) @@ -377,9 +373,9 @@ public class WorldAccess { if (occupancy > 0) { int finalO = occupancy; - store.getInSquare((tt) -> tt==type, pos, 1, PointOfInterestStorage.OccupationStatus.ANY + store.getInSquare((tt) -> tt==type, pos, 1, PoiManager.Occupancy.ANY ).filter(p -> p.getPos().equals(pos)).findFirst().ifPresent(p -> { - for (int i=0; i < finalO; i++) ((PointOfInterest_scarpetMixin)p).callReserveTicket(); + for (int i=0; i < finalO; i++) ((PointOfInterest_scarpetMixin)p).callAcquireTicket(); }); } return Value.TRUE; @@ -387,13 +383,13 @@ public class WorldAccess { expression.addContextFunction("weather",-1,(c, t, lv) -> { - ServerWorld world = ((CarpetContext) c).s.getWorld(); + ServerLevel world = ((CarpetContext) c).s.getLevel(); if(lv.size()==0)//cos it can thunder when raining or when clear. return new StringValue(world.isThundering() ? "thunder" : (world.isRaining() ? "rain" : "clear")); Value weather = lv.get(0); - ServerWorldProperties worldProperties = ((ServerWorldInterface) world).getWorldPropertiesCM(); + ServerLevelData worldProperties = ((ServerWorldInterface) world).getWorldPropertiesCM(); if(lv.size()==1) { int ticks; @@ -418,15 +414,15 @@ public class WorldAccess { switch (weather.getString().toLowerCase(Locale.ROOT)) { case "clear": - world.setWeather(ticks,0,false,false); + world.setWeatherParameters(ticks,0,false,false); break; case "rain": - world.setWeather(0,ticks,true,false); + world.setWeatherParameters(0,ticks,true,false); break; case "thunder": - world.setWeather( + world.setWeatherParameters( 0, ticks,//this is used to set thunder time, idk why... true, @@ -477,12 +473,12 @@ public class WorldAccess { int howMuch = 1; if (lv.size() > locator.offset+1) howMuch = (int) NumericValue.asNumber(lv.get(locator.offset+1)).getLong(); - BlockPos retpos = pos.offset(dir, howMuch); + BlockPos retpos = pos.relative(dir, howMuch); return ListValue.of(new NumericValue(retpos.getX()), new NumericValue(retpos.getY()), new NumericValue(retpos.getZ())); }); expression.addContextFunction("solid", -1, (c, t, lv) -> - genericStateTest(c, "solid", lv, (s, p, w) -> BooleanValue.of(s.isSolidBlock(w, p)))); // isSimpleFullBlock + genericStateTest(c, "solid", lv, (s, p, w) -> BooleanValue.of(s.isRedstoneConductor(w, p)))); // isSimpleFullBlock expression.addContextFunction("air", -1, (c, t, lv) -> booleanStateTest(c, "air", lv, (s, p) -> s.isAir())); @@ -491,7 +487,7 @@ public class WorldAccess { booleanStateTest(c, "liquid", lv, (s, p) -> !s.getFluidState().isEmpty())); expression.addContextFunction("flammable", -1, (c, t, lv) -> - booleanStateTest(c, "flammable", lv, (s, p) -> s.getMaterial().isBurnable())); + booleanStateTest(c, "flammable", lv, (s, p) -> s.getMaterial().isFlammable())); expression.addContextFunction("transparent", -1, (c, t, lv) -> booleanStateTest(c, "transparent", lv, (s, p) -> !s.getMaterial().isSolid())); @@ -503,36 +499,36 @@ public class WorldAccess { genericStateTest(c, "blocks_daylight", lv, (s, p, w) -> new NumericValue(s.propagatesSkylightDown(w, p))));*/ // investigate expression.addContextFunction("emitted_light", -1, (c, t, lv) -> - genericStateTest(c, "emitted_light", lv, (s, p, w) -> new NumericValue(s.getLuminance()))); + genericStateTest(c, "emitted_light", lv, (s, p, w) -> new NumericValue(s.getLightEmission()))); expression.addContextFunction("light", -1, (c, t, lv) -> - genericStateTest(c, "light", lv, (s, p, w) -> new NumericValue(Math.max(w.getLightLevel(LightType.BLOCK, p), w.getLightLevel(LightType.SKY, p))))); + genericStateTest(c, "light", lv, (s, p, w) -> new NumericValue(Math.max(w.getBrightness(LightLayer.BLOCK, p), w.getBrightness(LightLayer.SKY, p))))); expression.addContextFunction("block_light", -1, (c, t, lv) -> - genericStateTest(c, "block_light", lv, (s, p, w) -> new NumericValue(w.getLightLevel(LightType.BLOCK, p)))); + genericStateTest(c, "block_light", lv, (s, p, w) -> new NumericValue(w.getBrightness(LightLayer.BLOCK, p)))); expression.addContextFunction("sky_light", -1, (c, t, lv) -> - genericStateTest(c, "sky_light", lv, (s, p, w) -> new NumericValue(w.getLightLevel(LightType.SKY, p)))); + genericStateTest(c, "sky_light", lv, (s, p, w) -> new NumericValue(w.getBrightness(LightLayer.SKY, p)))); expression.addContextFunction("see_sky", -1, (c, t, lv) -> - genericStateTest(c, "see_sky", lv, (s, p, w) -> BooleanValue.of(w.isSkyVisible(p)))); + genericStateTest(c, "see_sky", lv, (s, p, w) -> BooleanValue.of(w.canSeeSky(p)))); expression.addContextFunction("brightness", -1, (c, t, lv) -> genericStateTest(c, "brightness", lv, (s, p, w) -> new NumericValue(w.getBrightness(p)))); expression.addContextFunction("hardness", -1, (c, t, lv) -> - genericStateTest(c, "hardness", lv, (s, p, w) -> new NumericValue(s.getHardness(w, p)))); + genericStateTest(c, "hardness", lv, (s, p, w) -> new NumericValue(s.getDestroySpeed(w, p)))); expression.addContextFunction("blast_resistance", -1, (c, t, lv) -> - genericStateTest(c, "blast_resistance", lv, (s, p, w) -> new NumericValue(s.getBlock().getBlastResistance()))); + genericStateTest(c, "blast_resistance", lv, (s, p, w) -> new NumericValue(s.getBlock().getExplosionResistance()))); expression.addContextFunction("in_slime_chunk", -1, (c, t, lv) -> { BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); ChunkPos chunkPos = new ChunkPos(pos); - return BooleanValue.of(ChunkRandom.getSlimeRandom( + return BooleanValue.of(WorldgenRandom.seedSlimeChunk( chunkPos.x, chunkPos.z, - ((CarpetContext)c).s.getWorld().getSeed(), + ((CarpetContext)c).s.getLevel().getSeed(), 987234911L ).nextInt(10) == 0); }); @@ -540,40 +536,40 @@ public class WorldAccess { expression.addContextFunction("top", -1, (c, t, lv) -> { String type = lv.get(0).getString().toLowerCase(Locale.ROOT); - Heightmap.Type htype; + Heightmap.Types htype; switch (type) { //case "light": htype = Heightmap.Type.LIGHT_BLOCKING; break; //investigate - case "motion": htype = Heightmap.Type.MOTION_BLOCKING; break; - case "terrain": htype = Heightmap.Type.MOTION_BLOCKING_NO_LEAVES; break; - case "ocean_floor": htype = Heightmap.Type.OCEAN_FLOOR; break; - case "surface": htype = Heightmap.Type.WORLD_SURFACE; break; + case "motion": htype = Heightmap.Types.MOTION_BLOCKING; break; + case "terrain": htype = Heightmap.Types.MOTION_BLOCKING_NO_LEAVES; break; + case "ocean_floor": htype = Heightmap.Types.OCEAN_FLOOR; break; + case "surface": htype = Heightmap.Types.WORLD_SURFACE; break; default: throw new InternalExpressionException("Unknown heightmap type: "+type); } BlockArgument locator = BlockArgument.findIn((CarpetContext)c, lv, 1); BlockPos pos = locator.block.getPos(); int x = pos.getX(); int z = pos.getZ(); - return new NumericValue(((CarpetContext)c).s.getWorld().getChunk(x >> 4, z >> 4).sampleHeightmap(htype, x & 15, z & 15) + 1); + return new NumericValue(((CarpetContext)c).s.getLevel().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); }); expression.addContextFunction("loaded", -1, (c, t, lv) -> - BooleanValue.of((((CarpetContext) c).s.getWorld().isChunkLoaded(BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos())))); + BooleanValue.of((((CarpetContext) c).s.getLevel().hasChunkAt(BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos())))); // Deprecated, use loaded_status as more indicative expression.addContextFunction("loaded_ep", -1, (c, t, lv) -> { c.host.issueDeprecation("loaded_ep(...)"); BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - return BooleanValue.of(((CarpetContext)c).s.getWorld().shouldTickEntity(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); + return BooleanValue.of(((CarpetContext)c).s.getLevel().isPositionEntityTicking(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); }); expression.addContextFunction("loaded_status", -1, (c, t, lv) -> { BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - WorldChunk chunk = ((CarpetContext)c).s.getWorld().getChunkManager().getWorldChunk(pos.getX()>>4, pos.getZ()>>4, false); + LevelChunk chunk = ((CarpetContext)c).s.getLevel().getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false); if (chunk == null) return Value.ZERO; - return new NumericValue(chunk.getLevelType().ordinal()); + return new NumericValue(chunk.getFullStatus().ordinal()); }); expression.addContextFunction("is_chunk_generated", -1, (c, t, lv) -> @@ -583,7 +579,7 @@ public class WorldAccess { boolean force = false; if (lv.size() > locator.offset) force = lv.get(locator.offset).getBoolean(); - return BooleanValue.of(canHasChunk(((CarpetContext)c).s.getWorld(), new ChunkPos(pos), null, force)); + return BooleanValue.of(canHasChunk(((CarpetContext)c).s.getLevel(), new ChunkPos(pos), null, force)); }); expression.addContextFunction("generation_status", -1, (c, t, lv) -> @@ -593,16 +589,16 @@ public class WorldAccess { boolean forceLoad = false; if (lv.size() > blockArgument.offset) forceLoad = lv.get(blockArgument.offset).getBoolean(); - Chunk chunk = ((CarpetContext)c).s.getWorld().getChunk(pos.getX()>>4, pos.getZ()>>4, ChunkStatus.EMPTY, forceLoad); + ChunkAccess chunk = ((CarpetContext)c).s.getLevel().getChunk(pos.getX()>>4, pos.getZ()>>4, ChunkStatus.EMPTY, forceLoad); if (chunk == null) return Value.NULL; - return new StringValue(chunk.getStatus().getId()); + return new StringValue(chunk.getStatus().getName()); }); expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { - ServerWorld world = ((CarpetContext) c).s.getWorld(); - Long2ObjectOpenHashMap>> levelTickets = ( - (ChunkTicketManagerInterface) ((ServerChunkManagerInterface) world.getChunkManager()) + ServerLevel world = ((CarpetContext) c).s.getLevel(); + Long2ObjectOpenHashMap>> levelTickets = ( + (ChunkTicketManagerInterface) ((ServerChunkManagerInterface) world.getChunkSource()) .getCMTicketManager() ).getTicketsByPosition(); List res = new ArrayList<>(); @@ -611,11 +607,11 @@ public class WorldAccess { for (long key : levelTickets.keySet()) { ChunkPos chpos = new ChunkPos(key); - for (ChunkTicket ticket : levelTickets.get(key)) + for (Ticket ticket : levelTickets.get(key)) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), - new NumericValue(33 - ticket.getLevel()), + new NumericValue(33 - ticket.getTicketLevel()), new NumericValue(chpos.x), new NumericValue(chpos.z) )); @@ -626,14 +622,14 @@ public class WorldAccess { { BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); BlockPos pos = blockArgument.block.getPos(); - SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); + SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); if (tickets != null) { - for (ChunkTicket ticket : tickets) + for (Ticket ticket : tickets) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), - new NumericValue(33 - ticket.getLevel()) + new NumericValue(33 - ticket.getTicketLevel()) )); } } @@ -643,25 +639,25 @@ public class WorldAccess { }); expression.addContextFunction("suffocates", -1, (c, t, lv) -> - genericStateTest(c, "suffocates", lv, (s, p, w) -> BooleanValue.of(s.shouldSuffocate(w, p)))); // canSuffocate + genericStateTest(c, "suffocates", lv, (s, p, w) -> BooleanValue.of(s.isSuffocating(w, p)))); // canSuffocate expression.addContextFunction("power", -1, (c, t, lv) -> - genericStateTest(c, "power", lv, (s, p, w) -> new NumericValue(w.getReceivedRedstonePower(p)))); + genericStateTest(c, "power", lv, (s, p, w) -> new NumericValue(w.getBestNeighborSignal(p)))); expression.addContextFunction("ticks_randomly", -1, (c, t, lv) -> - booleanStateTest(c, "ticks_randomly", lv, (s, p) -> s.hasRandomTicks())); + booleanStateTest(c, "ticks_randomly", lv, (s, p) -> s.isRandomlyTicking())); expression.addContextFunction("update", -1, (c, t, lv) -> booleanStateTest(c, "update", lv, (s, p) -> { - ((CarpetContext) c).s.getWorld().updateNeighbor(p, s.getBlock(), p); + ((CarpetContext) c).s.getLevel().neighborChanged(p, s.getBlock(), p); return true; })); expression.addContextFunction("block_tick", -1, (c, t, lv) -> booleanStateTest(c, "block_tick", lv, (s, p) -> { - ServerWorld w = ((CarpetContext)c).s.getWorld(); + ServerLevel w = ((CarpetContext)c).s.getLevel(); s.randomTick(w, p, w.random); return true; })); @@ -669,8 +665,8 @@ public class WorldAccess { expression.addContextFunction("random_tick", -1, (c, t, lv) -> booleanStateTest(c, "random_tick", lv, (s, p) -> { - ServerWorld w = ((CarpetContext)c).s.getWorld(); - if (s.hasRandomTicks() || s.getFluidState().hasRandomTicks()) + ServerLevel w = ((CarpetContext)c).s.getLevel(); + if (s.isRandomlyTicking() || s.getFluidState().isRandomlyTicking()) s.randomTick(w, p, w.random); return true; })); @@ -681,7 +677,7 @@ public class WorldAccess { boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); if (previous) return lv.get(0); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().executeBlocking( () -> { try { @@ -699,12 +695,12 @@ public class WorldAccess { expression.addContextFunction("set", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); BlockState sourceBlockState = sourceLocator.block.getBlockState(); BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); - NbtCompound data = null; + CompoundTag data = null; if (lv.size() > sourceLocator.offset) { List args = new ArrayList<>(); @@ -750,7 +746,7 @@ public class WorldAccess { } } } - StateManager states = sourceBlockState.getBlock().getStateManager(); + StateDefinition states = sourceBlockState.getBlock().getStateDefinition(); for (int i = 0; i < args.size()-1; i += 2) { String paramString = args.get(i).getString(); @@ -763,28 +759,28 @@ public class WorldAccess { } if (data == null) data = sourceLocator.block.getData(); - NbtCompound finalData = data; + CompoundTag finalData = data; if (sourceBlockState == targetBlockState && data == null) return Value.FALSE; BlockState finalSourceBlockState = sourceBlockState; BlockPos targetPos = targetLocator.block.getPos(); Boolean[] result = new Boolean[]{true}; - cc.s.getServer().submitAndJoin( () -> + cc.s.getServer().executeBlocking( () -> { - Clearable.clear(world.getBlockEntity(targetPos)); - boolean success = world.setBlockState(targetPos, finalSourceBlockState, 2); + Clearable.tryClear(world.getBlockEntity(targetPos)); + boolean success = world.setBlock(targetPos, finalSourceBlockState, 2); if (finalData != null) { BlockEntity be = world.getBlockEntity(targetPos); if (be != null) { - NbtCompound destTag = finalData.copy(); + CompoundTag destTag = finalData.copy(); destTag.putInt("x", targetPos.getX()); destTag.putInt("y", targetPos.getY()); destTag.putInt("z", targetPos.getZ()); - be.readNbt(destTag); - be.markDirty(); + be.load(destTag); + be.setChanged(); success = true; } } @@ -797,7 +793,7 @@ public class WorldAccess { expression.addContextFunction("destroy", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockState state = locator.block.getBlockState(); if (state.isAir()) return Value.FALSE; @@ -817,11 +813,11 @@ public class WorldAccess { { playerBreak = true; String itemString = val.getString(); - item = Registry.ITEM.getOrEmpty(InputValidator.identifierOf(itemString)) + item = Registry.ITEM.getOptional(InputValidator.identifierOf(itemString)) .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } } - NbtCompound tag = null; + CompoundTag tag = null; if (lv.size() > locator.offset+1) { if (!playerBreak) throw new InternalExpressionException("tag is not necessary with 'destroy' with no item"); @@ -839,21 +835,21 @@ public class WorldAccess { ItemStack tool = new ItemStack(item, 1); if (tag != null) - tool.setNbt(tag); - if (playerBreak && state.getHardness(world, where) < 0.0) return Value.FALSE; + tool.setTag(tag); + if (playerBreak && state.getDestroySpeed(world, where) < 0.0) return Value.FALSE; boolean removed = world.removeBlock(where, false); if (!removed) return Value.FALSE; - world.syncWorldEvent(null, 2001, where, Block.getRawIdFromState(state)); + world.levelEvent(null, 2001, where, Block.getId(state)); boolean toolBroke = false; boolean dropLoot = true; if (playerBreak) { - boolean isUsingEffectiveTool = !state.isToolRequired() || tool.isSuitableFor(state); + boolean isUsingEffectiveTool = !state.requiresCorrectToolForDrops() || tool.isCorrectToolForDrops(state); //postMine() durability from item classes - float hardness = state.getHardness(world, where); + float hardness = state.getDestroySpeed(world, where); int damageAmount = 0; - if ((item instanceof MiningToolItem && hardness > 0.0) || item instanceof ShearsItem) + if ((item instanceof DiggerItem && hardness > 0.0) || item instanceof ShearsItem) { damageAmount = 1; } @@ -861,30 +857,30 @@ public class WorldAccess { { damageAmount = 2; } - toolBroke = damageAmount>0 && tool.damage(damageAmount, world.getRandom(), null); + toolBroke = damageAmount>0 && tool.hurt(damageAmount, world.getRandom(), null); if (!isUsingEffectiveTool) dropLoot = false; } if (dropLoot) { - if (how < 0 || (tag != null && EnchantmentHelper.getLevel(Enchantments.SILK_TOUCH, tool) > 0)) + if (how < 0 || (tag != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0)) { - Block.dropStack(world, where, new ItemStack(state.getBlock())); + Block.popResource(world, where, new ItemStack(state.getBlock())); } else { if (how > 0) - tool.addEnchantment(Enchantments.FORTUNE, (int) how); + tool.enchant(Enchantments.BLOCK_FORTUNE, (int) how); if (DUMMY_ENTITY == null) DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, null); - Block.dropStacks(state, world, where, be, DUMMY_ENTITY, tool); + Block.dropResources(state, world, where, be, DUMMY_ENTITY, tool); } } if (!playerBreak) // no tool info - block brokwn return Value.TRUE; if (toolBroke) return Value.NULL; - NbtElement outtag = tool.getNbt(); + Tag outtag = tool.getTag(); if (outtag == null) return Value.TRUE; return new NBTSerializableValue(() -> outtag); @@ -896,23 +892,23 @@ public class WorldAccess { if (lv.size()<2) throw new InternalExpressionException("'harvest' takes at least 2 parameters: entity and block, or position, to harvest"); CarpetContext cc = (CarpetContext)c; - World world = cc.s.getWorld(); + Level world = cc.s.getLevel(); Value entityValue = lv.get(0); if (!(entityValue instanceof EntityValue)) return Value.FALSE; Entity e = ((EntityValue) entityValue).getEntity(); - if (!(e instanceof ServerPlayerEntity)) + if (!(e instanceof ServerPlayer)) return Value.FALSE; - ServerPlayerEntity player = (ServerPlayerEntity)e; + ServerPlayer player = (ServerPlayer)e; BlockArgument locator = BlockArgument.findIn(cc, lv, 1); BlockPos where = locator.block.getPos(); BlockState state = locator.block.getBlockState(); Block block = state.getBlock(); boolean success = false; - if (!((block == Blocks.BEDROCK || block == Blocks.BARRIER) && player.interactionManager.isSurvivalLike())) - success = player.interactionManager.tryBreakBlock(where); + if (!((block == Blocks.BEDROCK || block == Blocks.BARRIER) && player.gameMode.isSurvival())) + success = player.gameMode.destroyBlock(where); if (success) - world.syncWorldEvent(null, 2001, where, Block.getRawIdFromState(state)); + world.levelEvent(null, 2001, where, Block.getId(state)); return BooleanValue.of(success); }); @@ -922,12 +918,12 @@ public class WorldAccess { throw new InternalExpressionException("'create_explosion' requires at least a position to explode"); CarpetContext cc = (CarpetContext)c; float powah = 4.0f; - Explosion.DestructionType mode = Explosion.DestructionType.BREAK; + Explosion.BlockInteraction mode = Explosion.BlockInteraction.BREAK; boolean createFire = false; Entity source = null; LivingEntity attacker = null; Vector3Argument location = Vector3Argument.findIn(lv, 0, false, true); - Vec3d pos = location.vec; + Vec3 pos = location.vec; if (lv.size() > location.offset) { powah = NumericValue.asNumber(lv.get(location.offset), "explosion power").getFloat(); @@ -936,7 +932,7 @@ public class WorldAccess { { String strval = lv.get(location.offset+1).getString(); try { - mode = Explosion.DestructionType.valueOf(strval.toUpperCase(Locale.ROOT)); + mode = Explosion.BlockInteraction.valueOf(strval.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException ile) { throw new InternalExpressionException("Illegal explosions block behaviour: "+strval); } if (lv.size() > location.offset+2) @@ -966,7 +962,7 @@ public class WorldAccess { attacker = (LivingEntity) attackingEntity; } else throw new InternalExpressionException("Attacking entity needs to be a living thing, "+ - ValueConversions.of(Registry.ENTITY_TYPE.getId(attackingEntity.getType())).getString() +" ain't it."); + ValueConversions.of(Registry.ENTITY_TYPE.getKey(attackingEntity.getType())).getString() +" ain't it."); } else @@ -982,18 +978,18 @@ public class WorldAccess { float thePowah = powah; // copy of ServerWorld.createExplosion #TRACK# - Explosion explosion = new Explosion(cc.s.getWorld(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode){ + Explosion explosion = new Explosion(cc.s.getLevel(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode){ @Override - public @Nullable LivingEntity getCausingEntity() { + public @Nullable LivingEntity getSourceMob() { return theAttacker; } }; - explosion.collectBlocksAndDamageEntities(); - explosion.affectWorld(false); - if (mode == Explosion.DestructionType.NONE) explosion.clearAffectedBlocks(); - cc.s.getWorld().getPlayers().forEach(spe -> { - if (spe.squaredDistanceTo(pos) < 4096.0D) - spe.networkHandler.sendPacket(new ExplosionS2CPacket(pos.x, pos.y, pos.z, thePowah, explosion.getAffectedBlocks(), explosion.getAffectedPlayers().get(spe))); + explosion.explode(); + explosion.finalizeExplosion(false); + if (mode == Explosion.BlockInteraction.NONE) explosion.clearToBlow(); + cc.s.getLevel().players().forEach(spe -> { + if (spe.distanceToSqr(pos) < 4096.0D) + spe.connection.send(new ClientboundExplodePacket(pos.x, pos.y, pos.z, thePowah, explosion.getToBlow(), explosion.getHitPlayers().get(spe))); }); return Value.TRUE; }); @@ -1006,7 +1002,7 @@ public class WorldAccess { CarpetContext cc = (CarpetContext) c; String itemString = lv.get(0).getString(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); - ItemStackArgument stackArg = NBTSerializableValue.parseItem(itemString); + ItemInput stackArg = NBTSerializableValue.parseItem(itemString); BlockPos where = new BlockPos(locator.vec); String facing = "up"; if (lv.size() > locator.offset) @@ -1018,7 +1014,7 @@ public class WorldAccess { BlockValue.PlacementContext ctx; try { - ctx = BlockValue.PlacementContext.from(cc.s.getWorld(), where, facing, sneakPlace, stackArg.createStack(1, false)); + ctx = BlockValue.PlacementContext.from(cc.s.getLevel(), where, facing, sneakPlace, stackArg.createItemStack(1, false)); } catch (CommandSyntaxException e) { @@ -1027,8 +1023,8 @@ public class WorldAccess { if (!(stackArg.getItem() instanceof BlockItem)) { - ActionResult useResult = ctx.getStack().useOnBlock(ctx); - if (useResult == ActionResult.CONSUME || useResult == ActionResult.SUCCESS) + InteractionResult useResult = ctx.getItemInHand().useOn(ctx); + if (useResult == InteractionResult.CONSUME || useResult == InteractionResult.SUCCESS) { return Value.TRUE; } @@ -1037,14 +1033,14 @@ public class WorldAccess { { // not sure we need special case for block items, since useOnBlock can do that as well BlockItem blockItem = (BlockItem) stackArg.getItem(); if (!ctx.canPlace()) return Value.FALSE; - BlockState placementState = blockItem.getBlock().getPlacementState(ctx); + BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); if (placementState != null) { - if (placementState.canPlaceAt(cc.s.getWorld(), where)) + if (placementState.canSurvive(cc.s.getLevel(), where)) { - cc.s.getWorld().setBlockState(where, placementState, 2); - BlockSoundGroup blockSoundGroup = placementState.getSoundGroup(); - cc.s.getWorld().playSound(null, where, blockSoundGroup.getPlaceSound(), SoundCategory.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); + cc.s.getLevel().setBlock(where, placementState, 2); + SoundType blockSoundGroup = placementState.getSoundType(); + cc.s.getLevel().playSound(null, where, blockSoundGroup.getPlaceSound(), SoundSource.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); return Value.TRUE; } } @@ -1054,11 +1050,11 @@ public class WorldAccess { expression.addContextFunction("blocks_movement", -1, (c, t, lv) -> booleanStateTest(c, "blocks_movement", lv, (s, p) -> - !s.canPathfindThrough(((CarpetContext) c).s.getWorld(), p, NavigationType.LAND))); + !s.isPathfindable(((CarpetContext) c).s.getLevel(), p, PathComputationType.LAND))); expression.addContextFunction("block_sound", -1, (c, t, lv) -> stateStringQuery(c, "block_sound", lv, (s, p) -> - BlockInfo.soundName.get(s.getSoundGroup()))); + BlockInfo.soundName.get(s.getSoundType()))); expression.addContextFunction("material", -1, (c, t, lv) -> stateStringQuery(c, "material", lv, (s, p) -> @@ -1066,7 +1062,7 @@ public class WorldAccess { expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).s.getWorld(), p)))); + BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).s.getLevel(), p)))); // Deprecated for block_state() @@ -1078,10 +1074,10 @@ public class WorldAccess { if (lv.size() <= locator.offset) throw new InternalExpressionException("'property' requires to specify a property to query"); String tag = lv.get(locator.offset).getString(); - StateManager states = state.getBlock().getStateManager(); + StateDefinition states = state.getBlock().getStateDefinition(); Property property = states.getProperty(tag); if (property == null) return Value.NULL; - return new StringValue(state.get(property).toString().toLowerCase(Locale.ROOT)); + return new StringValue(state.getValue(property).toString().toLowerCase(Locale.ROOT)); }); // Deprecated for block_state() @@ -1090,7 +1086,7 @@ public class WorldAccess { c.host.issueDeprecation("block_properties(...)"); BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); BlockState state = locator.block.getBlockState(); - StateManager states = state.getBlock().getStateManager(); + StateDefinition states = state.getBlock().getStateDefinition(); return ListValue.wrap(states.getProperties().stream().map( p -> new StringValue(p.getName())).collect(Collectors.toList()) ); @@ -1102,7 +1098,7 @@ public class WorldAccess { { BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0, true); BlockState state = locator.block.getBlockState(); - StateManager states = state.getBlock().getStateManager(); + StateDefinition states = state.getBlock().getStateDefinition(); if (locator.offset == lv.size()) { Map properties = new HashMap<>(); @@ -1122,41 +1118,41 @@ public class WorldAccess { expression.addContextFunction("block_list", -1, (c, t, lv) -> { if (lv.size() == 0) - return ListValue.wrap(Registry.BLOCK.getIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(Registry.BLOCK.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getServer().getTagManager(); + TagContainer tagManager = cc.s.getServer().getTags(); String tag = lv.get(0).getString(); - net.minecraft.tag.Tag blockTag = tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTag(InputValidator.identifierOf(tag)); + net.minecraft.tags.Tag blockTag = tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getTag(InputValidator.identifierOf(tag)); if (blockTag == null) return Value.NULL; - return ListValue.wrap(blockTag.values().stream().map(b -> ValueConversions.of(Registry.BLOCK.getId(b))).collect(Collectors.toList())); + return ListValue.wrap(blockTag.getValues().stream().map(b -> ValueConversions.of(Registry.BLOCK.getKey(b))).collect(Collectors.toList())); }); expression.addContextFunction("block_tags", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - TagManager tagManager = cc.s.getServer().getTagManager(); + TagContainer tagManager = cc.s.getServer().getTags(); if (lv.size() == 0) - return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList())); BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); if (blockLocator.offset == lv.size()) { Block target = blockLocator.block.getBlockState().getBlock(); - return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); + return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList())); } String tag = lv.get(blockLocator.offset).getString(); - Tag blockTag = tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getTag(InputValidator.identifierOf(tag)); + net.minecraft.tags.Tag blockTag = tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getTag(InputValidator.identifierOf(tag)); if (blockTag == null) return Value.NULL; - return BooleanValue.of(blockLocator.block.getBlockState().isIn(blockTag)); + return BooleanValue.of(blockLocator.block.getBlockState().is(blockTag)); }); expression.addContextFunction("biome", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext) c; - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); if (lv.size() == 0) - return ListValue.wrap(world.getRegistryManager().get(Registry.BIOME_KEY).getIds().stream().map(ValueConversions::of)); + return ListValue.wrap(world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).keySet().stream().map(ValueConversions::of)); Biome biome; - BiomeSource biomeSource = world.getChunkManager().getChunkGenerator().getBiomeSource(); + BiomeSource biomeSource = world.getChunkSource().getGenerator().getBiomeSource(); if ( lv.size() == 1 && lv.get(0) instanceof MapValue map && biomeSource instanceof MultiNoiseBiomeSource mnbs @@ -1179,16 +1175,16 @@ public class WorldAccess { Value weirdness = map.get(new StringValue("weirdness")); nullCheck(weirdness, "weirdness"); - MultiNoiseUtil.NoiseValuePoint point = new MultiNoiseUtil.NoiseValuePoint( - MultiNoiseUtil.method_38665(numberGetOrThrow(temperature)), - MultiNoiseUtil.method_38665(numberGetOrThrow(humidity)), - MultiNoiseUtil.method_38665(numberGetOrThrow(continentalness)), - MultiNoiseUtil.method_38665(numberGetOrThrow(erosion)), - MultiNoiseUtil.method_38665(numberGetOrThrow(depth)), - MultiNoiseUtil.method_38665(numberGetOrThrow(weirdness)) + Climate.TargetPoint point = new Climate.TargetPoint( + Climate.quantizeCoord(numberGetOrThrow(temperature)), + Climate.quantizeCoord(numberGetOrThrow(humidity)), + Climate.quantizeCoord(numberGetOrThrow(continentalness)), + Climate.quantizeCoord(numberGetOrThrow(erosion)), + Climate.quantizeCoord(numberGetOrThrow(depth)), + Climate.quantizeCoord(numberGetOrThrow(weirdness)) ); - biome = mnbs.getBiomeAtPoint(point); - Identifier biomeId = cc.s.getServer().getRegistryManager().get(Registry.BIOME_KEY).getId(biome); + biome = mnbs.getNoiseBiome(point); + ResourceLocation biomeId = cc.s.getServer().registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } @@ -1196,7 +1192,7 @@ public class WorldAccess { if (locator.replacement != null) { - biome = world.getRegistryManager().get(Registry.BIOME_KEY).get(InputValidator.identifierOf(locator.replacement)); + biome = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).get(InputValidator.identifierOf(locator.replacement)); if (biome == null) throw new ThrowStatement(locator.replacement, Throwables.UNKNOWN_BIOME); } else @@ -1207,11 +1203,11 @@ public class WorldAccess { // in locatebiome if (locator.offset == lv.size()) { - Identifier biomeId = cc.s.getServer().getRegistryManager().get(Registry.BIOME_KEY).getId(biome); + ResourceLocation biomeId = cc.s.getServer().registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } String biomeFeature = lv.get(locator.offset).getString(); - BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); + BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); if (featureProvider == null) throw new InternalExpressionException("Unknown biome feature: " + biomeFeature); return featureProvider.apply(world, biome); @@ -1225,26 +1221,26 @@ public class WorldAccess { throw new InternalExpressionException("'set_biome' needs a biome name as an argument"); String biomeName = lv.get(locator.offset+0).getString(); // from locatebiome command code - Biome biome = cc.s.getServer().getRegistryManager().get(Registry.BIOME_KEY).getOrEmpty(InputValidator.identifierOf(biomeName)) + Biome biome = cc.s.getServer().registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getOptional(InputValidator.identifierOf(biomeName)) .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); boolean doImmediateUpdate = true; if (lv.size() > locator.offset+1) { doImmediateUpdate = lv.get(locator.offset+1).getBoolean(); } - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockPos pos = locator.block.getPos(); - Chunk chunk = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.BIOMES); - if (chunk instanceof WorldChunk) return Value.FALSE; // questinoalble, but it makes sense - int biomeX = BiomeCoords.fromBlock(pos.getX()); - int biomeY = BiomeCoords.fromBlock(pos.getY()); - int biomeZ = BiomeCoords.fromBlock(pos.getZ()); + ChunkAccess chunk = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.BIOMES); + if (chunk instanceof LevelChunk) return Value.FALSE; // questinoalble, but it makes sense + int biomeX = QuartPos.fromBlock(pos.getX()); + int biomeY = QuartPos.fromBlock(pos.getY()); + int biomeZ = QuartPos.fromBlock(pos.getZ()); try { - int i = BiomeCoords.fromBlock(chunk.getBottomY()); - int j = i + BiomeCoords.fromBlock(chunk.getHeight()) - 1; - int k = MathHelper.clamp(biomeY, i, j); - int l = chunk.getSectionIndex(BiomeCoords.toBlock(k)); - chunk.getSection(l).getBiomeContainer().set(biomeX & 3, k & 3, biomeZ & 3, biome); + int i = QuartPos.fromBlock(chunk.getMinBuildHeight()); + int j = i + QuartPos.fromBlock(chunk.getHeight()) - 1; + int k = Mth.clamp(biomeY, i, j); + int l = chunk.getSectionIndex(QuartPos.toBlock(k)); + chunk.getSection(l).getBiomes().set(biomeX & 3, k & 3, biomeZ & 3, biome); } catch (Throwable var8) { return Value.FALSE; } @@ -1255,21 +1251,21 @@ public class WorldAccess { expression.addContextFunction("reload_chunk", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); - ServerWorld world = cc.s.getWorld(); - cc.s.getServer().submitAndJoin( () -> WorldTools.forceChunkUpdate(pos, world)); + ServerLevel world = cc.s.getLevel(); + cc.s.getServer().executeBlocking( () -> WorldTools.forceChunkUpdate(pos, world)); return Value.TRUE; }); expression.addContextFunction("structure_references", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockPos pos = locator.block.getPos(); - Map, LongSet> references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getStructureReferences(); + Map, LongSet> references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); if (lv.size() == locator.offset) return ListValue.wrap(references.entrySet().stream(). filter(e -> e.getValue()!= null && !e.getValue().isEmpty()). - map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getId(e.getKey())))).collect(Collectors.toList()) + map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getKey(e.getKey())))).collect(Collectors.toList()) ); String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); //CarpetSettings.LOG.error(FeatureGenerator.featureToStructure.keySet().stream().collect(Collectors.joining(","))); @@ -1279,9 +1275,9 @@ public class WorldAccess { LongSet structureReferences = references.get(structureName); if (structureReferences == null || structureReferences.isEmpty()) return ListValue.of(); return ListValue.wrap(structureReferences.stream().map(l -> ListValue.of( - new NumericValue(16*ChunkPos.getPackedX(l)), + new NumericValue(16*ChunkPos.getX(l)), Value.ZERO, - new NumericValue(16*ChunkPos.getPackedZ(l)))).collect(Collectors.toList())); + new NumericValue(16*ChunkPos.getZ(l)))).collect(Collectors.toList())); }); expression.addContextFunction("structure_eligibility", -1, (c, t, lv) -> @@ -1289,10 +1285,10 @@ public class WorldAccess { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); // well, because - BooYah(world.getChunkManager().getChunkGenerator()); + BooYah(world.getChunkSource().getGenerator()); BlockPos pos = locator.block.getPos(); StructureFeature structure = null; @@ -1303,7 +1299,7 @@ public class WorldAccess { if (!(requested instanceof NullValue)) { String reqString = requested.getString(); - structure = Registry.STRUCTURE_FEATURE.getOrEmpty(InputValidator.identifierOf(reqString)) + structure = Registry.STRUCTURE_FEATURE.getOptional(InputValidator.identifierOf(reqString)) .orElseThrow(() -> new ThrowStatement(reqString, Throwables.UNKNOWN_STRUCTURE)); } if (lv.size() > locator.offset+1) @@ -1319,7 +1315,7 @@ public class WorldAccess { return ValueConversions.of(start); } Map ret = new HashMap<>(); - for(StructureFeature str : StructureFeature.STRUCTURES.values()) + for(StructureFeature str : StructureFeature.STRUCTURES_REGISTRY.values()) { StructureStart start; try @@ -1328,13 +1324,13 @@ public class WorldAccess { } catch (NullPointerException npe) { - CarpetSettings.LOG.error("Failed to detect structure: "+str.getName()); + CarpetSettings.LOG.error("Failed to detect structure: "+str.getFeatureName()); start = null; } if (start == null) continue; - Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getId(str))); + Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getKey(str))); ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start)); } return MapValue.wrap(ret); @@ -1344,21 +1340,21 @@ public class WorldAccess { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockPos pos = locator.block.getPos(); - Map, StructureStart> structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getStructureStarts(); + Map, StructureStart> structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); if (lv.size() == locator.offset) { Map structureList = new HashMap<>(); for (Map.Entry, StructureStart> entry : structures.entrySet()) { StructureStart start = entry.getValue(); - if (start == StructureStart.DEFAULT) + if (start == StructureStart.INVALID_START) continue; - BlockBox box = start.getBoundingBox(); + BoundingBox box = start.getBoundingBox(); structureList.put( - new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getId(entry.getKey()))), - ListValue.of(ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ())) + new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_FEATURE.getKey(entry.getKey()))), + ListValue.of(ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ())) ); } return MapValue.wrap(structureList); @@ -1372,7 +1368,7 @@ public class WorldAccess { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); BlockPos pos = locator.block.getPos(); if (lv.size() == locator.offset) @@ -1383,12 +1379,12 @@ public class WorldAccess { // good 'ol pointer Value[] result = new Value[]{Value.NULL}; // technically a world modification. Even if we could let it slide, we will still park it - ((CarpetContext) c).s.getServer().submitAndJoin(() -> + ((CarpetContext) c).s.getServer().executeBlocking(() -> { - Map, StructureStart> structures = world.getChunk(pos).getStructureStarts(); + Map, StructureStart> structures = world.getChunk(pos).getAllStarts(); if (lv.size() == locator.offset + 1) { - Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).s.getWorld(), locator.block.getPos()); + Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).s.getLevel(), locator.block.getPos()); //Boolean res = FeatureGenerator.gridStructure(structureName, ((CarpetContext) c).s.getWorld(), locator.block.getPos()); if (res == null) return; result[0] = res?Value.TRUE:Value.FALSE; @@ -1403,16 +1399,16 @@ public class WorldAccess { return; } StructureStart start = structures.get(structure); - ChunkPos structureChunkPos = start.getPos(); // new ChunkPos(start.getChunkX(), start.getChunkZ()); - BlockBox box = start.getBoundingBox(); - for (int chx = box.getMinX() / 16; chx <= box.getMaxX() / 16; chx++) // minx maxx + ChunkPos structureChunkPos = start.getChunkPos(); // new ChunkPos(start.getChunkX(), start.getChunkZ()); + BoundingBox box = start.getBoundingBox(); + for (int chx = box.minX() / 16; chx <= box.maxX() / 16; chx++) // minx maxx { - for (int chz = box.getMinZ() / 16; chz <= box.getMaxZ() / 16; chz++) //minZ maxZ + for (int chz = box.minZ() / 16; chz <= box.maxZ() / 16; chz++) //minZ maxZ { ChunkPos chpos = new ChunkPos(chx, chz); // getting a chunk will convert it to full, allowing to modify references Map, LongSet> references = - world.getChunk(chpos.getStartPos()).getStructureReferences(); + world.getChunk(chpos.getWorldPosition()).getAllReferences(); if (references.containsKey(structure) && references.get(structure) != null) references.get(structure).remove(structureChunkPos.toLong()); } @@ -1500,13 +1496,13 @@ public class WorldAccess { } - ServerWorld world = cc.s.getWorld(); + ServerLevel world = cc.s.getLevel(); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getServer().submitAndJoin( () -> + ((CarpetContext)c).s.getServer().executeBlocking( () -> { - Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkManager().threadedAnvilChunkStorage).regenerateChunkRegion(requestedChunks); + Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).regenerateChunkRegion(requestedChunks); /*for (ChunkPos chpos: requestedChunks) // needed in 1.16 only { if (world.getChunk(chpos.x, chpos.z, ChunkStatus.FULL, false) != null) @@ -1527,7 +1523,7 @@ public class WorldAccess { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockPos pos = locator.block.getPos(); - return new NumericValue(cc.s.getWorld().getChunk(pos).getInhabitedTime()); + return new NumericValue(cc.s.getLevel().getChunk(pos).getInhabitedTime()); }); expression.addContextFunction("spawn_potential", -1, (c, t, lv) -> @@ -1538,11 +1534,11 @@ public class WorldAccess { double required_charge = 1; if (lv.size() > locator.offset) required_charge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); - SpawnHelper.Info charger = cc.s.getWorld().getChunkManager().getSpawnInfo(); + NaturalSpawner.SpawnState charger = cc.s.getLevel().getChunkSource().getLastSpawnState(); if (charger == null) return Value.NULL; return new NumericValue( ((SpawnHelperInnerInterface)charger).getPotentialCalculator(). - calculate(pos, required_charge ) + getPotentialEnergyChange(pos, required_charge ) ); }); @@ -1553,29 +1549,29 @@ public class WorldAccess { BlockPos pos = locator.block.getPos(); if (lv.size() != locator.offset+2) throw new InternalExpressionException("'add_chunk_ticket' requires block position, ticket type and radius"); String type = lv.get(locator.offset).getString(); - ChunkTicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); + TicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); if (ticket == null) throw new InternalExpressionException("Unknown ticket type: "+type); int radius = NumericValue.asNumber(lv.get(locator.offset+1)).getInt(); if (radius < 1 || radius > 32) throw new InternalExpressionException("Ticket radius should be between 1 and 32 chunks"); // due to types we will wing it: ChunkPos target = new ChunkPos(pos); - if (ticket == ChunkTicketType.PORTAL) // portal - cc.s.getWorld().getChunkManager().addTicket(ChunkTicketType.PORTAL, target, radius, pos); - else if (ticket == ChunkTicketType.POST_TELEPORT) // post teleport - cc.s.getWorld().getChunkManager().addTicket(ChunkTicketType.POST_TELEPORT, target, radius, 1); + if (ticket == TicketType.PORTAL) // portal + cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.PORTAL, target, radius, pos); + else if (ticket == TicketType.POST_TELEPORT) // post teleport + cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, target, radius, 1); else - cc.s.getWorld().getChunkManager().addTicket(ChunkTicketType.UNKNOWN, target, radius, target); - return new NumericValue(ticket.getExpiryTicks()); + cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.UNKNOWN, target, radius, target); + return new NumericValue(ticket.timeout()); }); } @ScarpetFunction(maxParams = -1) public Value sample_noise(Context c, @Locator.Block BlockPos pos, String... noiseQueries) { - int mappedX = BiomeCoords.fromBlock(pos.getX()); - int mappedY = BiomeCoords.fromBlock(pos.getY()); - int mappedZ = BiomeCoords.fromBlock(pos.getZ()); - MultiNoiseUtil.MultiNoiseSampler mns = ((CarpetContext) c).s.getWorld().getChunkManager().getChunkGenerator().getMultiNoiseSampler(); + int mappedX = QuartPos.fromBlock(pos.getX()); + int mappedY = QuartPos.fromBlock(pos.getY()); + int mappedZ = QuartPos.fromBlock(pos.getZ()); + Climate.Sampler mns = ((CarpetContext) c).s.getLevel().getChunkSource().getGenerator().climateSampler(); Map ret = new HashMap<>(); if (noiseQueries.length == 0) { diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index 86468d06..4d9b2a23 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -8,11 +8,10 @@ import carpet.script.value.NullValue; import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; -import net.minecraft.util.math.BlockPos; - import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; +import net.minecraft.core.BlockPos; public class BlockArgument extends Argument { @@ -77,7 +76,7 @@ public class BlockArgument extends Argument return new BlockArgument( new BlockValue( null, - c.s.getWorld(), + c.s.getLevel(), new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) ), 1 + offset); @@ -88,7 +87,7 @@ public class BlockArgument extends Argument return new BlockArgument( new BlockValue( null, - c.s.getWorld(), + c.s.getLevel(), new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) ), 3 + offset @@ -127,7 +126,7 @@ public class BlockArgument extends Argument return new BlockArgument( new BlockValue( null, - c.s.getWorld(), + c.s.getLevel(), new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) ), 1+offset); @@ -138,7 +137,7 @@ public class BlockArgument extends Argument return new BlockArgument( new BlockValue( null, - c.s.getWorld(), + c.s.getLevel(), new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) ), 3+offset diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index 9b59dd09..930c121e 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -13,13 +13,13 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.ReportedException; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.NbtTagSizeTracker; -import net.minecraft.nbt.NbtElement; -import net.minecraft.nbt.NbtTypes; -import net.minecraft.util.WorldSavePath; -import net.minecraft.util.crash.CrashException; +import net.minecraft.nbt.Tag; +import net.minecraft.nbt.TagTypes; +import net.minecraft.world.level.storage.LevelResource; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.Pair; @@ -172,7 +172,7 @@ public class FileArgument { if (CarpetServer.minecraft_server == null) throw new InternalExpressionException("Accessing world files without server running"); - return CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+suffix); + return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+suffix); } private Path toPath(Module module) @@ -330,7 +330,7 @@ public class FileArgument return true; } - public NbtElement getNbtData(Module module) // aka getData + public Tag getNbtData(Module module) // aka getData { try { synchronized (writeIOSync) { Path dataFile = toPath(module); @@ -344,7 +344,7 @@ public class FileArgument //copied private method from net.minecraft.nbt.NbtIo.read() // to read non-compound tags - these won't be compressed - public static NbtElement readTag(Path path) + public static Tag readTag(Path path) { try { @@ -374,7 +374,7 @@ public class FileArgument else { dataInput_1.readUTF(); - return NbtTypes.byId(byte_1).read(dataInput_1, 0, NbtTagSizeTracker.EMPTY); + return TagTypes.getType(byte_1).load(dataInput_1, 0, NbtAccounter.UNLIMITED); } } catch (IOException secondIO) @@ -386,13 +386,13 @@ public class FileArgument } } } - catch (CrashException e) + catch (ReportedException e) { throw new ThrowStatement("Error when reading NBT file "+path.toString(), Throwables.NBT_ERROR); } } - public boolean saveNbtData(Module module, NbtElement tag) // aka saveData + public boolean saveNbtData(Module module, Tag tag) // aka saveData { try { synchronized (writeIOSync) { Path dataFile = toPath(module); @@ -407,7 +407,7 @@ public class FileArgument } //copied private method from net.minecraft.nbt.NbtIo.write() and client method safe_write - public static boolean writeTagDisk(NbtElement tag_1, Path path, boolean zipped) + public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped) { Path original = path; try @@ -418,16 +418,16 @@ public class FileArgument Files.deleteIfExists(path); } - if (tag_1 instanceof NbtCompound) + if (tag_1 instanceof CompoundTag) { - NbtIo.writeCompressed((NbtCompound) tag_1, Files.newOutputStream(path)); + NbtIo.writeCompressed((CompoundTag) tag_1, Files.newOutputStream(path)); } else { try (DataOutputStream dataOutputStream_1 = new DataOutputStream(Files.newOutputStream(path))) { - dataOutputStream_1.writeByte(tag_1.getType()); - if (tag_1.getType() != 0) + dataOutputStream_1.writeByte(tag_1.getId()); + if (tag_1.getId() != 0) { dataOutputStream_1.writeUTF(""); tag_1.write(dataOutputStream_1); diff --git a/src/main/java/carpet/script/argument/Vector3Argument.java b/src/main/java/carpet/script/argument/Vector3Argument.java index 212d2df7..c19bb479 100644 --- a/src/main/java/carpet/script/argument/Vector3Argument.java +++ b/src/main/java/carpet/script/argument/Vector3Argument.java @@ -6,28 +6,27 @@ import carpet.script.value.EntityValue; import carpet.script.value.ListValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.Vec3d; - import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; public class Vector3Argument extends Argument { - public Vec3d vec; + public Vec3 vec; public final double yaw; public final double pitch; public boolean fromBlock = false; public Entity entity = null; - private Vector3Argument(Vec3d v, int o) + private Vector3Argument(Vec3 v, int o) { super(o); this.vec = v; this.yaw = 0.0D; this.pitch = 0.0D; } - private Vector3Argument(Vec3d v, int o, double y, double p) + private Vector3Argument(Vec3 v, int o, double y, double p) { super(o); this.vec = v; @@ -63,17 +62,17 @@ public class Vector3Argument extends Argument Value v1 = params.next(); if (v1 instanceof BlockValue) { - return (new Vector3Argument(Vec3d.ofCenter(((BlockValue) v1).getPos()), 1+offset)).fromBlock(); + return (new Vector3Argument(Vec3.atCenterOf(((BlockValue) v1).getPos()), 1+offset)).fromBlock(); } if (optionalEntity && v1 instanceof EntityValue) { Entity e = ((EntityValue) v1).getEntity(); - return new Vector3Argument(e.getPos(), 1+offset).withEntity(e); + return new Vector3Argument(e.position(), 1+offset).withEntity(e); } if (v1 instanceof ListValue) { List args = ((ListValue) v1).getItems(); - Vec3d pos = new Vec3d( + Vec3 pos = new Vec3( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); @@ -86,7 +85,7 @@ public class Vector3Argument extends Argument } return new Vector3Argument(pos,offset+1, yaw, pitch); } - Vec3d pos = new Vec3d( + Vec3 pos = new Vec3( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.next()).getDouble(), NumericValue.asNumber(params.next()).getDouble()); diff --git a/src/main/java/carpet/script/bundled/Module.java b/src/main/java/carpet/script/bundled/Module.java index 369f4197..cec0fc79 100644 --- a/src/main/java/carpet/script/bundled/Module.java +++ b/src/main/java/carpet/script/bundled/Module.java @@ -2,11 +2,10 @@ package carpet.script.bundled; import carpet.CarpetServer; import carpet.script.argument.FileArgument; -import net.minecraft.nbt.NbtElement; -import net.minecraft.util.WorldSavePath; - import java.nio.file.Files; import java.nio.file.Path; +import net.minecraft.nbt.Tag; +import net.minecraft.world.level.storage.LevelResource; public abstract class Module { @@ -14,7 +13,7 @@ public abstract class Module public abstract String getCode(); public abstract boolean isLibrary(); - public static NbtElement getData(Module module) + public static Tag getData(Module module) { Path dataFile = resolveResource(module); if (dataFile == null) return null; @@ -22,7 +21,7 @@ public abstract class Module synchronized (FileArgument.writeIOSync) { return FileArgument.readTag(dataFile); } } - public static void saveData(Module module, NbtElement globalState) + public static void saveData(Module module, Tag globalState) { Path dataFile = resolveResource(module); if (dataFile == null) return; @@ -33,7 +32,7 @@ public abstract class Module private static Path resolveResource(Module module) { if (module == null || module.getName() == null) return null; // commandline app - return CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+module.getName()+".data.nbt"); + return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+module.getName()+".data.nbt"); } @Override diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index c4b559ee..07b9f497 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -37,56 +37,6 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.tree.ArgumentCommandNode; import com.mojang.brigadier.tree.CommandNode; -import net.minecraft.advancement.Advancement; -import net.minecraft.command.CommandSource; -import net.minecraft.command.argument.AngleArgumentType; -import net.minecraft.command.argument.BlockPosArgumentType; -import net.minecraft.command.argument.BlockPredicateArgumentType; -import net.minecraft.command.argument.BlockStateArgument; -import net.minecraft.command.argument.BlockStateArgumentType; -import net.minecraft.command.argument.ColorArgumentType; -import net.minecraft.command.argument.ColumnPosArgumentType; -import net.minecraft.command.argument.DimensionArgumentType; -import net.minecraft.command.argument.EntityAnchorArgumentType; -import net.minecraft.command.argument.EntityArgumentType; -import net.minecraft.command.argument.EntitySummonArgumentType; -import net.minecraft.command.argument.GameProfileArgumentType; -import net.minecraft.command.argument.IdentifierArgumentType; -import net.minecraft.command.argument.EnchantmentArgumentType; -import net.minecraft.command.argument.ItemSlotArgumentType; -import net.minecraft.command.argument.ItemStackArgumentType; -import net.minecraft.command.argument.MessageArgumentType; -import net.minecraft.command.argument.StatusEffectArgumentType; -import net.minecraft.command.argument.NbtCompoundArgumentType; -import net.minecraft.command.argument.NbtPathArgumentType; -import net.minecraft.command.argument.NbtElementArgumentType; -import net.minecraft.command.argument.NumberRangeArgumentType; -import net.minecraft.command.argument.ScoreboardObjectiveArgumentType; -import net.minecraft.command.argument.ScoreboardCriterionArgumentType; -import net.minecraft.command.argument.ParticleEffectArgumentType; -import net.minecraft.command.argument.RotationArgumentType; -import net.minecraft.command.argument.ScoreHolderArgumentType; -import net.minecraft.command.argument.ScoreboardSlotArgumentType; -import net.minecraft.command.argument.SwizzleArgumentType; -import net.minecraft.command.argument.TeamArgumentType; -import net.minecraft.command.argument.TimeArgumentType; -import net.minecraft.command.argument.UuidArgumentType; -import net.minecraft.command.argument.Vec2ArgumentType; -import net.minecraft.command.argument.Vec3ArgumentType; -import net.minecraft.command.suggestion.SuggestionProviders; -import net.minecraft.entity.Entity; -import net.minecraft.predicate.NumberRange; -import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.server.command.BossBarCommand; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.text.LiteralText; -import net.minecraft.util.Formatting; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.registry.Registry; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -100,14 +50,60 @@ import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; +import net.minecraft.ChatFormatting; +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.critereon.MinMaxBounds; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.commands.arguments.AngleArgument; +import net.minecraft.commands.arguments.ColorArgument; +import net.minecraft.commands.arguments.CompoundTagArgument; +import net.minecraft.commands.arguments.DimensionArgument; +import net.minecraft.commands.arguments.EntityAnchorArgument; +import net.minecraft.commands.arguments.EntitySummonArgument; +import net.minecraft.commands.arguments.GameProfileArgument; +import net.minecraft.commands.arguments.ItemEnchantmentArgument; +import net.minecraft.commands.arguments.MessageArgument; +import net.minecraft.commands.arguments.MobEffectArgument; +import net.minecraft.commands.arguments.NbtPathArgument; +import net.minecraft.commands.arguments.NbtTagArgument; +import net.minecraft.commands.arguments.ObjectiveArgument; +import net.minecraft.commands.arguments.ObjectiveCriteriaArgument; +import net.minecraft.commands.arguments.ParticleArgument; +import net.minecraft.commands.arguments.RangeArgument; +import net.minecraft.commands.arguments.ResourceLocationArgument; +import net.minecraft.commands.arguments.ScoreHolderArgument; +import net.minecraft.commands.arguments.ScoreboardSlotArgument; +import net.minecraft.commands.arguments.TeamArgument; +import net.minecraft.commands.arguments.TimeArgument; +import net.minecraft.commands.arguments.UuidArgument; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.commands.arguments.blocks.BlockPredicateArgument; +import net.minecraft.commands.arguments.blocks.BlockStateArgument; +import net.minecraft.commands.arguments.coordinates.ColumnPosArgument; +import net.minecraft.commands.arguments.coordinates.RotationArgument; +import net.minecraft.commands.arguments.coordinates.SwizzleArgument; +import net.minecraft.commands.arguments.coordinates.Vec2Argument; +import net.minecraft.commands.arguments.coordinates.Vec3Argument; +import net.minecraft.commands.arguments.item.ItemArgument; +import net.minecraft.commands.synchronization.SuggestionProviders; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.commands.BossBarCommands; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.scores.Scoreboard; -import static net.minecraft.server.command.CommandManager.argument; +import static net.minecraft.commands.Commands.argument; public abstract class CommandArgument { public static CommandSyntaxException error(String text) { - return new SimpleCommandExceptionType(new LiteralText(text)).create(); + return new SimpleCommandExceptionType(new TextComponent(text)).create(); } private static final List baseTypes = Lists.newArrayList( @@ -120,107 +116,107 @@ public abstract class CommandArgument new FloatArgument(), new IntArgument(), new WordArgument(), new GreedyStringArgument(), - new VanillaUnconfigurableArgument( "yaw", AngleArgumentType::angle, // angle - (c, p) -> new NumericValue(AngleArgumentType.getAngle(c, p)), true + new VanillaUnconfigurableArgument( "yaw", AngleArgument::angle, // angle + (c, p) -> new NumericValue(AngleArgument.getAngle(c, p)), true ), new BlockPosArgument(), - new VanillaUnconfigurableArgument( "block", BlockStateArgumentType::blockState, + new VanillaUnconfigurableArgument( "block", BlockStateArgument::block, (c, p) -> { - BlockStateArgument result = BlockStateArgumentType.getBlockState(c, p); - return new BlockValue(result.getBlockState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() ); + BlockInput result = BlockStateArgument.getBlock(c, p); + return new BlockValue(result.getState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() ); }, false ), - new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgumentType::blockPredicate, - (c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().getTagManager(), BlockPredicateArgumentType.getBlockPredicate(c, p)), false + new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgument::blockPredicate, + (c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().getTags(), BlockPredicateArgument.getBlockPredicate(c, p)), false ), - new VanillaUnconfigurableArgument("teamcolor", ColorArgumentType::color, + new VanillaUnconfigurableArgument("teamcolor", ColorArgument::color, (c, p) -> { - Formatting format = ColorArgumentType.getColor(c, p); - return ListValue.of(StringValue.of(format.getName()), ValueConversions.ofRGB(format.getColorValue())); + ChatFormatting format = ColorArgument.getColor(c, p); + return ListValue.of(StringValue.of(format.getName()), ValueConversions.ofRGB(format.getColor())); }, false ), - new VanillaUnconfigurableArgument("columnpos", ColumnPosArgumentType::columnPos, - (c, p) -> ValueConversions.of(ColumnPosArgumentType.getColumnPos(c, p)), false + new VanillaUnconfigurableArgument("columnpos", ColumnPosArgument::columnPos, + (c, p) -> ValueConversions.of(ColumnPosArgument.getColumnPos(c, p)), false ), // component // raw json - new VanillaUnconfigurableArgument("dimension", DimensionArgumentType::dimension, - (c, p) -> ValueConversions.of(DimensionArgumentType.getDimensionArgument(c, p)), false + new VanillaUnconfigurableArgument("dimension", DimensionArgument::dimension, + (c, p) -> ValueConversions.of(DimensionArgument.getDimension(c, p)), false ), new EntityArgument(), - new VanillaUnconfigurableArgument("anchor", EntityAnchorArgumentType::entityAnchor, - (c, p) -> StringValue.of(EntityAnchorArgumentType.getEntityAnchor(c, p).name()), false + new VanillaUnconfigurableArgument("anchor", EntityAnchorArgument::anchor, + (c, p) -> StringValue.of(EntityAnchorArgument.getAnchor(c, p).name()), false ), - new VanillaUnconfigurableArgument("entitytype", EntitySummonArgumentType::entitySummon, - (c, p) -> ValueConversions.of(EntitySummonArgumentType.getEntitySummon(c, p)), SuggestionProviders.SUMMONABLE_ENTITIES + new VanillaUnconfigurableArgument("entitytype", EntitySummonArgument::id, + (c, p) -> ValueConversions.of(EntitySummonArgument.getSummonableEntity(c, p)), SuggestionProviders.SUMMONABLE_ENTITIES ), - new VanillaUnconfigurableArgument("floatrange", NumberRangeArgumentType::floatRange, - (c, p) -> ValueConversions.of(c.getArgument(p, NumberRange.FloatRange.class)), true + new VanillaUnconfigurableArgument("floatrange", RangeArgument::floatRange, + (c, p) -> ValueConversions.of(c.getArgument(p, MinMaxBounds.Doubles.class)), true ), // function?? new PlayerProfileArgument(), - new VanillaUnconfigurableArgument("intrange", NumberRangeArgumentType::intRange, - (c, p) -> ValueConversions.of(NumberRangeArgumentType.IntRangeArgumentType.getRangeArgument(c, p)), true + new VanillaUnconfigurableArgument("intrange", RangeArgument::intRange, + (c, p) -> ValueConversions.of(RangeArgument.Ints.getRange(c, p)), true ), - new VanillaUnconfigurableArgument("enchantment", EnchantmentArgumentType::enchantment, - (c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getId(EnchantmentArgumentType.getEnchantment(c, p))), false + new VanillaUnconfigurableArgument("enchantment", ItemEnchantmentArgument::enchantment, + (c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getKey(ItemEnchantmentArgument.getEnchantment(c, p))), false ), // item_predicate ?? //same as item but accepts tags, not sure right now new SlotArgument(), - new VanillaUnconfigurableArgument("item", ItemStackArgumentType::itemStack, - (c, p) -> ValueConversions.of(ItemStackArgumentType.getItemStackArgument(c, p).createStack(1, false)), false + new VanillaUnconfigurableArgument("item", ItemArgument::item, + (c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false)), false ), - new VanillaUnconfigurableArgument("message", MessageArgumentType::message, - (c, p) -> new FormattedTextValue(MessageArgumentType.getMessage(c, p)), true + new VanillaUnconfigurableArgument("message", MessageArgument::message, + (c, p) -> new FormattedTextValue(MessageArgument.getMessage(c, p)), true ), - new VanillaUnconfigurableArgument("effect", StatusEffectArgumentType::statusEffect, - (c, p) -> ValueConversions.of(Registry.STATUS_EFFECT.getId(StatusEffectArgumentType.getStatusEffect(c, p))),false + new VanillaUnconfigurableArgument("effect", MobEffectArgument::effect, + (c, p) -> ValueConversions.of(Registry.MOB_EFFECT.getKey(MobEffectArgument.getEffect(c, p))),false ), new TagArgument(), // for nbt_compound_tag and nbt_tag - new VanillaUnconfigurableArgument("path", NbtPathArgumentType::nbtPath, - (c, p) -> StringValue.of(NbtPathArgumentType.getNbtPath(c, p).toString()), true + new VanillaUnconfigurableArgument("path", NbtPathArgument::nbtPath, + (c, p) -> StringValue.of(NbtPathArgument.getPath(c, p).toString()), true ), - new VanillaUnconfigurableArgument("objective", ScoreboardObjectiveArgumentType::scoreboardObjective, - (c, p) -> ValueConversions.of(ScoreboardObjectiveArgumentType.getObjective(c, p)), false + new VanillaUnconfigurableArgument("objective", ObjectiveArgument::objective, + (c, p) -> ValueConversions.of(ObjectiveArgument.getObjective(c, p)), false ), - new VanillaUnconfigurableArgument("criterion", ScoreboardCriterionArgumentType::scoreboardCriterion, - (c, p) -> StringValue.of(ScoreboardCriterionArgumentType.getCriterion(c, p).getName()), false + new VanillaUnconfigurableArgument("criterion", ObjectiveCriteriaArgument::criteria, + (c, p) -> StringValue.of(ObjectiveCriteriaArgument.getCriteria(c, p).getName()), false ), // operation // not sure if we need it, you have scarpet for that - new VanillaUnconfigurableArgument("particle", ParticleEffectArgumentType::particleEffect, - (c, p) -> ValueConversions.of(ParticleEffectArgumentType.getParticle(c, p)), false + new VanillaUnconfigurableArgument("particle", ParticleArgument::particle, + (c, p) -> ValueConversions.of(ParticleArgument.getParticle(c, p)), false ), // resource / identifier section - new VanillaUnconfigurableArgument("recipe", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getRecipeArgument(c, p).getId()), SuggestionProviders.ALL_RECIPES + new VanillaUnconfigurableArgument("recipe", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getRecipe(c, p).getId()), SuggestionProviders.ALL_RECIPES ), - new VanillaUnconfigurableArgument("advancement", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getAdvancementArgument(c, p).getId()), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getAdvancementLoader().getAdvancements().stream().map(Advancement::getId), builder) + new VanillaUnconfigurableArgument("advancement", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) ), - new VanillaUnconfigurableArgument("lootcondition", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getId(IdentifierArgumentType.getPredicateArgument(c, p).getType())), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getPredicateManager().getIds(), builder) + new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) ), - new VanillaUnconfigurableArgument("loottable", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getLootManager().getTableIds(), builder) + new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) ), - new VanillaUnconfigurableArgument("attribute", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getId(IdentifierArgumentType.getAttributeArgument(c, p))), (ctx, builder) -> CommandSource.suggestIdentifiers(Registry.ATTRIBUTE.getIds(), builder) + new VanillaUnconfigurableArgument("attribute", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getKey(ResourceLocationArgument.getAttribute(c, p))), (ctx, builder) -> SharedSuggestionProvider.suggestResource(Registry.ATTRIBUTE.keySet(), builder) ), - new VanillaUnconfigurableArgument("boss", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), BossBarCommand.SUGGESTION_PROVIDER + new VanillaUnconfigurableArgument("boss", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), BossBarCommands.SUGGEST_BOSS_BAR ), - new VanillaUnconfigurableArgument("biome", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), SuggestionProviders.ALL_BIOMES + new VanillaUnconfigurableArgument("biome", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_BIOMES ), - new VanillaUnconfigurableArgument("sound", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), SuggestionProviders.AVAILABLE_SOUNDS + new VanillaUnconfigurableArgument("sound", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_SOUNDS ), - new VanillaUnconfigurableArgument("storekey", IdentifierArgumentType::identifier, - (c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getDataCommandStorage().getIds(), builder) + new VanillaUnconfigurableArgument("storekey", ResourceLocationArgument::id, + (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getCommandStorage().keys(), builder) ), // default @@ -229,32 +225,32 @@ public abstract class CommandArgument // end resource / identifier // I would be great if you guys have suggestions for that. new VanillaUnconfigurableArgument("rotation", - RotationArgumentType::rotation, + RotationArgument::rotation, (c, p) -> { - Vec2f rot = RotationArgumentType.getRotation(c, p).toAbsoluteRotation(c.getSource()); + Vec2 rot = RotationArgument.getRotation(c, p).getRotation(c.getSource()); return ListValue.of(new NumericValue(rot.x), new NumericValue(rot.y)); }, true ), new ScoreholderArgument(), - new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgumentType::scoreboardSlot, - (c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgumentType.getScoreboardSlot(c, p))), false + new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot, + (c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgument.getDisplaySlot(c, p))), false ), - new VanillaUnconfigurableArgument("swizzle", SwizzleArgumentType::swizzle, - (c, p) -> StringValue.of(SwizzleArgumentType.getSwizzle(c, p).stream().map(Direction.Axis::asString).collect(Collectors.joining())), true + new VanillaUnconfigurableArgument("swizzle", SwizzleArgument::swizzle, + (c, p) -> StringValue.of(SwizzleArgument.getSwizzle(c, p).stream().map(Direction.Axis::getSerializedName).collect(Collectors.joining())), true ), - new VanillaUnconfigurableArgument("team", TeamArgumentType::team, - (c, p) -> StringValue.of(TeamArgumentType.getTeam(c, p).getName()), false + new VanillaUnconfigurableArgument("team", TeamArgument::team, + (c, p) -> StringValue.of(TeamArgument.getTeam(c, p).getName()), false ), - new VanillaUnconfigurableArgument("time", TimeArgumentType::time, + new VanillaUnconfigurableArgument("time", TimeArgument::time, (c, p) -> new NumericValue(IntegerArgumentType.getInteger(c, p)), false ), - new VanillaUnconfigurableArgument("uuid", UuidArgumentType::uuid, - (c, p) -> StringValue.of(UuidArgumentType.getUuid(c, p).toString()), false + new VanillaUnconfigurableArgument("uuid", UuidArgument::uuid, + (c, p) -> StringValue.of(UuidArgument.getUuid(c, p).toString()), false ), - new VanillaUnconfigurableArgument("surfacelocation", Vec2ArgumentType::vec2, // vec2 + new VanillaUnconfigurableArgument("surfacelocation", Vec2Argument::vec2, // vec2 (c, p) -> { - Vec2f res = Vec2ArgumentType.getVec2(c, p); + Vec2 res = Vec2Argument.getVec2(c, p); return ListValue.of(NumericValue.of(res.x), NumericValue.of(res.y)); }, false @@ -281,7 +277,7 @@ public abstract class CommandArgument return DEFAULT; } - public static RequiredArgumentBuilder argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException + public static RequiredArgumentBuilder argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException { CommandArgument arg = getTypeForArgument(param, host); if (arg.suggestionProvider != null) return argument(param, arg.getArgumentType()).suggests(arg.suggestionProvider); @@ -297,7 +293,7 @@ public abstract class CommandArgument protected Collection examples; protected boolean needsMatching; protected boolean caseSensitive = true; - protected SuggestionProvider suggestionProvider; + protected SuggestionProvider suggestionProvider; protected FunctionArgument customSuggester; @@ -314,12 +310,12 @@ public abstract class CommandArgument protected abstract ArgumentType getArgumentType() throws CommandSyntaxException; - public static Value getValue(CommandContext context, String param, CarpetScriptHost host) throws CommandSyntaxException + public static Value getValue(CommandContext context, String param, CarpetScriptHost host) throws CommandSyntaxException { return getTypeForArgument(param, host).getValueFromContext(context, param); } - protected abstract Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException; + protected abstract Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException; public String getTypeSuffix() { @@ -359,7 +355,7 @@ public abstract class CommandArgument } public CompletableFuture suggest( - CommandContext context, + CommandContext context, SuggestionsBuilder suggestionsBuilder, CarpetScriptHost host ) throws CommandSyntaxException @@ -370,20 +366,20 @@ public abstract class CommandArgument return suggestionsBuilder.buildFuture(); } - protected List suggestFor(CommandContext context, String prefix, CarpetScriptHost host) throws CommandSyntaxException + protected List suggestFor(CommandContext context, String prefix, CarpetScriptHost host) throws CommandSyntaxException { return getOptions(context, host).stream().filter(s -> optionMatchesPrefix(prefix, s)).collect(Collectors.toList()); } - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { if (customSuggester != null) { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); Map params = new HashMap<>(); - for(ParsedCommandNode pnode : context.getNodes()) + for(ParsedCommandNode pnode : context.getNodes()) { - CommandNode node = pnode.getNode(); + CommandNode node = pnode.getNode(); if (node instanceof ArgumentCommandNode) { params.put(StringValue.of(node.getName()), CommandArgument.getValue(context, node.getName(), host)); @@ -437,13 +433,13 @@ public abstract class CommandArgument } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { String choseValue = StringArgumentType.getString(context, param); if (!caseSensitive) choseValue = choseValue.toLowerCase(Locale.ROOT); if (!validOptions.isEmpty() && !validOptions.contains(choseValue)) { - throw new SimpleCommandExceptionType(new LiteralText("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); } return StringValue.of(choseValue); } @@ -463,7 +459,7 @@ public abstract class CommandArgument } @Override - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { return validOptions.isEmpty()?super.getOptions(context, host):validOptions; } @@ -496,21 +492,21 @@ public abstract class CommandArgument private BlockPosArgument() { - super("pos", BlockPosArgumentType.blockPos().getExamples(), false); + super("pos", net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos().getExamples(), false); } @Override public ArgumentType getArgumentType() { - return BlockPosArgumentType.blockPos(); + return net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos(); } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { BlockPos pos = mustBeLoaded - ? BlockPosArgumentType.getLoadedBlockPos(context, param) - : BlockPosArgumentType.getBlockPos(context, param); + ? net.minecraft.commands.arguments.coordinates.BlockPosArgument.getLoadedBlockPos(context, param) + : net.minecraft.commands.arguments.coordinates.BlockPosArgument.getSpawnablePos(context, param); return ValueConversions.of(pos); } @@ -534,19 +530,19 @@ public abstract class CommandArgument private LocationArgument() { - super("location", Vec3ArgumentType.vec3().getExamples(), false); + super("location", Vec3Argument.vec3().getExamples(), false); blockCentered = true; } @Override protected ArgumentType getArgumentType() { - return Vec3ArgumentType.vec3(blockCentered); + return Vec3Argument.vec3(blockCentered); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - return ValueConversions.of(Vec3ArgumentType.getVec3(context, param)); + return ValueConversions.of(Vec3Argument.getVec3(context, param)); } @Override @@ -570,7 +566,7 @@ public abstract class CommandArgument private EntityArgument() { - super("entities", EntityArgumentType.entities().getExamples(), false); + super("entities", net.minecraft.commands.arguments.EntityArgument.entities().getExamples(), false); onlyFans = false; single = false; } @@ -579,22 +575,22 @@ public abstract class CommandArgument { if (onlyFans) { - return single?EntityArgumentType.player():EntityArgumentType.players(); + return single?net.minecraft.commands.arguments.EntityArgument.player():net.minecraft.commands.arguments.EntityArgument.players(); } else { - return single?EntityArgumentType.entity():EntityArgumentType.entities(); + return single?net.minecraft.commands.arguments.EntityArgument.entity():net.minecraft.commands.arguments.EntityArgument.entities(); } } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - Collection founds = EntityArgumentType.getOptionalEntities(context, param); + Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param); if (!single) return ListValue.wrap(founds.stream().map(EntityValue::new).collect(Collectors.toList())); if (founds.size() == 0) return Value.NULL; if (founds.size() == 1) return new EntityValue(founds.iterator().next()); - throw new SimpleCommandExceptionType(new LiteralText("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create(); } @Override @@ -618,24 +614,24 @@ public abstract class CommandArgument private PlayerProfileArgument() { - super("players", GameProfileArgumentType.gameProfile().getExamples(), false); + super("players", GameProfileArgument.gameProfile().getExamples(), false); single = false; } @Override protected ArgumentType getArgumentType() { - return GameProfileArgumentType.gameProfile(); + return GameProfileArgument.gameProfile(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - Collection profiles = GameProfileArgumentType.getProfileArgument(context, param); + Collection profiles = GameProfileArgument.getGameProfiles(context, param); if (!single) return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName())).collect(Collectors.toList())); int size = profiles.size(); if (size == 0) return Value.NULL; if (size == 1) return StringValue.of(profiles.iterator().next().getName()); - throw new SimpleCommandExceptionType(new LiteralText("Multiple game profiles returned while only one was requested"+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Multiple game profiles returned while only one was requested"+" for custom type "+suffix)).create(); } @Override @@ -658,25 +654,25 @@ public abstract class CommandArgument private ScoreholderArgument() { - super("scoreholder", ScoreHolderArgumentType.scoreHolder().getExamples(), false); + super("scoreholder", ScoreHolderArgument.scoreHolder().getExamples(), false); single = false; - suggestionProvider = ScoreHolderArgumentType.SUGGESTION_PROVIDER; + suggestionProvider = ScoreHolderArgument.SUGGEST_SCORE_HOLDERS; } @Override protected ArgumentType getArgumentType() { - return single?ScoreHolderArgumentType.scoreHolder():ScoreHolderArgumentType.scoreHolders(); + return single?ScoreHolderArgument.scoreHolder():ScoreHolderArgument.scoreHolders(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - Collection holders = ScoreHolderArgumentType.getScoreHolders(context, param); + Collection holders = ScoreHolderArgument.getNames(context, param); if (!single) return ListValue.wrap(holders.stream().map(StringValue::of).collect(Collectors.toList())); int size = holders.size(); if (size == 0) return Value.NULL; if (size == 1) return StringValue.of(holders.iterator().next()); - throw new SimpleCommandExceptionType(new LiteralText("Multiple score holders returned while only one was requested"+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Multiple score holders returned while only one was requested"+" for custom type "+suffix)).create(); } @Override @@ -698,22 +694,22 @@ public abstract class CommandArgument boolean mapRequired; private TagArgument() { - super("tag", NbtCompoundArgumentType.nbtCompound().getExamples(), false); + super("tag", CompoundTagArgument.compoundTag().getExamples(), false); mapRequired = true; } @Override protected ArgumentType getArgumentType() { - return mapRequired?NbtCompoundArgumentType.nbtCompound(): NbtElementArgumentType.nbtElement(); + return mapRequired?CompoundTagArgument.compoundTag(): NbtTagArgument.nbtTag(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { if (mapRequired) - return new NBTSerializableValue(NbtCompoundArgumentType.getNbtCompound(context, param)); + return new NBTSerializableValue(CompoundTagArgument.getCompoundTag(context, param)); else - return new NBTSerializableValue(NbtElementArgumentType.getNbtElement(context, param)); + return new NBTSerializableValue(NbtTagArgument.getNbtTag(context, param)); } @Override @@ -732,7 +728,7 @@ public abstract class CommandArgument private static class CustomIdentifierArgument extends CommandArgument { - Set validOptions = Collections.emptySet(); + Set validOptions = Collections.emptySet(); protected CustomIdentifierArgument() { @@ -742,16 +738,16 @@ public abstract class CommandArgument @Override protected ArgumentType getArgumentType() { - return IdentifierArgumentType.identifier(); + return ResourceLocationArgument.id(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - Identifier choseValue = IdentifierArgumentType.getIdentifier(context, param); + ResourceLocation choseValue = ResourceLocationArgument.getId(context, param); if (!validOptions.isEmpty() && !validOptions.contains(choseValue)) { - throw new SimpleCommandExceptionType(new LiteralText("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); } return ValueConversions.of(choseValue); } @@ -770,7 +766,7 @@ public abstract class CommandArgument { Value optionsValue = config.get("options"); if (!(optionsValue instanceof ListValue)) throw error("Custom sting type requires options passed as a list"+" for custom type "+suffix); - validOptions = ((ListValue) optionsValue).getItems().stream().map(v -> new Identifier(v.getString())).collect(Collectors.toSet()); + validOptions = ((ListValue) optionsValue).getItems().stream().map(v -> new ResourceLocation(v.getString())).collect(Collectors.toSet()); } } } @@ -799,7 +795,7 @@ public abstract class CommandArgument } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { return new NumericValue(DoubleArgumentType.getDouble(context, param)); } @@ -850,7 +846,7 @@ public abstract class CommandArgument } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { return new NumericValue(LongArgumentType.getLong(context, param)); } @@ -926,22 +922,22 @@ public abstract class CommandArgument protected SlotArgument() { - super("slot", ItemSlotArgumentType.itemSlot().getExamples(), false); + super("slot", net.minecraft.commands.arguments.SlotArgument.slot().getExamples(), false); } @Override protected ArgumentType getArgumentType() throws CommandSyntaxException { - return ItemSlotArgumentType.itemSlot(); + return net.minecraft.commands.arguments.SlotArgument.slot(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - int slot = ItemSlotArgumentType.getItemSlot(context, param); + int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param); if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).numericalIds().contains(slot)) { - throw new SimpleCommandExceptionType(new LiteralText("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(new TextComponent("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create(); } return ValueConversions.ofVanillaSlotResult(slot); } @@ -960,7 +956,7 @@ public abstract class CommandArgument } @Override - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { return restrict==null?super.getOptions(context, host):RESTRICTED_CONTAINERS.get(restrict).commandIds(); } @@ -975,7 +971,7 @@ public abstract class CommandArgument @FunctionalInterface private interface ValueExtractor { - Value apply(CommandContext ctx, String param) throws CommandSyntaxException; + Value apply(CommandContext ctx, String param) throws CommandSyntaxException; } @FunctionalInterface @@ -1013,7 +1009,7 @@ public abstract class CommandArgument String suffix, ArgumentProvider argumentTypeSupplier, ValueExtractor valueExtractor, - SuggestionProvider suggester + SuggestionProvider suggester ) { super(suffix, Collections.emptyList(), false); @@ -1030,7 +1026,7 @@ public abstract class CommandArgument } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { return valueExtractor.apply(context, param); } diff --git a/src/main/java/carpet/script/command/CommandToken.java b/src/main/java/carpet/script/command/CommandToken.java index 3949e39b..257ac8c2 100644 --- a/src/main/java/carpet/script/command/CommandToken.java +++ b/src/main/java/carpet/script/command/CommandToken.java @@ -5,15 +5,14 @@ import carpet.script.value.FunctionValue; import com.google.common.collect.Lists; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.server.command.ServerCommandSource; - import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.minecraft.commands.CommandSourceStack; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.literal; public class CommandToken implements Comparable { @@ -71,7 +70,7 @@ public class CommandToken implements Comparable } - public ArgumentBuilder getCommandNode(CarpetScriptHost host) throws CommandSyntaxException + public ArgumentBuilder getCommandNode(CarpetScriptHost host) throws CommandSyntaxException { if (isArgument) return CommandArgument.argumentNode(surface, host); diff --git a/src/main/java/carpet/script/exception/CarpetExpressionException.java b/src/main/java/carpet/script/exception/CarpetExpressionException.java index 969b1ea5..7d3e79c6 100644 --- a/src/main/java/carpet/script/exception/CarpetExpressionException.java +++ b/src/main/java/carpet/script/exception/CarpetExpressionException.java @@ -2,9 +2,8 @@ package carpet.script.exception; import carpet.script.value.FunctionValue; import carpet.utils.Messenger; -import net.minecraft.server.command.ServerCommandSource; - import java.util.List; +import net.minecraft.commands.CommandSourceStack; public class CarpetExpressionException extends RuntimeException implements ResolvedException { @@ -15,7 +14,7 @@ public class CarpetExpressionException extends RuntimeException implements Resol super(message); this.stack = stack; } - public void printStack(ServerCommandSource source) + public void printStack(CommandSourceStack source) { if (stack != null && !stack.isEmpty()) { diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 9075faf3..bffe0913 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -15,10 +15,9 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.command.CommandException; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.WorldSavePath; - +import net.minecraft.commands.CommandRuntimeException; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.world.level.storage.LevelResource; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; @@ -58,7 +57,7 @@ public class AppStoreManager public static class ScarpetAppStoreValidator extends Validator { - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String string) { APP_STORE_ROOT.sealed = false; APP_STORE_ROOT.children = new HashMap<>(); @@ -251,13 +250,13 @@ public class AppStoreManager * @return {@code 1} if we succesfully saved the script, {@code 0} otherwise */ - public static int downloadScript(ServerCommandSource source, String path) + public static int downloadScript(CommandSourceStack source, String path) { AppInfo nodeInfo = getFileNode(path); return downloadScript(source, path, nodeInfo, false); } - private static int downloadScript(ServerCommandSource source, String path, AppInfo nodeInfo, boolean useTrash) + private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash) { String code; try @@ -266,7 +265,7 @@ public class AppStoreManager } catch (IOException e) { - throw new CommandException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage())); + throw new CommandRuntimeException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage())); } if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) return 0; boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); @@ -297,21 +296,21 @@ public class AppStoreManager } catch (IOException e) { - throw new CommandException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage())); + throw new CommandRuntimeException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage())); } } - public static boolean saveScriptToFile(ServerCommandSource source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) + public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) { Path scriptLocation; - if (globalSavePath && !source.getServer().isDedicated()) // never happens, this is always called with globalSavePath being false + if (globalSavePath && !source.getServer().isDedicatedServer()) // never happens, this is always called with globalSavePath being false { //cos config folder only is in clients scriptLocation = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts/appstore").toAbsolutePath().resolve(path); } else { - scriptLocation = source.getServer().getSavePath(WorldSavePath.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); + scriptLocation = source.getServer().getWorldPath(LevelResource.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); } try { @@ -463,7 +462,7 @@ public class AppStoreManager { downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true); } - catch (CommandException e) + catch (CommandRuntimeException e) { throw new InternalExpressionException("Error when installing app dependencies: " + e.toString()); } diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java index 0253e184..5f30def1 100644 --- a/src/main/java/carpet/script/utils/BiomeInfo.java +++ b/src/main/java/carpet/script/utils/BiomeInfo.java @@ -7,39 +7,37 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.gen.feature.ConfiguredStructureFeature; - import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; +import net.minecraft.core.Registry; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; public class BiomeInfo { - public final static Map> biomeFeatures = new HashMap>(){{ + public final static Map> biomeFeatures = new HashMap>(){{ //put("top_material", (w, b) -> new BlockValue( b.getGenerationSettings(). getSurfaceConfig().getTopMaterial(), null, null)); //put("under_material", (w, b) -> new BlockValue( b.getGenerationSettings().getSurfaceConfig().getUnderMaterial(), null, null)); - put("category", (w, b) -> StringValue.of(b.getCategory().getName())); - put("temperature", (w, b) -> NumericValue.of(b.getTemperature())); - put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFogColor())); - put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFoliageColor().orElse(4764952))); // client Biome.getDefaultFoliageColor - put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getSkyColor())); - put("water_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterColor())); - put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterFogColor())); + put("category", (w, b) -> StringValue.of(b.getBiomeCategory().getName())); + put("temperature", (w, b) -> NumericValue.of(b.getBaseTemperature())); + put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFogColor())); + put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFoliageColorOverride().orElse(4764952))); // client Biome.getDefaultFoliageColor + put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getSkyColor())); + put("water_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterColor())); + put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterFogColor())); put("humidity", (w, b) -> NumericValue.of(b.getDownfall())); put("precipitation", (w, b) -> StringValue.of(b.getPrecipitation().getName())); //put("depth", (w, b) -> NumericValue.of(b.getDepth())); //put("scale", (w, b) -> NumericValue.of(b.getScale())); put("features", (w, b) -> { - Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY); + Registry> registry = w.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY); return ListValue.wrap( - b.getGenerationSettings().getFeatures().stream().map(step -> + b.getGenerationSettings().features().stream().map(step -> ListValue.wrap(step.stream().map(cfp -> - ValueConversions.of(registry.getId(((PlacedFeatureInterface)cfp.get()).getRawFeature())) + ValueConversions.of(registry.getKey(((PlacedFeatureInterface)cfp.get()).getRawFeature())) )) ) ); diff --git a/src/main/java/carpet/script/utils/EquipmentInventory.java b/src/main/java/carpet/script/utils/EquipmentInventory.java index 79f9cf68..05543625 100644 --- a/src/main/java/carpet/script/utils/EquipmentInventory.java +++ b/src/main/java/carpet/script/utils/EquipmentInventory.java @@ -1,15 +1,14 @@ package carpet.script.utils; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; - import java.util.Arrays; import java.util.List; +import net.minecraft.world.Container; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; -public class EquipmentInventory implements Inventory +public class EquipmentInventory implements Container { private static final List slotToSlot = Arrays.asList( EquipmentSlot.MAINHAND, @@ -24,7 +23,7 @@ public class EquipmentInventory implements Inventory } @Override - public int size() + public int getContainerSize() { return 6; } @@ -33,12 +32,12 @@ public class EquipmentInventory implements Inventory public boolean isEmpty() { for (EquipmentSlot slot: slotToSlot) - if (!mob.getEquippedStack(slot).isEmpty()) return false; + if (!mob.getItemBySlot(slot).isEmpty()) return false; return true; } @Override - public ItemStack getStack(int slot) + public ItemStack getItem(int slot) { EquipmentSlot slotSlot; try @@ -50,11 +49,11 @@ public class EquipmentInventory implements Inventory //going out of the index should be really exceptional return ItemStack.EMPTY; } - return mob.getEquippedStack(slotSlot); + return mob.getItemBySlot(slotSlot); } @Override - public ItemStack removeStack(int slot, int amount) + public ItemStack removeItem(int slot, int amount) { EquipmentSlot slotSlot; try @@ -66,11 +65,11 @@ public class EquipmentInventory implements Inventory //going out of the index should be really exceptional return ItemStack.EMPTY; } - return mob.getEquippedStack(slotSlot).split(amount); + return mob.getItemBySlot(slotSlot).split(amount); } @Override - public ItemStack removeStack(int slot) + public ItemStack removeItemNoUpdate(int slot) { EquipmentSlot slotSlot; try @@ -82,13 +81,13 @@ public class EquipmentInventory implements Inventory //going out of the index should be really exceptional return ItemStack.EMPTY; } - ItemStack previous = mob.getEquippedStack(slotSlot); - mob.equipStack(slotSlot, ItemStack.EMPTY); + ItemStack previous = mob.getItemBySlot(slotSlot); + mob.setItemSlot(slotSlot, ItemStack.EMPTY); return previous; } @Override - public void setStack(int slot, ItemStack stack) + public void setItem(int slot, ItemStack stack) { EquipmentSlot slotSlot; try @@ -100,25 +99,25 @@ public class EquipmentInventory implements Inventory //going out of the index should be really exceptional return; } - mob.equipStack(slotSlot, stack); + mob.setItemSlot(slotSlot, stack); } @Override - public void markDirty() + public void setChanged() { } @Override - public boolean canPlayerUse(PlayerEntity player) + public boolean stillValid(Player player) { return false; } @Override - public void clear() + public void clearContent() { for (EquipmentSlot slot: slotToSlot) - mob.equipStack(slot, ItemStack.EMPTY); + mob.setItemSlot(slot, ItemStack.EMPTY); } } diff --git a/src/main/java/carpet/script/utils/InputValidator.java b/src/main/java/carpet/script/utils/InputValidator.java index 9c5ff322..3d184ab1 100644 --- a/src/main/java/carpet/script/utils/InputValidator.java +++ b/src/main/java/carpet/script/utils/InputValidator.java @@ -1,11 +1,11 @@ package carpet.script.utils; import carpet.script.exception.InternalExpressionException; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; import org.lwjgl.system.CallbackI; import java.util.Locale; +import net.minecraft.ResourceLocationException; +import net.minecraft.resources.ResourceLocation; public class InputValidator { public static String validateSimpleString(String input, boolean strict) @@ -16,13 +16,13 @@ public class InputValidator { return simplified; } - public static Identifier identifierOf(String string) + public static ResourceLocation identifierOf(String string) { try { - return new Identifier(string); + return new ResourceLocation(string); } - catch (InvalidIdentifierException iie) + catch (ResourceLocationException iie) { throw new InternalExpressionException("Incorrect identifier format '"+string+"': "+iie.getMessage()); } diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index b53e72dd..fea54e76 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -18,31 +18,30 @@ import carpet.script.value.Value; import com.google.common.collect.Sets; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.argument.ParticleEffectArgumentType; -import net.minecraft.entity.Entity; -import net.minecraft.nbt.NbtByte; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtDouble; -import net.minecraft.nbt.NbtFloat; -import net.minecraft.nbt.NbtInt; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.particle.ParticleEffect; +import net.minecraft.commands.arguments.ParticleArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.nbt.FloatTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; -import net.minecraft.util.registry.RegistryKey; - +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -60,13 +59,13 @@ import static java.util.Map.entry; public class ShapeDispatcher { - private static final Map particleCache = new HashMap<>(); + private static final Map particleCache = new HashMap<>(); public static record ShapeWithConfig(ExpiringShape shape, Map config) {} public static ShapeWithConfig fromFunctionArgs( - MinecraftServer server, ServerWorld world, + MinecraftServer server, ServerLevel world, List lv, - Set playerSet + Set playerSet ) { if (lv.size() < 3) throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params"); @@ -93,7 +92,7 @@ public class ShapeDispatcher for (int i=2; i < lv.size(); i++) paramList.add(lv.get(i)); params = ShapeDispatcher.parseParams(paramList); } - params.putIfAbsent("dim", new StringValue(world.getRegistryKey().getValue().toString())); + params.putIfAbsent("dim", new StringValue(world.dimension().location().toString())); params.putIfAbsent("duration", duration); if (params.containsKey("player")) @@ -106,7 +105,7 @@ public class ShapeDispatcher playerVals = Collections.singletonList(players); for (Value pVal : playerVals) { - ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pVal); + ServerPlayer player = EntityValue.getPlayerByValue(server, pVal); if (player == null) throw new InternalExpressionException("'player' parameter needs to represent an existing player, not "+pVal.getString()); playerSet.add(player); @@ -116,11 +115,11 @@ public class ShapeDispatcher return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params); } - public static void sendShape(Collection players, List shapes) + public static void sendShape(Collection players, List shapes) { - List clientPlayers = new ArrayList<>(); - List alternativePlayers = new ArrayList<>(); - for (ServerPlayerEntity player : players) + List clientPlayers = new ArrayList<>(); + List alternativePlayers = new ArrayList<>(); + for (ServerPlayer player : players) { if (ServerNetworkHandler.isValidCarpetPlayer(player)) { @@ -134,7 +133,7 @@ public class ShapeDispatcher if (!clientPlayers.isEmpty()) { - NbtList tag = new NbtList(); + ListTag tag = new ListTag(); int tagcount = 0; for (ShapeWithConfig s : shapes) { @@ -142,30 +141,30 @@ public class ShapeDispatcher if (tagcount++>1000) { tagcount = 0; - NbtElement finalTag = tag; + Tag finalTag = tag; clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); - tag = new NbtList(); + tag = new ListTag(); } } - NbtElement finalTag = tag; + Tag finalTag = tag; if (tag.size() > 0) clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); } if (!alternativePlayers.isEmpty()) { - List> alternatives = new ArrayList<>(); + List> alternatives = new ArrayList<>(); shapes.forEach(s -> alternatives.add(s.shape().alternative())); alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p))); } } - public static ParticleEffect getParticleData(String name) + public static ParticleOptions getParticleData(String name) { - ParticleEffect particle = particleCache.get(name); + ParticleOptions particle = particleCache.get(name); if (particle != null) return particle; try { - particle = ParticleEffectArgumentType.readParameters(new StringReader(name)); + particle = ParticleArgument.readParticle(new StringReader(name)); } catch (CommandSyntaxException e) { @@ -205,10 +204,10 @@ public class ShapeDispatcher } // client - public static ExpiringShape fromTag(NbtCompound tag) + public static ExpiringShape fromTag(CompoundTag tag) { Map options = new HashMap<>(); - for (String key : tag.getKeys()) + for (String key : tag.getAllKeys()) { Param decoder = Param.of.get(key); if (decoder==null) @@ -222,7 +221,7 @@ public class ShapeDispatcher Value shapeValue = options.get("shape"); if (shapeValue == null) { - CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getKeys())); + CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys())); return null; } Function,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); @@ -271,16 +270,16 @@ public class ShapeDispatcher protected String snapTo; protected boolean snapX, snapY, snapZ; protected boolean discreteX, discreteY, discreteZ; - protected RegistryKey shapeDimension; + protected ResourceKey shapeDimension; protected ExpiringShape() { } - public static NbtCompound toTag(Map params) + public static CompoundTag toTag(Map params) { - NbtCompound tag = new NbtCompound(); + CompoundTag tag = new CompoundTag(); params.forEach((k, v) -> { - NbtElement valTag = Param.of.get(k).toTag(v); + Tag valTag = Param.of.get(k).toTag(v); if (valTag != null) tag.put(k, valTag); }); return tag; @@ -325,7 +324,7 @@ public class ShapeDispatcher key = 0; followEntity = -1; - shapeDimension = RegistryKey.of(Registry.WORLD_KEY, new Identifier(options.get("dim").getString())); + shapeDimension = ResourceKey.create(Registry.DIMENSION_REGISTRY, new ResourceLocation(options.get("dim").getString())); if (options.containsKey("follow")) { followEntity = NumericValue.asNumber(options.getOrDefault("follow", optional.get("follow"))).getInt(); @@ -339,33 +338,33 @@ public class ShapeDispatcher } } public int getExpiry() { return duration; } - public Vec3d toAbsolute(Entity e, Vec3d vec, float partialTick) + public Vec3 toAbsolute(Entity e, Vec3 vec, float partialTick) { return vec.add( - snapX?(discreteX ?MathHelper.floor(e.getX()):MathHelper.lerp(partialTick, e.prevX, e.getX())):0.0, - snapY?(discreteY ?MathHelper.floor(e.getY()):MathHelper.lerp(partialTick, e.prevY, e.getY())):0.0, - snapZ?(discreteZ ?MathHelper.floor(e.getZ()):MathHelper.lerp(partialTick, e.prevZ, e.getZ())):0.0 + snapX?(discreteX ?Mth.floor(e.getX()):Mth.lerp(partialTick, e.xo, e.getX())):0.0, + snapY?(discreteY ?Mth.floor(e.getY()):Mth.lerp(partialTick, e.yo, e.getY())):0.0, + snapZ?(discreteZ ?Mth.floor(e.getZ()):Mth.lerp(partialTick, e.zo, e.getZ())):0.0 ); } - public Vec3d relativiseRender(World world, Vec3d vec, float partialTick) + public Vec3 relativiseRender(Level world, Vec3 vec, float partialTick) { if (followEntity < 0) return vec; - Entity e = world.getEntityById(followEntity); + Entity e = world.getEntity(followEntity); if (e == null) return vec; return toAbsolute(e, vec, partialTick); } - public Vec3d vecFromValue(Value value) + public Vec3 vecFromValue(Value value) { if (!(value instanceof ListValue)) throw new InternalExpressionException("decoded value of "+value.getPrettyString()+" is not a triple"); List elements = ((ListValue) value).getItems(); - return new Vec3d( + return new Vec3( NumericValue.asNumber( elements.get(0)).getDouble(), NumericValue.asNumber( elements.get(1)).getDouble(), NumericValue.asNumber( elements.get(2)).getDouble() ); } - protected ParticleEffect replacementParticle() + protected ParticleOptions replacementParticle() { String particleName = fa ==0 ? String.format(Locale.ROOT , "dust %.1f %.1f %.1f 1.0", r, g, b): @@ -374,7 +373,7 @@ public class ShapeDispatcher } - public abstract Consumer alternative(); + public abstract Consumer alternative(); public long key() { if (key!=0) return key; @@ -398,7 +397,7 @@ public class ShapeDispatcher private static final double xdif = new Random().nextDouble(); private static final double ydif = new Random().nextDouble(); private static final double zdif = new Random().nextDouble(); - int vec3dhash(Vec3d vec) + int vec3dhash(Vec3 vec) { return vec.add(xdif, ydif, zdif).hashCode(); } @@ -443,7 +442,7 @@ public class ShapeDispatcher protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } public DisplayedText() { } - Vec3d pos; + Vec3 pos; String text; int textcolor; int textbck; @@ -457,7 +456,7 @@ public class ShapeDispatcher float indent; int align; float height; - Text value; + Component value; boolean doublesided; @Override @@ -520,7 +519,7 @@ public class ShapeDispatcher @Override - public Consumer alternative() + public Consumer alternative() { return s -> {}; } @@ -558,8 +557,8 @@ public class ShapeDispatcher protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } public Box() { } - Vec3d from; - Vec3d to; + Vec3 from; + Vec3 to; @Override protected void init(Map options) @@ -570,20 +569,20 @@ public class ShapeDispatcher } @Override - public Consumer alternative() + public Consumer alternative() { - ParticleEffect particle = replacementParticle(); + ParticleOptions particle = replacementParticle(); double density = Math.max(2.0, from.distanceTo(to) /50/ (a+0.1)) ; return p -> { - if (p.world.getRegistryKey() == shapeDimension) + if (p.level.dimension() == shapeDimension) { particleMesh( Collections.singletonList(p), particle, density, - relativiseRender(p.world, from, 0), - relativiseRender(p.world, to, 0) + relativiseRender(p.level, from, 0), + relativiseRender(p.level, to, 0) ); } }; @@ -599,8 +598,8 @@ public class ShapeDispatcher return hash; } - public static int particleMesh(List playerList, ParticleEffect particle, double density, - Vec3d from, Vec3d to) + public static int particleMesh(List playerList, ParticleOptions particle, double density, + Vec3 from, Vec3 to) { double x1 = from.x; double y1 = from.y; @@ -609,20 +608,20 @@ public class ShapeDispatcher double y2 = to.y; double z2 = to.z; return - drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y2, z1), density)+ - drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x2, y2, z1), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y1, z1), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x1, y1, z1), density)+ + drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y2, z1), density)+ + drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x2, y2, z1), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y1, z1), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x1, y1, z1), density)+ - drawParticleLine(playerList, particle, new Vec3d(x1, y1, z2), new Vec3d(x1, y2, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x1, y2, z2), new Vec3d(x2, y2, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y2, z2), new Vec3d(x2, y1, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y1, z2), new Vec3d(x1, y1, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x1, y1, z2), new Vec3(x1, y2, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x1, y2, z2), new Vec3(x2, y2, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y2, z2), new Vec3(x2, y1, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y1, z2), new Vec3(x1, y1, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y1, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x1, y2, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y2, z2), density)+ - drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x2, y1, z2), density); + drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y1, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x1, y2, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y2, z2), density)+ + drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x2, y1, z2), density); } } @@ -640,8 +639,8 @@ public class ShapeDispatcher super(); } - Vec3d from; - Vec3d to; + Vec3 from; + Vec3 to; @Override protected void init(Map options) @@ -652,17 +651,17 @@ public class ShapeDispatcher } @Override - public Consumer alternative() + public Consumer alternative() { - ParticleEffect particle = replacementParticle(); + ParticleOptions particle = replacementParticle(); double density = Math.max(2.0, from.distanceTo(to) /50) / (a+0.1); return p -> { - if (p.world.getRegistryKey() == shapeDimension) drawParticleLine( + if (p.level.dimension() == shapeDimension) drawParticleLine( Collections.singletonList(p), particle, - relativiseRender(p.world, from, 0), - relativiseRender(p.world, to, 0), + relativiseRender(p.level, from, 0), + relativiseRender(p.level, to, 0), density ); }; @@ -693,7 +692,7 @@ public class ShapeDispatcher super(); } - Vec3d center; + Vec3 center; float radius; int level; int subdivisions; @@ -713,14 +712,14 @@ public class ShapeDispatcher } @Override - public Consumer alternative() { return p -> + public Consumer alternative() { return p -> { - ParticleEffect particle = replacementParticle(); + ParticleOptions particle = replacementParticle(); int partno = Math.min(1000,20*subdivisions); - Random rand = p.world.getRandom(); - ServerWorld world = p.getWorld(); + Random rand = p.level.getRandom(); + ServerLevel world = p.getLevel(); - Vec3d ccenter = relativiseRender(world, center, 0 ); + Vec3 ccenter = relativiseRender(world, center, 0 ); double ccx = ccenter.x; double ccy = ccenter.y; @@ -731,10 +730,10 @@ public class ShapeDispatcher float theta = (float)Math.asin(rand.nextDouble()*2.0-1.0); float phi = (float)(2*Math.PI*rand.nextDouble()); - double x = radius * MathHelper.cos(theta) * MathHelper.cos(phi); - double y = radius * MathHelper.cos(theta) * MathHelper.sin(phi); - double z = radius * MathHelper.sin(theta); - world.spawnParticles(p, particle, true, + double x = radius * Mth.cos(theta) * Mth.cos(phi); + double y = radius * Mth.cos(theta) * Mth.sin(phi); + double z = radius * Mth.sin(theta); + world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); } @@ -764,7 +763,7 @@ public class ShapeDispatcher @Override protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } - Vec3d center; + Vec3 center; float height; float radius; int level; @@ -786,19 +785,19 @@ public class ShapeDispatcher subdivisions = Math.max(10, (int)(10*Math.sqrt(radius))); } height = NumericValue.asNumber(options.getOrDefault("height", optional.get("height"))).getFloat(); - axis = Direction.Axis.fromName(options.getOrDefault("axis", optional.get("axis")).getString()); + axis = Direction.Axis.byName(options.getOrDefault("axis", optional.get("axis")).getString()); } @Override - public Consumer alternative() { return p -> + public Consumer alternative() { return p -> { - ParticleEffect particle = replacementParticle(); + ParticleOptions particle = replacementParticle(); int partno = (int)Math.min(1000,Math.sqrt(20*subdivisions*(1+height))); - Random rand = p.world.getRandom(); - ServerWorld world = p.getWorld(); + Random rand = p.level.getRandom(); + ServerLevel world = p.getLevel(); - Vec3d ccenter = relativiseRender(world, center, 0 ); + Vec3 ccenter = relativiseRender(world, center, 0 ); double ccx = ccenter.x; double ccy = ccenter.y; @@ -810,10 +809,10 @@ public class ShapeDispatcher { float d = rand.nextFloat()*height; float phi = (float)(2*Math.PI*rand.nextDouble()); - double x = radius * MathHelper.cos(phi); + double x = radius * Mth.cos(phi); double y = d; - double z = radius * MathHelper.sin(phi); - world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); + double z = radius * Mth.sin(phi); + world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); } } else if (axis== Direction.Axis.X) @@ -823,9 +822,9 @@ public class ShapeDispatcher float d = rand.nextFloat()*height; float phi = (float)(2*Math.PI*rand.nextDouble()); double x = d; - double y = radius * MathHelper.cos(phi); - double z = radius * MathHelper.sin(phi); - world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); + double y = radius * Mth.cos(phi); + double z = radius * Mth.sin(phi); + world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); } } else // Z @@ -834,10 +833,10 @@ public class ShapeDispatcher { float d = rand.nextFloat()*height; float phi = (float)(2*Math.PI*rand.nextDouble()); - double x = radius * MathHelper.sin(phi); - double y = radius * MathHelper.cos(phi); + double x = radius * Mth.sin(phi); + double y = radius * Mth.cos(phi); double z = d; - world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); + world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0); } } };} @@ -900,9 +899,9 @@ public class ShapeDispatcher this.id = id; } - public abstract NbtElement toTag(Value value); //validates value, returning null if not necessary to keep it and serialize + public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize public abstract Value validate(Map options, MinecraftServer server, Value value); // makes sure the value is proper - public abstract Value decode(NbtElement tag); + public abstract Value decode(Tag tag); } public abstract static class StringParam extends Param @@ -910,9 +909,9 @@ public class ShapeDispatcher protected StringParam(String id) { super(id); } @Override - public NbtElement toTag(Value value) { return NbtString.of(value.getString()); } + public Tag toTag(Value value) { return StringTag.valueOf(value.getString()); } @Override - public Value decode(NbtElement tag) { return new StringValue(tag.asString()); } + public Value decode(Tag tag) { return new StringValue(tag.getAsString()); } } public static class TextParam extends StringParam { @@ -937,22 +936,22 @@ public class ShapeDispatcher public Value validate(Map options, MinecraftServer server, Value value) { if (!(value instanceof FormattedTextValue)) - value = new FormattedTextValue(new LiteralText(value.getString())); + value = new FormattedTextValue(new TextComponent(value.getString())); return value; } @Override - public NbtElement toTag(Value value) + public Tag toTag(Value value) { if (!(value instanceof FormattedTextValue)) - value = new FormattedTextValue(new LiteralText(value.getString())); - return NbtString.of(((FormattedTextValue)value).serialize()); + value = new FormattedTextValue(new TextComponent(value.getString())); + return StringTag.valueOf(((FormattedTextValue)value).serialize()); } @Override - public Value decode(NbtElement tag) + public Value decode(Tag tag) { - return FormattedTextValue.deserialize(tag.asString()); + return FormattedTextValue.deserialize(tag.getAsString()); } } @@ -1015,24 +1014,24 @@ public class ShapeDispatcher } @Override - public NbtElement toTag(Value value) + public Tag toTag(Value value) { - return NbtByte.of(value.getBoolean()); + return ByteTag.valueOf(value.getBoolean()); } @Override - public Value decode(NbtElement tag) + public Value decode(Tag tag) { - return BooleanValue.of(((NbtByte) tag).byteValue() > 0); + return BooleanValue.of(((ByteTag) tag).getAsByte() > 0); } } public static class FloatParam extends NumericParam { protected FloatParam(String id) { super(id); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } + public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); } @Override - public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } } public static abstract class PositiveParam extends NumericParam @@ -1049,27 +1048,27 @@ public class ShapeDispatcher { protected PositiveFloatParam(String id) { super(id); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } + public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); } @Override - public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } } public static class PositiveIntParam extends PositiveParam { protected PositiveIntParam(String id) { super(id); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } + public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); } @Override - public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } } public static class NonNegativeIntParam extends NumericParam { protected NonNegativeIntParam(String id) { super(id); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } + public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); } @Override - public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { Value ret = super.validate(options, server, value); @@ -1081,9 +1080,9 @@ public class ShapeDispatcher { protected NonNegativeFloatParam(String id) { super(id); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); } + public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); } @Override - public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); } + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { Value ret = super.validate(options, server, value); @@ -1149,9 +1148,9 @@ public class ShapeDispatcher } @Override - public Value decode(NbtElement tag) + public Value decode(Tag tag) { - NbtList ctag = (NbtList)tag; + ListTag ctag = (ListTag)tag; return ListValue.of( new NumericValue(ctag.getDouble(0)), new NumericValue(ctag.getDouble(1)), @@ -1159,13 +1158,13 @@ public class ShapeDispatcher ); } @Override - public NbtElement toTag(Value value) + public Tag toTag(Value value) { List lv = ((ListValue)value).getItems(); - NbtList tag = new NbtList(); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); + ListTag tag = new ListTag(); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble())); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble())); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble())); return tag; } } @@ -1188,13 +1187,13 @@ public class ShapeDispatcher } @Override - public Value decode(NbtElement tag) + public Value decode(Tag tag) { - NbtList ltag = (NbtList)tag; + ListTag ltag = (ListTag)tag; List points = new ArrayList<>(); for (int i=0, ll = ltag.size(); i lv = ((ListValue)pointsValue).getItems(); - NbtList ltag = new NbtList(); + ListTag ltag = new ListTag(); for (Value value : lv) { List coords = ((ListValue)value).getItems(); - NbtList tag = new NbtList(); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble())); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble())); - tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble())); + ListTag tag = new ListTag(); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble())); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble())); + tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble())); ltag.add(tag); } return ltag; @@ -1230,9 +1229,9 @@ public class ShapeDispatcher } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } + public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); } @Override - public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } } public static class EntityParam extends Param @@ -1241,47 +1240,47 @@ public class ShapeDispatcher protected EntityParam(String id) { super(id); } @Override - public NbtElement toTag(Value value) + public Tag toTag(Value value) { - return NbtInt.of(NumericValue.asNumber(value, id).getInt()); + return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @Override public Value validate(Map options, MinecraftServer server, Value value) { if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getId()); - ServerPlayerEntity player = EntityValue.getPlayerByValue(server, value); + ServerPlayer player = EntityValue.getPlayerByValue(server, value); if (player == null) throw new InternalExpressionException(id+" parameter needs to represent an entity or player"); return new NumericValue(player.getId()); } @Override - public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } + public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); } } - private static boolean isStraight(Vec3d from, Vec3d to, double density) + private static boolean isStraight(Vec3 from, Vec3 to, double density) { if ( (from.x == to.x && from.y == to.y) || (from.x == to.x && from.z == to.z) || (from.y == to.y && from.z == to.z)) return from.distanceTo(to) / density > 20; return false; } - private static int drawOptimizedParticleLine(List playerList, ParticleEffect particle, Vec3d from, Vec3d to, double density) + private static int drawOptimizedParticleLine(List playerList, ParticleOptions particle, Vec3 from, Vec3 to, double density) { double distance = from.distanceTo(to); int particles = (int)(distance/density); - Vec3d towards = to.subtract(from); + Vec3 towards = to.subtract(from); int parts = 0; - for (ServerPlayerEntity player : playerList) + for (ServerPlayer player : playerList) { - ServerWorld world = player.getWorld(); - world.spawnParticles(player, particle, true, + ServerLevel world = player.getLevel(); + world.sendParticles(player, particle, true, (towards.x)/2+from.x, (towards.y)/2+from.y, (towards.z)/2+from.z, particles/3, towards.x/6, towards.y/6, towards.z/6, 0.0); - world.spawnParticles(player, particle, true, + world.sendParticles(player, particle, true, from.x, from.y, from.z,1,0.0,0.0,0.0,0.0); - world.spawnParticles(player, particle, true, + world.sendParticles(player, particle, true, to.x, to.y, to.z,1,0.0,0.0,0.0,0.0); parts += particles/3+2; } @@ -1290,13 +1289,13 @@ public class ShapeDispatcher { int center = (divider*2)/3; int dev = 2*divider; - for (ServerPlayerEntity player : playerList) + for (ServerPlayer player : playerList) { - ServerWorld world = player.getWorld(); - world.spawnParticles(player, particle, true, + ServerLevel world = player.getLevel(); + world.sendParticles(player, particle, true, (towards.x)/center+from.x, (towards.y)/center+from.y, (towards.z)/center+from.z, particles/divider, towards.x/dev, towards.y/dev, towards.z/dev, 0.0); - world.spawnParticles(player, particle, true, + world.sendParticles(player, particle, true, (towards.x)*(1.0-1.0/center)+from.x, (towards.y)*(1.0-1.0/center)+from.y, (towards.z)*(1.0-1.0/center)+from.z, particles/divider, towards.x/dev, towards.y/dev, towards.z/dev, 0.0); } @@ -1306,22 +1305,22 @@ public class ShapeDispatcher return parts; } - public static int drawParticleLine(List players, ParticleEffect particle, Vec3d from, Vec3d to, double density) + public static int drawParticleLine(List players, ParticleOptions particle, Vec3 from, Vec3 to, double density) { - double distance = from.squaredDistanceTo(to); + double distance = from.distanceToSqr(to); if (distance == 0) return 0; int pcount = 0; if (distance < 100) { - Random rand = players.get(0).world.random; + Random rand = players.get(0).level.random; int particles = (int)(distance/density)+1; - Vec3d towards = to.subtract(from); + Vec3 towards = to.subtract(from); for (int i = 0; i < particles; i++) { - Vec3d at = from.add(towards.multiply( rand.nextDouble())); - for (ServerPlayerEntity player : players) + Vec3 at = from.add(towards.scale( rand.nextDouble())); + for (ServerPlayer player : players) { - player.getWorld().spawnParticles(player, particle, true, + player.getLevel().sendParticles(player, particle, true, at.x, at.y, at.z, 1, 0.0, 0.0, 0.0, 0.0); pcount ++; @@ -1331,15 +1330,15 @@ public class ShapeDispatcher } if (isStraight(from, to, density)) return drawOptimizedParticleLine(players, particle, from, to, density); - Vec3d incvec = to.subtract(from).multiply(2*density/Math.sqrt(distance)); + Vec3 incvec = to.subtract(from).scale(2*density/Math.sqrt(distance)); - for (Vec3d delta = new Vec3d(0.0,0.0,0.0); - delta.lengthSquared(), Long2ObjectOpenHashMap>> shapes; - private final Map, Long2ObjectOpenHashMap>> labels; - private MinecraftClient client; + private final Map, Long2ObjectOpenHashMap>> shapes; + private final Map, Long2ObjectOpenHashMap>> labels; + private Minecraft client; - private Map>> renderedShapes - = new HashMap>>() + private Map>> renderedShapes + = new HashMap>>() {{ put("line", RenderedLine::new); put("box", RenderedBox::new); @@ -44,22 +43,22 @@ public class ShapesRenderer put("label", RenderedText::new); }}; - public ShapesRenderer(MinecraftClient minecraftClient) + public ShapesRenderer(Minecraft minecraftClient) { this.client = minecraftClient; shapes = new HashMap<>(); labels = new HashMap<>(); } - public void render(MatrixStack matrices, Camera camera, float partialTick) + public void render(PoseStack matrices, Camera camera, float partialTick) { CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); //Camera camera = this.client.gameRenderer.getCamera(); - ClientWorld iWorld = this.client.world; - RegistryKey dimensionType = iWorld.getRegistryKey(); + ClientLevel iWorld = this.client.level; + ResourceKey dimensionType = iWorld.dimension(); if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) && (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) return; - long currentTime = client.world.getTime(); + long currentTime = client.level.getGameTime(); RenderSystem.disableTexture(); RenderSystem.enableDepthTest(); RenderSystem.setShader(GameRenderer::getPositionColorShader); @@ -76,21 +75,21 @@ public class ShapesRenderer //RenderSystem.polygonOffset(-3f, -3f); //RenderSystem.enablePolygonOffset(); - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferBuilder = tessellator.getBuffer(); + Tesselator tessellator = Tesselator.getInstance(); + BufferBuilder bufferBuilder = tessellator.getBuilder(); // render - double cameraX = camera.getPos().x; - double cameraY = camera.getPos().y; - double cameraZ = camera.getPos().z; + double cameraX = camera.getPosition().x; + double cameraY = camera.getPosition().y; + double cameraZ = camera.getPosition().z; if (shapes.size() != 0) { synchronized (shapes) { shapes.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) ); - MatrixStack matrixStack = RenderSystem.getModelViewStack(); - matrixStack.push(); - matrixStack.multiplyPositionMatrix(matrices.peek().getPositionMatrix()); + PoseStack matrixStack = RenderSystem.getModelViewStack(); + matrixStack.pushPose(); + matrixStack.mulPoseMatrix(matrices.last().pose()); RenderSystem.applyModelViewMatrix(); // lines @@ -104,7 +103,7 @@ public class ShapesRenderer if (s.shouldRender(dimensionType)) s.renderFaces(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); }); RenderSystem.lineWidth(1.0F); - matrixStack.pop(); + matrixStack.popPose(); RenderSystem.applyModelViewMatrix(); }} @@ -125,7 +124,7 @@ public class ShapesRenderer CarpetProfiler.end_current_section(token); } - public void addShapes(NbtList tag) + public void addShapes(ListTag tag) { CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); for (int i=0, count = tag.size(); i < count; i++) @@ -135,11 +134,11 @@ public class ShapesRenderer CarpetProfiler.end_current_section(token); } - public void addShape(NbtCompound tag) + public void addShape(CompoundTag tag) { ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag); if (shape == null) return; - BiFunction> shapeFactory; + BiFunction> shapeFactory; shapeFactory = renderedShapes.get(tag.getString("shape")); if (shapeFactory == null) { @@ -148,9 +147,9 @@ public class ShapesRenderer else { RenderedShape rshape = shapeFactory.apply(client, shape); - RegistryKey dim = shape.shapeDimension; + ResourceKey dim = shape.shapeDimension; long key = rshape.key(); - Map, Long2ObjectOpenHashMap>> container = + Map, Long2ObjectOpenHashMap>> container = rshape.stageDeux()?labels:shapes; synchronized (container) { @@ -195,15 +194,15 @@ public class ShapesRenderer public abstract static class RenderedShape { protected T shape; - protected MinecraftClient client; + protected Minecraft client; long expiryTick; double renderEpsilon = 0; - public abstract void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ); - public void renderFaces(Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ) {} - protected RenderedShape(MinecraftClient client, T shape) + public abstract void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ); + public void renderFaces(Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick ) {} + protected RenderedShape(Minecraft client, T shape) { this.shape = shape; - expiryTick = client.world.getTime()+shape.getExpiry(); + expiryTick = client.level.getGameTime()+shape.getExpiry(); renderEpsilon = (3+((double)shape.key())/Long.MAX_VALUE)/1000; this.client = client; } @@ -216,12 +215,12 @@ public class ShapesRenderer { return shape.key(); }; - public boolean shouldRender(RegistryKey dim) + public boolean shouldRender(ResourceKey dim) { if (shape.followEntity <=0 ) return true; - if (client.world == null) return false; - if (client.world.getRegistryKey() != dim) return false; - return client.world.getEntityById(shape.followEntity) != null; + if (client.level == null) return false; + if (client.level.dimension() != dim) return false; + return client.level.getEntity(shape.followEntity) != null; } public boolean stageDeux() { @@ -237,28 +236,28 @@ public class ShapesRenderer public static class RenderedText extends RenderedShape { - protected RenderedText(MinecraftClient client, ShapeDispatcher.ExpiringShape shape) + protected RenderedText(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.DisplayedText)shape); } @Override - public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; - Vec3d v1 = shape.relativiseRender(client.world, shape.pos, partialTick); - Camera camera1 = client.gameRenderer.getCamera(); - TextRenderer textRenderer = client.textRenderer; + Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick); + Camera camera1 = client.gameRenderer.getMainCamera(); + Font textRenderer = client.font; if (shape.doublesided) RenderSystem.disableCull(); else RenderSystem.enableCull(); - matrices.push(); + matrices.pushPose(); matrices.translate(v1.x - cx,v1.y - cy,v1.z - cz); if (shape.facing == null) { //matrices.method_34425(new Matrix4f(camera1.getRotation())); - matrices.multiply(camera1.getRotation()); + matrices.mulPose(camera1.rotation()); } else { @@ -267,27 +266,27 @@ public class ShapesRenderer case NORTH: break; case SOUTH: - matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(180)); + matrices.mulPose(Vector3f.YP.rotationDegrees(180)); break; case EAST: - matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(270)); + matrices.mulPose(Vector3f.YP.rotationDegrees(270)); break; case WEST: - matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(90)); + matrices.mulPose(Vector3f.YP.rotationDegrees(90)); break; case UP: - matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(90)); + matrices.mulPose(Vector3f.XP.rotationDegrees(90)); break; case DOWN: - matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(-90)); + matrices.mulPose(Vector3f.XP.rotationDegrees(-90)); break; } } matrices.scale(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); //RenderSystem.scalef(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); - if (shape.tilt!=0.0f) matrices.multiply(Vec3f.POSITIVE_Z.getDegreesQuaternion(shape.tilt)); - if (shape.lean!=0.0f) matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(shape.lean)); - if (shape.turn!=0.0f) matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(shape.turn)); + if (shape.tilt!=0.0f) matrices.mulPose(Vector3f.ZP.rotationDegrees(shape.tilt)); + if (shape.lean!=0.0f) matrices.mulPose(Vector3f.XP.rotationDegrees(shape.lean)); + if (shape.turn!=0.0f) matrices.mulPose(Vector3f.YP.rotationDegrees(shape.turn)); matrices.translate(-10*shape.indent, -10*shape.height-9, (-10*renderEpsilon)-10*shape.raise); //if (visibleThroughWalls) RenderSystem.disableDepthTest(); matrices.scale(-1, 1, 1); @@ -296,16 +295,16 @@ public class ShapesRenderer float text_x = 0; if (shape.align == 0) { - text_x = (float)(-textRenderer.getWidth(shape.value.getString())) / 2.0F; + text_x = (float)(-textRenderer.width(shape.value.getString())) / 2.0F; } else if (shape.align == 1) { - text_x = (float)(-textRenderer.getWidth(shape.value.getString())); + text_x = (float)(-textRenderer.width(shape.value.getString())); } - VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(builder); - textRenderer.draw(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.peek().getPositionMatrix(), immediate, false, shape.textbck, 15728880); - immediate.draw(); - matrices.pop(); + MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); + textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, false, shape.textbck, 15728880); + immediate.endBatch(); + matrices.popPose(); RenderSystem.enableCull(); } @@ -333,17 +332,17 @@ public class ShapesRenderer public static class RenderedBox extends RenderedShape { - private RenderedBox(MinecraftClient client, ShapeDispatcher.ExpiringShape shape) + private RenderedBox(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Box)shape); } @Override - public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; - Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); - Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawBoxWireGLLines(tessellator, bufferBuilder, (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), @@ -352,11 +351,11 @@ public class ShapesRenderer ); } @Override - public void renderFaces(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) return; - Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); - Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); // consider using built-ins //DebugRenderer.drawBox(new Box(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z), 0.5f, 0.5f, 0.5f, 0.5f);//shape.r, shape.g, shape.b, shape.a); drawBoxFaces(tessellator, bufferBuilder, @@ -371,15 +370,15 @@ public class ShapesRenderer public static class RenderedLine extends RenderedShape { - public RenderedLine(MinecraftClient client, ShapeDispatcher.ExpiringShape shape) + public RenderedLine(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Line)shape); } @Override - public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { - Vec3d v1 = shape.relativiseRender(client.world, shape.from, partialTick); - Vec3d v2 = shape.relativiseRender(client.world, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawLine(tessellator, bufferBuilder, (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), @@ -390,25 +389,25 @@ public class ShapesRenderer public static class RenderedSphere extends RenderedShape { - public RenderedSphere(MinecraftClient client, ShapeDispatcher.ExpiringShape shape) + public RenderedSphere(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Sphere)shape); } @Override - public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; - Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereWireframe(tessellator, bufferBuilder, (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), (float)(shape.radius+renderEpsilon), shape.subdivisions, shape.r, shape.g, shape.b, shape.a); } @Override - public void renderFaces(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) return; - Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereFaces(tessellator, bufferBuilder, (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), (float)(shape.radius+renderEpsilon), shape.subdivisions, @@ -418,16 +417,16 @@ public class ShapesRenderer public static class RenderedCylinder extends RenderedShape { - public RenderedCylinder(MinecraftClient client, ShapeDispatcher.ExpiringShape shape) + public RenderedCylinder(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Cylinder)shape); } @Override - public void renderLines(MatrixStack matrices, Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) return; - Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - double dir = MathHelper.sign(shape.height); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + double dir = Mth.sign(shape.height); drawCylinderWireframe(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), (float) (shape.radius + renderEpsilon), (float) (shape.height + 2*dir*renderEpsilon), shape.axis, @@ -436,11 +435,11 @@ public class ShapesRenderer } @Override - public void renderFaces(Tessellator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) return; - Vec3d vc = shape.relativiseRender(client.world, shape.center, partialTick); - double dir = MathHelper.sign(shape.height); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + double dir = Mth.sign(shape.height); drawCylinderFaces(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), (float) (shape.radius + renderEpsilon), (float) (shape.height + 2*dir*renderEpsilon), shape.axis, @@ -451,128 +450,128 @@ public class ShapesRenderer // some raw shit - public static void drawLine(Tessellator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); - builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); - tessellator.draw(); + public static void drawLine(Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha) { + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + tessellator.end(); } public static void drawBoxWireGLLines( - Tessellator tessellator, BufferBuilder builder, + Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, boolean xthick, boolean ythick, boolean zthick, float red1, float grn1, float blu1, float alpha, float red2, float grn2, float blu2) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); if (xthick) { - builder.vertex(x1, y1, z1).color(red1, grn2, blu2, alpha).next(); - builder.vertex(x2, y1, z1).color(red1, grn2, blu2, alpha).next(); + builder.vertex(x1, y1, z1).color(red1, grn2, blu2, alpha).endVertex(); + builder.vertex(x2, y1, z1).color(red1, grn2, blu2, alpha).endVertex(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); } if (ythick) { - builder.vertex(x1, y1, z1).color(red2, grn1, blu2, alpha).next(); - builder.vertex(x1, y2, z1).color(red2, grn1, blu2, alpha).next(); + builder.vertex(x1, y1, z1).color(red2, grn1, blu2, alpha).endVertex(); + builder.vertex(x1, y2, z1).color(red2, grn1, blu2, alpha).endVertex(); - builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); } if (zthick) { - builder.vertex(x1, y1, z1).color(red2, grn2, blu1, alpha).next(); - builder.vertex(x1, y1, z2).color(red2, grn2, blu1, alpha).next(); + builder.vertex(x1, y1, z1).color(red2, grn2, blu1, alpha).endVertex(); + builder.vertex(x1, y1, z2).color(red2, grn2, blu1, alpha).endVertex(); - builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } public static void drawBoxFaces( - Tessellator tessellator, BufferBuilder builder, + Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, boolean xthick, boolean ythick, boolean zthick, float red1, float grn1, float blu1, float alpha) { - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); if (xthick && ythick) { - builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); if (zthick) { - builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); } } if (zthick && ythick) { - builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); if (xthick) { - builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); } } // now at least drawing one if (zthick && xthick) { - builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y1, z2).color(red1, grn1, blu1, alpha).endVertex(); if (ythick) { - builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).next(); - builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).next(); + builder.vertex(x1, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z1).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); + builder.vertex(x1, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); } } - tessellator.draw(); + tessellator.end(); } - public static void drawCylinderWireframe(Tessellator tessellator, BufferBuilder builder, + public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder builder, float cx, float cy, float cz, float r, float h, Direction.Axis axis, int subd, boolean isFlat, float red, float grn, float blu, float alpha) @@ -584,7 +583,7 @@ public class ShapesRenderer float hstep = 1.0f; if (!isFlat) { - hsteps = (int) Math.ceil(MathHelper.abs(h) / (step * r)) + 1; + hsteps = (int) Math.ceil(Mth.abs(h) / (step * r)) + 1; hstep = h / (hsteps - 1); }// draw base @@ -593,48 +592,48 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh*hstep; - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360+1; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); + float x = r * Mth.cos(theta); float y = hh; - float z = r * MathHelper.sin(theta); - builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + float z = r * Mth.sin(theta); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } if (!isFlat) { for (int i = 0; i <= num_steps180; i++) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip float theta = step * i; - float x = r * MathHelper.cos(theta); + float x = r * Mth.cos(theta); - float z = r * MathHelper.sin(theta); + float z = r * Mth.sin(theta); - builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + h, cz - z).color(red, grn, blu, alpha).next(); - builder.vertex(cx - x, cy + h, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); - tessellator.draw(); + builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + h, cz - z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx - x, cy + h, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex(); + tessellator.end(); } } else { - builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx - x, cy, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy, cz - z).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx - x, cy, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy, cz - z).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } } @@ -643,47 +642,47 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh * hstep; - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float z = r * MathHelper.cos(theta); + float z = r * Mth.cos(theta); float x = hh; - float y = r * MathHelper.sin(theta); - builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + float y = r * Mth.sin(theta); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } if (!isFlat) { for (int i = 0; i <= num_steps180; i++) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip float theta = step * i; - float y = r * MathHelper.cos(theta); + float y = r * Mth.cos(theta); - float z = r * MathHelper.sin(theta); + float z = r * Mth.sin(theta); - builder.vertex(cx + 0, cy - y, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + 0, cy + y, cz - z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + h, cy + y, cz - z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + h, cy - y, cz + z).color(red, grn, blu, alpha).next(); - tessellator.draw(); + builder.vertex(cx + 0, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + 0, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + h, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + h, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); + tessellator.end(); } } else { - builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; - float y = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx, cy - y, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx, cy + y, cz - z).color(red, grn, blu, alpha).next(); + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } } else if (axis == Direction.Axis.Z) @@ -691,52 +690,52 @@ public class ShapesRenderer for (int dh = 0; dh < hsteps; dh++) { float hh = dh * hstep; - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float y = r * MathHelper.cos(theta); + float y = r * Mth.cos(theta); float z = hh; - float x = r * MathHelper.sin(theta); - builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.sin(theta); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } if (!isFlat) { for (int i = 0; i <= num_steps180; i++) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip float theta = step * i; - float x = r * MathHelper.cos(theta); + float x = r * Mth.cos(theta); - float y = r * MathHelper.sin(theta); + float y = r * Mth.sin(theta); - builder.vertex(cx + x, cy - y, cz + 0).color(red, grn, blu, alpha).next(); - builder.vertex(cx - x, cy + y, cz + 0).color(red, grn, blu, alpha).next(); - builder.vertex(cx - x, cy + y, cz + h).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy - y, cz + h).color(red, grn, blu, alpha).next(); - tessellator.draw(); + builder.vertex(cx + x, cy - y, cz + 0).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx - x, cy + y, cz + 0).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx - x, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy - y, cz + h).color(red, grn, blu, alpha).endVertex(); + tessellator.end(); } } else { - builder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float y = r * MathHelper.sin(theta); - builder.vertex(cx + x, cy - y, cz).color(red, grn, blu, alpha).next(); - builder.vertex(cx - x, cy + y, cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); + builder.vertex(cx + x, cy - y, cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx - x, cy + y, cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } } } - public static void drawCylinderFaces(Tessellator tessellator, BufferBuilder builder, + public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder builder, float cx, float cy, float cz, float r, float h, Direction.Axis axis, int subd, boolean isFlat, float red, float grn, float blu, float alpha) @@ -748,137 +747,137 @@ public class ShapesRenderer if (axis == Direction.Axis.Y) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(x + cx, cy, z + cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(x + cx, cy, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); if (!isFlat) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx, cy+h, cz).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx, cy+h, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(x + cx, cy+h, z + cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(x + cx, cy+h, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float xp = r * 1; float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).next(); - builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + 0, cz + z).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex(); xp = x; zp = z; } - tessellator.draw(); + tessellator.end(); } } else if (axis == Direction.Axis.X) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float y = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx, cy + y, z + cz).color(red, grn, blu, alpha).next(); + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx, cy + y, z + cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); if (!isFlat) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx+h, cy, cz).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx+h, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float y = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx+h, cy + y, cz + z).color(red, grn, blu, alpha).next(); + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx+h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float yp = r * 1; float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { float theta = step * i; - float y = r * MathHelper.cos(theta); - float z = r * MathHelper.sin(theta); - builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).next(); - builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).next(); - builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).next(); - builder.vertex(cx + 0, cy + y, cz + z).color(red, grn, blu, alpha).next(); + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); + builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + 0, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); yp = y; zp = z; } - tessellator.draw(); + tessellator.end(); } } else if (axis == Direction.Axis.Z) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float y = r * MathHelper.sin(theta); - builder.vertex(x + cx, cy+y, cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); + builder.vertex(x + cx, cy+y, cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); if (!isFlat) { - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - builder.vertex(cx, cy, cz+h).color(red, grn, blu, alpha).next(); + builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + builder.vertex(cx, cy, cz+h).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float y = r * MathHelper.sin(theta); - builder.vertex(x + cx, cy+y, cz+h).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); + builder.vertex(x + cx, cy+y, cz+h).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float xp = r; float yp = 0; for (int i = 1; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.cos(theta); - float y = r * MathHelper.sin(theta); - builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).next(); - builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).next(); - builder.vertex(cx + x, cy + y, cz + 0).color(red, grn, blu, alpha).next(); + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); + builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + x, cy + y, cz + 0).color(red, grn, blu, alpha).endVertex(); xp = x; yp = y; } - tessellator.draw(); + tessellator.end(); } } } - public static void drawSphereWireframe(Tessellator tessellator, BufferBuilder builder, + public static void drawSphereWireframe(Tesselator tessellator, BufferBuilder builder, float cx, float cy, float cz, float r, int subd, float red, float grn, float blu, float alpha) @@ -888,37 +887,37 @@ public class ShapesRenderer int num_steps360 = (int)(2*Math.PI / step)+1; for (int i = 0; i <= num_steps360; i++) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); float theta = step * i ; for (int j = 0; j <= num_steps180; j++) { float phi = step * j ; - float x = r * MathHelper.sin(phi) * MathHelper.cos(theta); - float z = r * MathHelper.sin(phi) * MathHelper.sin(theta); - float y = r * MathHelper.cos(phi); - builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); + builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } for (int j = 0; j <= num_steps180; j++) { - builder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); // line loop to line strip + builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip float phi = step * j ; for (int i = 0; i <= num_steps360; i++) { float theta = step * i; - float x = r * MathHelper.sin(phi) * MathHelper.cos(theta); - float z = r * MathHelper.sin(phi) * MathHelper.sin(theta); - float y = r * MathHelper.cos(phi); - builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); + builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).endVertex(); } - tessellator.draw(); + tessellator.end(); } } - public static void drawSphereFaces(Tessellator tessellator, BufferBuilder builder, + public static void drawSphereFaces(Tesselator tessellator, BufferBuilder builder, float cx, float cy, float cz, float r, int subd, float red, float grn, float blu, float alpha) @@ -931,7 +930,7 @@ public class ShapesRenderer { float theta = i * step; float thetaprime = theta+step; - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); // quad strip to quads + builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float xb = 0; float zb = 0; float xbp = 0; @@ -940,22 +939,22 @@ public class ShapesRenderer for (int j = 0; j <= num_steps180; j++) { float phi = j * step; - float x = r * MathHelper.sin(phi) * MathHelper.cos(theta); - float z = r * MathHelper.sin(phi) * MathHelper.sin(theta); - float y = r * MathHelper.cos(phi); - float xp = r * MathHelper.sin(phi) * MathHelper.cos(thetaprime); - float zp = r * MathHelper.sin(phi) * MathHelper.sin(thetaprime); - builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).next(); - builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).next(); - builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).next(); - builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).next(); + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); + float xp = r * Mth.sin(phi) * Mth.cos(thetaprime); + float zp = r * Mth.sin(phi) * Mth.sin(thetaprime); + builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); xb = x; zb = z; xbp = xp; zbp = zp; yp = y; } - tessellator.draw(); + tessellator.end(); } } } diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 0681a17b..75d35c43 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -2,83 +2,83 @@ package carpet.script.utils; import carpet.CarpetSettings; import com.mojang.brigadier.ResultConsumer; -import net.minecraft.command.argument.EntityAnchorArgumentType; -import net.minecraft.entity.Entity; +import net.minecraft.commands.CommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.EntityAnchorArgument; +import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.CommandOutput; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.Text; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.dimension.DimensionType; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.function.BinaryOperator; -public class SnoopyCommandSource extends ServerCommandSource +public class SnoopyCommandSource extends CommandSourceStack { - private final CommandOutput output; - private final Vec3d position; - private final ServerWorld world; + private final CommandSource output; + private final Vec3 position; + private final ServerLevel world; private final int level; private final String simpleName; - private final Text name; + private final Component name; private final MinecraftServer server; // skipping silent since snooper is never silent private final Entity entity; - private final ResultConsumer resultConsumer; - private final EntityAnchorArgumentType.EntityAnchor entityAnchor; - private final Vec2f rotation; + private final ResultConsumer resultConsumer; + private final EntityAnchorArgument.Anchor entityAnchor; + private final Vec2 rotation; // good stuff - private final Text[] error; - private final List chatOutput; + private final Component[] error; + private final List chatOutput; - public SnoopyCommandSource(ServerCommandSource original, Text[] error, List chatOutput) + public SnoopyCommandSource(CommandSourceStack original, Component[] error, List chatOutput) { - super(CommandOutput.DUMMY, original.getPosition(), original.getRotation(), original.getWorld(), CarpetSettings.runPermissionLevel, - original.getName(), original.getDisplayName(), original.getServer(), original.getEntity(), false, - (ctx, succ, res) -> { }, EntityAnchorArgumentType.EntityAnchor.FEET); - this.output = CommandOutput.DUMMY; + super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), CarpetSettings.runPermissionLevel, + original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false, + (ctx, succ, res) -> { }, EntityAnchorArgument.Anchor.FEET); + this.output = CommandSource.NULL; this.position = original.getPosition(); - this.world = original.getWorld(); + this.world = original.getLevel(); this.level = CarpetSettings.runPermissionLevel; - this.simpleName = original.getName(); + this.simpleName = original.getTextName(); this.name = original.getDisplayName(); this.server = original.getServer(); this.entity = original.getEntity(); this.resultConsumer = (ctx, succ, res) -> { }; - this.entityAnchor = original.getEntityAnchor(); + this.entityAnchor = original.getAnchor(); this.rotation = original.getRotation(); this.error = error; this.chatOutput = chatOutput; } - public SnoopyCommandSource(ServerPlayerEntity player, Text[] error, List output) { - super(player, player.getPos(), player.getRotationClient(), - player.world instanceof ServerWorld ? (ServerWorld) player.world : null, - player.server.getPermissionLevel(player.getGameProfile()), player.getName().getString(), player.getDisplayName(), - player.world.getServer(), player); + public SnoopyCommandSource(ServerPlayer player, Component[] error, List output) { + super(player, player.position(), player.getRotationVector(), + player.level instanceof ServerLevel ? (ServerLevel) player.level : null, + player.server.getProfilePermissions(player.getGameProfile()), player.getName().getString(), player.getDisplayName(), + player.level.getServer(), player); this.output = player; - this.position = player.getPos(); - this.world = player.world instanceof ServerWorld ? (ServerWorld) player.world : null; - this.level = player.server.getPermissionLevel(player.getGameProfile()); + this.position = player.position(); + this.world = player.level instanceof ServerLevel ? (ServerLevel) player.level : null; + this.level = player.server.getProfilePermissions(player.getGameProfile()); this.simpleName = player.getName().getString(); this.name = player.getDisplayName(); - this.server = player.world.getServer(); + this.server = player.level.getServer(); this.entity = player; this.resultConsumer = (ctx, succ, res) -> { }; - this.entityAnchor = EntityAnchorArgumentType.EntityAnchor.FEET; - this.rotation = player.getRotationClient(); // not a client call really + this.entityAnchor = EntityAnchorArgument.Anchor.FEET; + this.rotation = player.getRotationVector(); // not a client call really this.error = error; this.chatOutput = output; } - private SnoopyCommandSource(CommandOutput output, Vec3d pos, Vec2f rot, ServerWorld world, int level, String simpleName, Text name, MinecraftServer server, @Nullable Entity entity, ResultConsumer consumer, EntityAnchorArgumentType.EntityAnchor entityAnchor, - Text[] error, List chatOutput + private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer consumer, EntityAnchorArgument.Anchor entityAnchor, + Component[] error, List chatOutput ) { super(output, pos, rot, world, level, simpleName, name, server, entity, false, @@ -99,34 +99,34 @@ public class SnoopyCommandSource extends ServerCommandSource } @Override - public ServerCommandSource withEntity(Entity entity) + public CommandSourceStack withEntity(Entity entity) { return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource withPosition(Vec3d position) + public CommandSourceStack withPosition(Vec3 position) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource withRotation(Vec2f rotation) + public CommandSourceStack withRotation(Vec2 rotation) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource withConsumer(ResultConsumer consumer) + public CommandSourceStack withCallback(ResultConsumer consumer) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource mergeConsumers(ResultConsumer consumer, BinaryOperator> binaryOperator) + public CommandSourceStack withCallback(ResultConsumer consumer, BinaryOperator> binaryOperator) { - ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); - return this.withConsumer(resultConsumer); + ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); + return this.withCallback(resultConsumer); } //@Override // only used in fuctions and we really don't care to track these actually, besides the basic output @@ -134,51 +134,51 @@ public class SnoopyCommandSource extends ServerCommandSource //public ServerCommandSource withSilent() { return this; } @Override - public ServerCommandSource withLevel(int level) + public CommandSourceStack withPermission(int level) { return this; } @Override - public ServerCommandSource withMaxLevel(int level) + public CommandSourceStack withMaximumPermission(int level) { return this; } @Override - public ServerCommandSource withEntityAnchor(EntityAnchorArgumentType.EntityAnchor anchor) + public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, error, chatOutput); } @Override - public ServerCommandSource withWorld(ServerWorld world) + public CommandSourceStack withLevel(ServerLevel world) { - double d = DimensionType.getCoordinateScaleFactor(this.world.getDimension(), world.getDimension()); - Vec3d position = new Vec3d(this.position.x * d, this.position.y, this.position.z * d); + double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType()); + Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d); return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput); } @Override - public ServerCommandSource withLookingAt(Vec3d position) + public CommandSourceStack facing(Vec3 position) { - Vec3d vec3d = this.entityAnchor.positionAt(this); + Vec3 vec3d = this.entityAnchor.apply(this); double d = position.x - vec3d.x; double e = position.y - vec3d.y; double f = position.z - vec3d.z; double g = (double) Math.sqrt(d * d + f * f); - float h = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(e, g) * 57.2957763671875D))); - float i = MathHelper.wrapDegrees((float)(MathHelper.atan2(f, d) * 57.2957763671875D) - 90.0F); - return this.withRotation(new Vec2f(h, i)); + float h = Mth.wrapDegrees((float)(-(Mth.atan2(e, g) * 57.2957763671875D))); + float i = Mth.wrapDegrees((float)(Mth.atan2(f, d) * 57.2957763671875D) - 90.0F); + return this.withRotation(new Vec2(h, i)); } @Override - public void sendError(Text message) + public void sendFailure(Component message) { error[0] = message; } @Override - public void sendFeedback(Text message, boolean broadcastToOps) + public void sendSuccess(Component message, boolean broadcastToOps) { chatOutput.add(message); } diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index 73e4a125..d0aec077 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -18,12 +18,11 @@ import com.sun.management.OperatingSystemMXBean; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; import net.minecraft.SharedConstants; -import net.minecraft.util.WorldSavePath; -import net.minecraft.util.math.Vec2f; -import net.minecraft.world.GameRules; -import net.minecraft.world.WorldProperties; -import net.minecraft.world.border.WorldBorder; - +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.storage.LevelData; +import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.phys.Vec2; import java.lang.management.ManagementFactory; import java.nio.file.Path; import java.util.ArrayList; @@ -47,65 +46,65 @@ public class SystemInfo { put("app_scope", c -> StringValue.of((c.host).isPerUser()?"player":"global")); put("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new).collect(Collectors.toList()))); - put("world_name", c -> new StringValue(c.s.getServer().getSaveProperties().getLevelName())); - put("world_seed", c -> new NumericValue(c.s.getWorld().getSeed())); - put("server_motd", c -> StringValue.of(c.s.getServer().getServerMotd())); - put("world_path", c -> StringValue.of(c.s.getServer().getSavePath(WorldSavePath.ROOT).toString())); + put("world_name", c -> new StringValue(c.s.getServer().getWorldData().getLevelName())); + put("world_seed", c -> new NumericValue(c.s.getLevel().getSeed())); + put("server_motd", c -> StringValue.of(c.s.getServer().getMotd())); + put("world_path", c -> StringValue.of(c.s.getServer().getWorldPath(LevelResource.ROOT).toString())); put("world_folder", c -> { - Path serverPath = c.s.getServer().getSavePath(WorldSavePath.ROOT); + Path serverPath = c.s.getServer().getWorldPath(LevelResource.ROOT); int nodeCount = serverPath.getNameCount(); if (nodeCount < 2) return Value.NULL; String tlf = serverPath.getName(nodeCount-2).toString(); return StringValue.of(tlf); }); - put("world_dimensions", c -> ListValue.wrap(c.s.getServer().getWorldRegistryKeys().stream().map(k -> ValueConversions.of(k.getValue())).collect(Collectors.toList()))); + put("world_dimensions", c -> ListValue.wrap(c.s.getServer().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList()))); put("world_spawn_point", c -> { - WorldProperties prop = c.s.getServer().getOverworld().getLevelProperties(); - return ListValue.of(NumericValue.of(prop.getSpawnX()), NumericValue.of(prop.getSpawnY()), NumericValue.of(prop.getSpawnZ())); + LevelData prop = c.s.getServer().overworld().getLevelData(); + return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn())); }); - put("world_bottom", c-> new NumericValue(c.s.getWorld().getBottomY())); + put("world_bottom", c-> new NumericValue(c.s.getLevel().getMinBuildHeight())); - put("world_top", c-> new NumericValue(c.s.getWorld().getTopY())); + put("world_top", c-> new NumericValue(c.s.getLevel().getMaxBuildHeight())); put("world_center", c-> { - WorldBorder worldBorder = c.s.getWorld().getWorldBorder(); + WorldBorder worldBorder = c.s.getLevel().getWorldBorder(); return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ()); }); - put("world_size", c -> new NumericValue(c.s.getWorld().getWorldBorder().getSize() / 2)); + put("world_size", c -> new NumericValue(c.s.getLevel().getWorldBorder().getSize() / 2)); - put("world_max_size", c-> new NumericValue( c.s.getWorld().getWorldBorder().getMaxRadius())); + put("world_max_size", c-> new NumericValue( c.s.getLevel().getWorldBorder().getAbsoluteMaxSize())); - put("world_time", c -> new NumericValue(c.s.getWorld().getTime())); + put("world_time", c -> new NumericValue(c.s.getLevel().getGameTime())); - put("game_difficulty", c -> StringValue.of(c.s.getServer().getSaveProperties().getDifficulty().getName())); - put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getSaveProperties().isHardcore())); - put("game_storage_format", c -> StringValue.of(c.s.getServer().getSaveProperties().getFormatName(c.s.getServer().getSaveProperties().getVersion()))); - put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameMode().getName())); - put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayerCount())); - put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerManager().getViewDistance())); + put("game_difficulty", c -> StringValue.of(c.s.getServer().getWorldData().getDifficulty().getKey())); + put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getWorldData().isHardcore())); + put("game_storage_format", c -> StringValue.of(c.s.getServer().getWorldData().getStorageVersionName(c.s.getServer().getWorldData().getVersion()))); + put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameType().getName())); + put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayers())); + put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerList().getViewDistance())); put("game_mod_name", c -> StringValue.of(c.s.getServer().getServerModName())); - put("game_version", c -> StringValue.of(c.s.getServer().getVersion())); - put("game_target", c -> StringValue.of(SharedConstants.getGameVersion().getReleaseTarget())); + put("game_version", c -> StringValue.of(c.s.getServer().getServerVersion())); + put("game_target", c -> StringValue.of(SharedConstants.getCurrentVersion().getReleaseTarget())); put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { - String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\."); + String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\."); return NumericValue.of((vers.length > 1)?Integer.parseInt(vers[1]):0); }); put("game_minor_target", c -> { - String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\."); + String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\."); return NumericValue.of((vers.length > 2)?Integer.parseInt(vers[2]):0); }); - put("game_stable", c -> BooleanValue.of(SharedConstants.getGameVersion().isStable())); - put("game_data_version", c->NumericValue.of(SharedConstants.getGameVersion().getWorldVersion())); - put("game_pack_version", c->NumericValue.of(SharedConstants.getGameVersion().getPackVersion())); + put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable())); + put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getWorldVersion())); + put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion())); - put("server_ip", c -> StringValue.of(c.s.getServer().getServerIp())); + put("server_ip", c -> StringValue.of(c.s.getServer().getLocalIp())); put("server_whitelisted", c -> BooleanValue.of(c.s.getServer().isEnforceWhitelist())); put("server_whitelist", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerManager().getWhitelistedNames()) + for (String s: c.s.getServer().getPlayerList().getWhiteListNames()) { whitelist.append(StringValue.of(s)); } @@ -113,7 +112,7 @@ public class SystemInfo { }); put("server_banned_players", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerManager().getUserBanList().getNames()) + for (String s: c.s.getServer().getPlayerList().getBans().getUserList()) { whitelist.append(StringValue.of(s)); } @@ -121,7 +120,7 @@ public class SystemInfo { }); put("server_banned_ips", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerManager().getIpBanList().getNames()) + for (String s: c.s.getServer().getPlayerList().getIpBans().getUserList()) { whitelist.append(StringValue.of(s)); } @@ -137,9 +136,9 @@ public class SystemInfo { put("server_last_tick_times", c -> { //assuming we are in the tick world section // might be off one tick when run in the off tasks or asynchronously. - int currentReportedTick = c.s.getServer().getTicks()-1; + int currentReportedTick = c.s.getServer().getTickCount()-1; List ticks = new ArrayList<>(100); - final long[] tickArray = c.s.getServer().lastTickLengths; + final long[] tickArray = c.s.getServer().tickTimes; for (int i=currentReportedTick+100; i > currentReportedTick; i--) { ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0)); @@ -191,11 +190,11 @@ public class SystemInfo { }); put("world_gamerules", c->{ Map rules = new HashMap<>(); - final GameRules gameRules = c.s.getWorld().getGameRules(); - GameRules.accept(new GameRules.Visitor() { + final GameRules gameRules = c.s.getLevel().getGameRules(); + GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { @Override - public > void visit(GameRules.Key key, GameRules.Type type) { - rules.put(StringValue.of(key.getName()), StringValue.of(gameRules.get(key).toString())); + public > void visit(GameRules.Key key, GameRules.Type type) { + rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString())); } }); return MapValue.wrap(rules); @@ -203,9 +202,9 @@ public class SystemInfo { put("source_entity", c -> EntityValue.of(c.s.getEntity())); put("source_position", c -> ValueConversions.of(c.s.getPosition())); - put("source_dimension", c -> ValueConversions.of(c.s.getWorld())); + put("source_dimension", c -> ValueConversions.of(c.s.getLevel())); put("source_rotation", c -> { - Vec2f rotation = c.s.getRotation(); + Vec2 rotation = c.s.getRotation(); return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y)); }); diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java index da1bd92a..18a14fc5 100644 --- a/src/main/java/carpet/script/utils/WorldTools.java +++ b/src/main/java/carpet/script/utils/WorldTools.java @@ -3,35 +3,34 @@ package carpet.script.utils; import carpet.fakes.MinecraftServerInterface; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; +import net.minecraft.Util; +import net.minecraft.core.BlockPos; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.WorldGenerationProgressListener; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.util.registry.SimpleRegistry; -import net.minecraft.world.World; -import net.minecraft.world.biome.source.BiomeAccess; -import net.minecraft.world.biome.source.MultiNoiseBiomeSource; -import net.minecraft.world.border.WorldBorderListener; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.chunk.WorldChunk; -import net.minecraft.world.dimension.DimensionOptions; -import net.minecraft.world.dimension.DimensionType; -import net.minecraft.world.gen.GeneratorOptions; -import net.minecraft.world.gen.Spawner; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; -import net.minecraft.world.gen.chunk.NoiseChunkGenerator; -import net.minecraft.world.level.ServerWorldProperties; -import net.minecraft.world.level.UnmodifiableLevelProperties; -import net.minecraft.world.storage.RegionFile; - +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.progress.ChunkProgressListener; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.CustomSpawner; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.biome.MultiNoiseBiomeSource; +import net.minecraft.world.level.border.BorderChangeListener; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.storage.RegionFile; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.storage.DerivedLevelData; +import net.minecraft.world.level.storage.ServerLevelData; import java.io.File; import java.io.IOException; import java.nio.file.Path; @@ -43,7 +42,7 @@ import java.util.Set; public class WorldTools { - public static boolean canHasChunk(ServerWorld world, ChunkPos chpos, Map regionCache, boolean deepcheck) + public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, Map regionCache, boolean deepcheck) { if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null) return true; @@ -54,7 +53,7 @@ public class WorldTools if (region == null) return false; return region.hasChunk(chpos); } - Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getWorldDirectory(world.getRegistryKey()).toFile(), "region").toPath(); + Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getDimensionPath(world.dimension()).toFile(), "region").toPath(); Path regionFilePath = regionPath.resolve(currentRegionName); File regionFile = regionFilePath.toFile(); if (!regionFile.exists()) @@ -75,37 +74,37 @@ public class WorldTools public static boolean createWorld(MinecraftServer server, String worldKey, Long seed) { - Identifier worldId = new Identifier(worldKey); - ServerWorld overWorld = server.getOverworld(); + ResourceLocation worldId = new ResourceLocation(worldKey); + ServerLevel overWorld = server.overworld(); - Set> worldKeys = server.getWorldRegistryKeys(); - for (RegistryKey worldRegistryKey : worldKeys) + Set> worldKeys = server.levelKeys(); + for (ResourceKey worldRegistryKey : worldKeys) { - if (worldRegistryKey.getValue().equals(worldId)) + if (worldRegistryKey.location().equals(worldId)) { // world with this id already exists return false; } } - ServerWorldProperties serverWorldProperties = server.getSaveProperties().getMainWorldProperties(); - GeneratorOptions generatorOptions = server.getSaveProperties().getGeneratorOptions(); - boolean bl = generatorOptions.isDebugWorld(); - long l = generatorOptions.getSeed(); - long m = BiomeAccess.hashSeed(l); - List list = List.of(); - SimpleRegistry simpleRegistry = generatorOptions.getDimensions(); - DimensionOptions dimensionOptions = simpleRegistry.get(DimensionOptions.OVERWORLD); + ServerLevelData serverWorldProperties = server.getWorldData().overworldData(); + WorldGenSettings generatorOptions = server.getWorldData().worldGenSettings(); + boolean bl = generatorOptions.isDebug(); + long l = generatorOptions.seed(); + long m = BiomeManager.obfuscateSeed(l); + List list = List.of(); + MappedRegistry simpleRegistry = generatorOptions.dimensions(); + LevelStem dimensionOptions = simpleRegistry.get(LevelStem.OVERWORLD); ChunkGenerator chunkGenerator2; DimensionType dimensionType2; if (dimensionOptions == null) { - dimensionType2 = server.getRegistryManager().getMutable(Registry.DIMENSION_TYPE_KEY).getOrThrow(DimensionType.OVERWORLD_REGISTRY_KEY); - chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager(), (new Random()).nextLong()); + dimensionType2 = server.registryAccess().ownedRegistryOrThrow(Registry.DIMENSION_TYPE_REGISTRY).getOrThrow(DimensionType.OVERWORLD_LOCATION); + chunkGenerator2 = WorldGenSettings.makeDefaultOverworld(server.registryAccess(), (new Random()).nextLong()); } else { - dimensionType2 = dimensionOptions.getDimensionType(); - chunkGenerator2 = dimensionOptions.getChunkGenerator(); + dimensionType2 = dimensionOptions.type(); + chunkGenerator2 = dimensionOptions.generator(); } - RegistryKey customWorld = RegistryKey.of(Registry.WORLD_KEY, worldId); + ResourceKey customWorld = ResourceKey.create(Registry.DIMENSION_REGISTRY, worldId); //chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN), (seed==null)?l:seed); @@ -114,15 +113,15 @@ public class WorldTools // return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD); //}); - chunkGenerator2 = new NoiseChunkGenerator(server.getRegistryManager().get(Registry.NOISE_WORLDGEN), MultiNoiseBiomeSource.Preset.OVERWORLD.getBiomeSource(server.getRegistryManager().get(Registry.BIOME_KEY)), seed, () -> { - return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD); + chunkGenerator2 = new NoiseBasedChunkGenerator(server.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY), MultiNoiseBiomeSource.Preset.OVERWORLD.biomeSource(server.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY)), seed, () -> { + return server.registryAccess().registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY).getOrThrow(NoiseGeneratorSettings.OVERWORLD); }); - ServerWorld serverWorld = new ServerWorld( + ServerLevel serverWorld = new ServerLevel( server, - Util.getMainWorkerExecutor(), + Util.backgroundExecutor(), ((MinecraftServerInterface) server).getCMSession(), - new UnmodifiableLevelProperties(server.getSaveProperties(), serverWorldProperties), + new DerivedLevelData(server.getWorldData(), serverWorldProperties), customWorld, dimensionType2, NOOP_LISTENER, @@ -131,37 +130,37 @@ public class WorldTools (seed==null)?l:seed, list, false); - overWorld.getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld.getWorldBorder())); + overWorld.getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld.getWorldBorder())); ((MinecraftServerInterface) server).getCMWorlds().put(customWorld, serverWorld); return true; } - public static void forceChunkUpdate(BlockPos pos, ServerWorld world) + public static void forceChunkUpdate(BlockPos pos, ServerLevel world) { - WorldChunk worldChunk = world.getChunkManager().getWorldChunk(pos.getX()>>4, pos.getZ()>>4, false); + LevelChunk worldChunk = world.getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false); if (worldChunk != null) { - int vd = world.getServer().getPlayerManager().getViewDistance() * 16; + int vd = world.getServer().getPlayerList().getViewDistance() * 16; int vvd = vd * vd; - List nearbyPlayers = world.getPlayers(p -> pos.getSquaredDistance(p.getX(), pos.getY(), p.getZ(), true) < vvd); + List nearbyPlayers = world.getPlayers(p -> pos.distSqr(p.getX(), pos.getY(), p.getZ(), true) < vvd); if (!nearbyPlayers.isEmpty()) { - ChunkDataS2CPacket packet = new ChunkDataS2CPacket(worldChunk, world.getLightingProvider(), null, null, false); // false seems to update neighbours as well. + ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well. ChunkPos chpos = new ChunkPos(pos); - nearbyPlayers.forEach(p -> p.networkHandler.sendPacket(packet)); + nearbyPlayers.forEach(p -> p.connection.send(packet)); } } } - private static class NoopWorldGenerationProgressListener implements WorldGenerationProgressListener + private static class NoopWorldGenerationProgressListener implements ChunkProgressListener { - @Override public void start(ChunkPos spawnPos) { } - @Override public void setChunkStatus(ChunkPos pos, ChunkStatus status) { } + @Override public void updateSpawnPos(ChunkPos spawnPos) { } + @Override public void onStatusChange(ChunkPos pos, ChunkStatus status) { } @Environment(EnvType.CLIENT) @Override public void start() { } @Override public void stop() { } } - public static final WorldGenerationProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener(); + public static final ChunkProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener(); } diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index ca1720ff..5c1760c2 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -7,27 +7,6 @@ import carpet.script.exception.Throwables; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.command.argument.BlockArgumentParser; -import net.minecraft.block.Blocks; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.state.property.Property; -import net.minecraft.util.dynamic.GlobalPos; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; -import net.minecraft.world.chunk.WorldChunk; - import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -35,22 +14,42 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; public class BlockValue extends Value { - public static final BlockValue AIR = new BlockValue(Blocks.AIR.getDefaultState(), null, BlockPos.ORIGIN); + public static final BlockValue AIR = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO); public static final BlockValue NULL = new BlockValue(null, null, null); private BlockState blockState; private final BlockPos pos; - private final ServerWorld world; - private NbtCompound data; + private final ServerLevel world; + private CompoundTag data; public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) { BlockPos pos = locateBlockPos(c, x,y,z); - return new BlockValue(null, c.s.getWorld(), pos); + return new BlockValue(null, c.s.getLevel(), pos); } private static final Map bvCache= new HashMap<>(); @@ -60,13 +59,13 @@ public class BlockValue extends Value { BlockValue bv = bvCache.get(str); if (bv != null) return bv; - BlockArgumentParser blockstateparser = (new BlockArgumentParser(new StringReader(str), false)).parse(true); - if (blockstateparser.getBlockState() != null) + BlockStateParser blockstateparser = (new BlockStateParser(new StringReader(str), false)).parse(true); + if (blockstateparser.getState() != null) { - NbtCompound bd = blockstateparser.getNbtData(); + CompoundTag bd = blockstateparser.getNbt(); if (bd == null) - bd = new NbtCompound(); - bv = new BlockValue(blockstateparser.getBlockState(), null, null, bd ); + bd = new CompoundTag(); + bv = new BlockValue(blockstateparser.getState(), null, null, bd ); if (bvCache.size()>10000) bvCache.clear(); bvCache.put(str, bv); @@ -98,16 +97,16 @@ public class BlockValue extends Value throw new InternalExpressionException("Attempted to fetch block state without world or stored block state"); } - public static BlockEntity getBlockEntity(ServerWorld world, BlockPos pos) + public static BlockEntity getBlockEntity(ServerLevel world, BlockPos pos) { - if (world.getServer().isOnThread()) + if (world.getServer().isSameThread()) return world.getBlockEntity(pos); else - return world.getWorldChunk(pos).getBlockEntity(pos, WorldChunk.CreationType.IMMEDIATE); + return world.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); } - public NbtCompound getData() + public CompoundTag getData() { if (data != null) { @@ -120,17 +119,17 @@ public class BlockValue extends Value BlockEntity be = getBlockEntity(world, pos); if (be == null) { - data = new NbtCompound(); + data = new CompoundTag(); return null; } - data = be.createNbt(); + data = be.saveWithoutMetadata(); return data; } return null; } - public BlockValue(BlockState state, ServerWorld world, BlockPos position) + public BlockValue(BlockState state, ServerLevel world, BlockPos position) { this.world = world; blockState = state; @@ -138,7 +137,7 @@ public class BlockValue extends Value data = null; } - public BlockValue(BlockState state, ServerWorld world, BlockPos position, NbtCompound nbt) + public BlockValue(BlockState state, ServerLevel world, BlockPos position, CompoundTag nbt) { this.world = world; blockState = state; @@ -150,7 +149,7 @@ public class BlockValue extends Value @Override public String getString() { - return nameFromRegistryId(Registry.BLOCK.getId(getBlockState().getBlock())); + return nameFromRegistryId(Registry.BLOCK.getKey(getBlockState().getBlock())); } @Override @@ -175,7 +174,7 @@ public class BlockValue extends Value public int hashCode() { if (world != null && pos != null ) - return GlobalPos.create(world.getRegistryKey() , pos).hashCode(); //getDimension().getType() + return GlobalPos.of(world.dimension() , pos).hashCode(); //getDimension().getType() return ("b"+getString()).hashCode(); } @@ -184,29 +183,29 @@ public class BlockValue extends Value return pos; } - public ServerWorld getWorld() { return world;} + public ServerLevel getWorld() { return world;} @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); // follows falling block convertion - NbtCompound tag = new NbtCompound(); - NbtCompound state = new NbtCompound(); + CompoundTag tag = new CompoundTag(); + CompoundTag state = new CompoundTag(); BlockState s = getBlockState(); - state.put("Name", NbtString.of(Registry.BLOCK.getId(s.getBlock()).toString())); + state.put("Name", StringTag.valueOf(Registry.BLOCK.getKey(s.getBlock()).toString())); Collection> properties = s.getProperties(); if (!properties.isEmpty()) { - NbtCompound props = new NbtCompound(); + CompoundTag props = new CompoundTag(); for (Property p: properties) { - props.put(p.getName(), NbtString.of(s.get(p).toString().toLowerCase(Locale.ROOT))); + props.put(p.getName(), StringTag.valueOf(s.getValue(p).toString().toLowerCase(Locale.ROOT))); } state.put("Properties", props); } tag.put("BlockState", state); - NbtCompound dataTag = getData(); + CompoundTag dataTag = getData(); if (dataTag != null) { tag.put("TileEntityData", dataTag); @@ -241,7 +240,7 @@ public class BlockValue extends Value WESTUP("west-up", 1.0, 0.6, 0.5, Direction.WEST); public final String name; - public final Vec3d hitOffset; + public final Vec3 hitOffset; public final Direction facing; private static final Map DIRECTION_MAP = Arrays.stream(values()).collect(Collectors.toMap(SpecificDirection::getName, d -> d)); @@ -250,7 +249,7 @@ public class BlockValue extends Value SpecificDirection(String name, double hitx, double hity, double hitz, Direction blockFacing) { this.name = name; - this.hitOffset = new Vec3d(hitx, hity, hitz); + this.hitOffset = new Vec3(hitx, hity, hitz); this.facing = blockFacing; } private String getName() @@ -259,40 +258,40 @@ public class BlockValue extends Value } } - public static class PlacementContext extends ItemPlacementContext { + public static class PlacementContext extends BlockPlaceContext { private final Direction facing; private final boolean sneakPlace; - public static PlacementContext from(World world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack) + public static PlacementContext from(Level world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack) { SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction); if (dir == null) throw new InternalExpressionException("unknown block placement direction: "+direction); - BlockHitResult hitres = new BlockHitResult(Vec3d.of(pos).add(dir.hitOffset), dir.facing, pos, false); + BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false); return new PlacementContext(world, dir.facing, sneakPlace, itemStack, hitres); } - private PlacementContext(World world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) { - super(world_1, null, Hand.MAIN_HAND, itemStack_1, hitres); + private PlacementContext(Level world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) { + super(world_1, null, InteractionHand.MAIN_HAND, itemStack_1, hitres); this.facing = direction_1; this.sneakPlace = sneakPlace; } @Override - public BlockPos getBlockPos() { - boolean prevcanReplaceExisting = canReplaceExisting; - canReplaceExisting = true; - BlockPos ret = super.getBlockPos(); - canReplaceExisting = prevcanReplaceExisting; + public BlockPos getClickedPos() { + boolean prevcanReplaceExisting = replaceClicked; + replaceClicked = true; + BlockPos ret = super.getClickedPos(); + replaceClicked = prevcanReplaceExisting; return ret; } @Override - public Direction getPlayerLookDirection() { + public Direction getNearestLookingDirection() { return facing.getOpposite(); } @Override - public Direction[] getPlacementDirections() { + public Direction[] getNearestLookingDirections() { switch(this.facing) { case DOWN: default: @@ -311,18 +310,18 @@ public class BlockValue extends Value } @Override - public Direction getPlayerFacing() { + public Direction getHorizontalDirection() { return this.facing.getAxis() == Direction.Axis.Y ? Direction.NORTH : this.facing; } @Override - public boolean shouldCancelInteraction() { + public boolean isSecondaryUseActive() { return sneakPlace; } @Override - public float getPlayerYaw() { - return (float)(this.facing.getHorizontal() * 90); + public float getRotation() { + return (float)(this.facing.get2DDataValue() * 90); } } } diff --git a/src/main/java/carpet/script/value/BooleanValue.java b/src/main/java/carpet/script/value/BooleanValue.java index 64b91c00..66c29bd0 100644 --- a/src/main/java/carpet/script/value/BooleanValue.java +++ b/src/main/java/carpet/script/value/BooleanValue.java @@ -2,8 +2,8 @@ package carpet.script.value; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.NbtByte; -import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.Tag; public class BooleanValue extends NumericValue { @@ -47,8 +47,8 @@ public class BooleanValue extends NumericValue } @Override - public NbtElement toTag(boolean force) { - return NbtByte.of(boolValue); + public Tag toTag(boolean force) { + return ByteTag.valueOf(boolValue); } @Override diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index dd761bc9..1a789d03 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -18,61 +18,58 @@ import carpet.script.utils.InputValidator; import com.google.common.collect.Sets; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.entity.ai.brain.Brain; -import net.minecraft.entity.ai.brain.Memory; -import net.minecraft.entity.EntityGroup; -import net.minecraft.entity.ai.brain.MemoryModuleType; -import net.minecraft.entity.ai.pathing.Path; -import net.minecraft.entity.attribute.AttributeContainer; -import net.minecraft.entity.attribute.EntityAttribute; -import net.minecraft.entity.projectile.ProjectileEntity; -import net.minecraft.entity.vehicle.AbstractMinecartEntity; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.network.packet.s2c.play.EntityPassengersSetS2CPacket; -import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket; -import net.minecraft.network.packet.s2c.play.ExperienceBarUpdateS2CPacket; -import net.minecraft.network.packet.s2c.play.PlayerPositionLookS2CPacket; -import net.minecraft.network.packet.s2c.play.UpdateSelectedSlotS2CPacket; -import net.minecraft.command.EntitySelector; -import net.minecraft.command.EntitySelectorReader; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityPose; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.ItemEntity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.ai.goal.GoToWalkTargetGoal; -import net.minecraft.entity.ai.goal.Goal; -import net.minecraft.entity.effect.StatusEffect; -import net.minecraft.entity.effect.StatusEffectInstance; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.mob.PathAwareEntity; -import net.minecraft.entity.passive.PassiveEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.predicate.entity.EntityPredicates; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.commands.arguments.selector.EntitySelectorParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.tag.Tag; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.TypeFilter; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.GameMode; -import net.minecraft.world.World; - +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.Tag; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.MobType; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.Brain; +import net.minecraft.world.entity.ai.attributes.Attribute; +import net.minecraft.world.entity.ai.attributes.AttributeMap; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.MoveTowardsRestrictionGoal; +import net.minecraft.world.entity.ai.memory.ExpirableValue; +import net.minecraft.world.entity.ai.memory.MemoryModuleType; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; @@ -109,18 +106,18 @@ public class EntityValue extends Value } private static final Map selectorCache = new HashMap<>(); - public static Collection getEntitiesFromSelector(ServerCommandSource source, String selector) + public static Collection getEntitiesFromSelector(CommandSourceStack source, String selector) { try { EntitySelector entitySelector = selectorCache.get(selector); if (entitySelector != null) { - return entitySelector.getEntities(source.withMaxLevel(4)); + return entitySelector.findEntities(source.withMaximumPermission(4)); } - entitySelector = new EntitySelectorReader(new StringReader(selector), true).read(); + entitySelector = new EntitySelectorParser(new StringReader(selector), true).parse(); selectorCache.put(selector, entitySelector); - return entitySelector.getEntities(source.withMaxLevel(4)); + return entitySelector.findEntities(source.withMaximumPermission(4)); } catch (CommandSyntaxException e) { @@ -130,23 +127,23 @@ public class EntityValue extends Value public Entity getEntity() { - if (entity instanceof ServerPlayerEntity && ((ServerPlayerEntityInterface)entity).isInvalidEntityObject()) + if (entity instanceof ServerPlayer && ((ServerPlayerEntityInterface)entity).isInvalidEntityObject()) { - ServerPlayerEntity newPlayer = entity.getServer().getPlayerManager().getPlayer(entity.getUuid()); + ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); if (newPlayer != null) entity = newPlayer; } return entity; } - public static ServerPlayerEntity getPlayerByValue(MinecraftServer server, Value value) + public static ServerPlayer getPlayerByValue(MinecraftServer server, Value value) { - ServerPlayerEntity player = null; + ServerPlayer player = null; if (value instanceof EntityValue) { Entity e = ((EntityValue) value).getEntity(); - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - player = (ServerPlayerEntity) e; + player = (ServerPlayer) e; } } else if (value.isNull()) @@ -156,7 +153,7 @@ public class EntityValue extends Value else { String playerName = value.getString(); - player = server.getPlayerManager().getPlayer(playerName); + player = server.getPlayerList().getPlayerByName(playerName); } return player; } @@ -167,9 +164,9 @@ public class EntityValue extends Value if (value instanceof EntityValue) { Entity e = ((EntityValue) value).getEntity(); - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - playerName = e.getEntityName(); + playerName = e.getScoreboardName(); } } else if (value.isNull()) @@ -250,11 +247,11 @@ public class EntityValue extends Value positive = false; who = who.substring(1); } - Tag> eTag = server.getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTag(InputValidator.identifierOf(who)); + Tag> eTag = server.getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(who)); if (eTag == null) throw new InternalExpressionException(who+" is not a valid entity descriptor"); if (positive) { - return new EntityClassDescriptor(null, e -> eTag.contains(e.getType()) && e.isAlive(), eTag.values().stream()); + return new EntityClassDescriptor(null, e -> eTag.contains(e.getType()) && e.isAlive(), eTag.getValues().stream()); } else { @@ -268,7 +265,7 @@ public class EntityValue extends Value public static class EntityClassDescriptor { - public TypeFilter directType; // interface of EntityType + public EntityTypeTest directType; // interface of EntityType public Predicate filteringPredicate; public List> typeList; public Value listValue; @@ -277,15 +274,15 @@ public class EntityValue extends Value directType = type; filteringPredicate = predicate; typeList = types; - listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getId(et)))).collect(Collectors.toList())); + listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(et)))).collect(Collectors.toList())); } - EntityClassDescriptor( TypeFilter type, Predicate predicate, List> types) + EntityClassDescriptor( EntityTypeTest type, Predicate predicate, List> types) { directType = type; filteringPredicate = predicate; typeList = types; - listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getId(et)))).collect(Collectors.toList())); + listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(et)))).collect(Collectors.toList())); } EntityClassDescriptor(EntityType type, Predicate predicate, Stream> types) @@ -293,7 +290,7 @@ public class EntityValue extends Value this(type, predicate, types.collect(Collectors.toList())); } - EntityClassDescriptor(TypeFilter type, Predicate predicate, Stream> types) + EntityClassDescriptor(EntityTypeTest type, Predicate predicate, Stream> types) { this(type, predicate, types.collect(Collectors.toList())); } @@ -351,49 +348,49 @@ public class EntityValue extends Value ).collect(Collectors.toSet()); - put("*", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> true, allTypes) ); - put("valid", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), EntityPredicates.VALID_ENTITY, allTypes)); - put("!valid", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> !e.isAlive(), allTypes)); + put("*", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), e -> true, allTypes) ); + put("valid", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes)); + put("!valid", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), e -> !e.isAlive(), allTypes)); - put("living", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(living::contains))); - put("!living", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); + put("living", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(living::contains))); + put("!living", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); - put("projectile", new EntityClassDescriptor(TypeFilter.instanceOf(ProjectileEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(projectiles::contains))); - put("!projectile", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof ProjectileEntity) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et)))); + put("projectile", new EntityClassDescriptor(EntityTypeTest.forClass(Projectile.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(projectiles::contains))); + put("!projectile", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), (e) -> (!(e instanceof Projectile) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et)))); - put("minecarts", new EntityClassDescriptor(TypeFilter.instanceOf(AbstractMinecartEntity.class), EntityPredicates.VALID_ENTITY, allTypes.stream().filter(minecarts::contains))); - put("!minecarts", new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> (!(e instanceof AbstractMinecartEntity) && e.isAlive()), allTypes.stream().filter(et -> !minecarts.contains(et) && !living.contains(et)))); + put("minecarts", new EntityClassDescriptor(EntityTypeTest.forClass(AbstractMinecart.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(minecarts::contains))); + put("!minecarts", new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), (e) -> (!(e instanceof AbstractMinecart) && e.isAlive()), allTypes.stream().filter(et -> !minecarts.contains(et) && !living.contains(et)))); // combat groups - put("arthropod", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(arthropods::contains))); - put("!arthropod", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.ARTHROPOD && e.isAlive()), allTypes.stream().filter(et -> !arthropods.contains(et) && living.contains(et)))); + put("arthropod", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.ARTHROPOD && e.isAlive()), allTypes.stream().filter(arthropods::contains))); + put("!arthropod", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.ARTHROPOD && e.isAlive()), allTypes.stream().filter(et -> !arthropods.contains(et) && living.contains(et)))); - put("undead", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(undeads::contains))); - put("!undead", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.UNDEAD && e.isAlive()), allTypes.stream().filter(et -> !undeads.contains(et) && living.contains(et)))); + put("undead", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEAD && e.isAlive()), allTypes.stream().filter(undeads::contains))); + put("!undead", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEAD && e.isAlive()), allTypes.stream().filter(et -> !undeads.contains(et) && living.contains(et)))); - put("aquatic", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(aquatique::contains))); - put("!aquatic", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.AQUATIC && e.isAlive()), allTypes.stream().filter(et -> !aquatique.contains(et) && living.contains(et)))); + put("aquatic", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.WATER && e.isAlive()), allTypes.stream().filter(aquatique::contains))); + put("!aquatic", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.WATER && e.isAlive()), allTypes.stream().filter(et -> !aquatique.contains(et) && living.contains(et)))); - put("illager", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(illagers::contains))); - put("!illager", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.ILLAGER && e.isAlive()), allTypes.stream().filter(et -> !illagers.contains(et) && living.contains(et)))); + put("illager", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.ILLAGER && e.isAlive()), allTypes.stream().filter(illagers::contains))); + put("!illager", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.ILLAGER && e.isAlive()), allTypes.stream().filter(et -> !illagers.contains(et) && living.contains(et)))); - put("regular", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() == EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(regular::contains))); - put("!regular", new EntityClassDescriptor(TypeFilter.instanceOf(LivingEntity.class), e -> (((LivingEntity) e).getGroup() != EntityGroup.DEFAULT && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); + put("regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(regular::contains))); + put("!regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); - for (Identifier typeId : Registry.ENTITY_TYPE.getIds()) + for (ResourceLocation typeId : Registry.ENTITY_TYPE.keySet()) { EntityType type = Registry.ENTITY_TYPE.get(typeId); String mobType = ValueConversions.simplify(typeId); - put( mobType, new EntityClassDescriptor(type, EntityPredicates.VALID_ENTITY, Stream.of(type))); - put("!"+mobType, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); + put( mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type))); + put("!"+mobType, new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); } - for (SpawnGroup catId : SpawnGroup.values()) + for (MobCategory catId : MobCategory.values()) { String catStr = catId.getName(); - put( catStr, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> ((e.getType().getSpawnGroup() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() == catId))); - put("!"+catStr, new EntityClassDescriptor(TypeFilter.instanceOf(Entity.class), e -> ((e.getType().getSpawnGroup() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getSpawnGroup() != catId))); + put( catStr, new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId))); + put("!"+catStr, new EntityClassDescriptor(EntityTypeTest.forClass(Entity.class), e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId))); } }}; } @@ -423,96 +420,96 @@ public class EntityValue extends Value private static final Map> featureAccessors = new HashMap>() {{ //put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString())); put("removed", (entity, arg) -> BooleanValue.of(entity.isRemoved())); - put("uuid",(e, a) -> new StringValue(e.getUuidAsString())); + put("uuid",(e, a) -> new StringValue(e.getStringUUID())); put("id",(e, a) -> new NumericValue(e.getId())); put("pos", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()))); - put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.getYaw()), new NumericValue(e.getPitch()))); + put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.getYRot()), new NumericValue(e.getXRot()))); put("x", (e, a) -> new NumericValue(e.getX())); put("y", (e, a) -> new NumericValue(e.getY())); put("z", (e, a) -> new NumericValue(e.getZ())); put("motion", (e, a) -> { - Vec3d velocity = e.getVelocity(); + Vec3 velocity = e.getDeltaMovement(); return ListValue.of(new NumericValue(velocity.x), new NumericValue(velocity.y), new NumericValue(velocity.z)); }); - put("motion_x", (e, a) -> new NumericValue(e.getVelocity().x)); - put("motion_y", (e, a) -> new NumericValue(e.getVelocity().y)); - put("motion_z", (e, a) -> new NumericValue(e.getVelocity().z)); + put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x)); + put("motion_y", (e, a) -> new NumericValue(e.getDeltaMovement().y)); + put("motion_z", (e, a) -> new NumericValue(e.getDeltaMovement().z)); put("on_ground", (e, a) -> BooleanValue.of(e.isOnGround())); put("name", (e, a) -> new StringValue(e.getName().getString())); put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName())); - put("command_name", (e, a) -> new StringValue(e.getEntityName())); + put("command_name", (e, a) -> new StringValue(e.getScoreboardName())); put("custom_name", (e, a) -> e.hasCustomName()?new StringValue(e.getCustomName().getString()):Value.NULL); - put("type", (e, a) -> new StringValue(nameFromRegistryId(Registry.ENTITY_TYPE.getId(e.getType())))); - put("is_riding", (e, a) -> BooleanValue.of(e.hasVehicle())); - put("is_ridden", (e, a) -> BooleanValue.of(e.hasPassengers())); - put("passengers", (e, a) -> ListValue.wrap(e.getPassengerList().stream().map(EntityValue::new).collect(Collectors.toList()))); + put("type", (e, a) -> new StringValue(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(e.getType())))); + put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger())); + put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); + put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new).collect(Collectors.toList()))); put("mount", (e, a) -> (e.getVehicle()!=null)?new EntityValue(e.getVehicle()):Value.NULL); put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface)e).isPermanentVehicle())); // deprecated - put("tags", (e, a) -> ListValue.wrap(e.getScoreboardTags().stream().map(StringValue::new).collect(Collectors.toList()))); + put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList()))); - put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getScoreboardTags().stream().map(StringValue::new).collect(Collectors.toList()))); - put("entity_tags", (e, a) -> ListValue.wrap(e.getServer().getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTags().entrySet().stream().filter(entry -> entry.getValue().contains(e.getType())).map(entry -> ValueConversions.of(entry.getKey())).collect(Collectors.toList()))); + put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList()))); + put("entity_tags", (e, a) -> ListValue.wrap(e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getAllTags().entrySet().stream().filter(entry -> entry.getValue().contains(e.getType())).map(entry -> ValueConversions.of(entry.getKey())).collect(Collectors.toList()))); // deprecated - put("has_tag", (e, a) -> BooleanValue.of(e.getScoreboardTags().contains(a.getString()))); + put("has_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString()))); - put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getScoreboardTags().contains(a.getString()))); + put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString()))); put("has_entity_tag", (e, a) -> { - Tag> tag = e.getServer().getTagManager().getOrCreateTagGroup(Registry.ENTITY_TYPE_KEY).getTag(InputValidator.identifierOf(a.getString())); + Tag> tag = e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(a.getString())); if (tag == null) return Value.NULL; - return BooleanValue.of(e.getType().isIn(tag)); + return BooleanValue.of(e.getType().is(tag)); }); - put("yaw", (e, a)-> new NumericValue(e.getYaw())); + put("yaw", (e, a)-> new NumericValue(e.getYRot())); put("head_yaw", (e, a)-> { if (e instanceof LivingEntity) { - return new NumericValue(e.getHeadYaw()); + return new NumericValue(e.getYHeadRot()); } return Value.NULL; }); put("body_yaw", (e, a)-> { if (e instanceof LivingEntity) { - return new NumericValue(((LivingEntity) e).bodyYaw); + return new NumericValue(((LivingEntity) e).yBodyRot); } return Value.NULL; }); - put("pitch", (e, a)-> new NumericValue(e.getPitch())); + put("pitch", (e, a)-> new NumericValue(e.getXRot())); put("look", (e, a) -> { - Vec3d look = e.getRotationVector(); + Vec3 look = e.getLookAngle(); return ListValue.of(new NumericValue(look.x),new NumericValue(look.y),new NumericValue(look.z)); }); put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire())); - put("fire", (e, a) -> new NumericValue(e.getFireTicks())); - put("is_freezing", (e, a) -> BooleanValue.of(e.isFreezing())); - put("frost", (e, a) -> new NumericValue(e.getFrozenTicks())); + put("fire", (e, a) -> new NumericValue(e.getRemainingFireTicks())); + put("is_freezing", (e, a) -> BooleanValue.of(e.isFullyFrozen())); + put("frost", (e, a) -> new NumericValue(e.getTicksFrozen())); put("silent", (e, a)-> BooleanValue.of(e.isSilent())); - put("gravity", (e, a) -> BooleanValue.of(!e.hasNoGravity())); - put("immune_to_fire", (e, a) -> BooleanValue.of(e.isFireImmune())); + put("gravity", (e, a) -> BooleanValue.of(!e.isNoGravity())); + put("immune_to_fire", (e, a) -> BooleanValue.of(e.fireImmune())); put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze())); put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable())); - put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.world.getRegistryKey().getValue()))); // getDimId - put("height", (e, a) -> new NumericValue(e.getDimensions(EntityPose.STANDING).height)); - put("width", (e, a) -> new NumericValue(e.getDimensions(EntityPose.STANDING).width)); - put("eye_height", (e, a) -> new NumericValue(e.getStandingEyeHeight())); - put("age", (e, a) -> new NumericValue(e.age)); - put("breeding_age", (e, a) -> e instanceof PassiveEntity?new NumericValue(((PassiveEntity) e).getBreedingAge()):Value.NULL); - put("despawn_timer", (e, a) -> e instanceof LivingEntity?new NumericValue(((LivingEntity) e).getDespawnCounter()):Value.NULL); - put("item", (e, a) -> (e instanceof ItemEntity)?ValueConversions.of(((ItemEntity) e).getStack()):Value.NULL); - put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getStack().getCount()):Value.NULL); + put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.level.dimension().location()))); // getDimId + put("height", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).height)); + put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width)); + put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight())); + put("age", (e, a) -> new NumericValue(e.tickCount)); + put("breeding_age", (e, a) -> e instanceof AgeableMob?new NumericValue(((AgeableMob) e).getAge()):Value.NULL); + put("despawn_timer", (e, a) -> e instanceof LivingEntity?new NumericValue(((LivingEntity) e).getNoActionTime()):Value.NULL); + put("item", (e, a) -> (e instanceof ItemEntity)?ValueConversions.of(((ItemEntity) e).getItem()):Value.NULL); + put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getItem().getCount()):Value.NULL); put("pickup_delay", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntityInterface) e).getPickupDelayCM()):Value.NULL); put("portal_cooldown", (e , a) ->new NumericValue(((EntityInterface)e).getPortalTimer())); put("portal_timer", (e , a) ->new NumericValue(((EntityInterface)e).getPublicNetherPortalCooldown())); // ItemEntity -> despawn timer via ssGetAge put("is_baby", (e, a) -> (e instanceof LivingEntity)?BooleanValue.of(((LivingEntity) e).isBaby()):Value.NULL); put("target", (e, a) -> { - if (e instanceof MobEntity) + if (e instanceof Mob) { - LivingEntity target = ((MobEntity) e).getTarget(); // there is also getAttacking in living.... + LivingEntity target = ((Mob) e).getTarget(); // there is also getAttacking in living.... if (target != null) { return new EntityValue(target); @@ -521,81 +518,81 @@ public class EntityValue extends Value return Value.NULL; }); put("home", (e, a) -> { - if (e instanceof MobEntity) + if (e instanceof Mob) { - return (((MobEntity) e).getPositionTargetRange () > 0)?new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((PathAwareEntity) e).getPositionTarget()):Value.FALSE; + return (((Mob) e).getRestrictRadius () > 0)?new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PathfinderMob) e).getRestrictCenter()):Value.FALSE; } return Value.NULL; }); put("spawn_point", (e, a) -> { - if (e instanceof ServerPlayerEntity spe) + if (e instanceof ServerPlayer spe) { - if (spe.getSpawnPointPosition() == null) return Value.FALSE; + if (spe.getRespawnPosition() == null) return Value.FALSE; return ListValue.of( - ValueConversions.of(spe.getSpawnPointPosition()), - ValueConversions.of(spe.getSpawnPointDimension()), - new NumericValue(spe.getSpawnAngle()), - BooleanValue.of(spe.isSpawnForced()) + ValueConversions.of(spe.getRespawnPosition()), + ValueConversions.of(spe.getRespawnDimension()), + new NumericValue(spe.getRespawnAngle()), + BooleanValue.of(spe.isRespawnForced()) ); } return Value.NULL; }); put("pose", (e, a) -> new StringValue(e.getPose().name().toLowerCase(Locale.ROOT))); - put("sneaking", (e, a) -> e.isSneaking()?Value.TRUE:Value.FALSE); + put("sneaking", (e, a) -> e.isShiftKeyDown()?Value.TRUE:Value.FALSE); put("sprinting", (e, a) -> e.isSprinting()?Value.TRUE:Value.FALSE); put("swimming", (e, a) -> e.isSwimming()?Value.TRUE:Value.FALSE); put("swinging", (e, a) -> { - if (e instanceof LivingEntity) return BooleanValue.of(((LivingEntity) e).handSwinging); + if (e instanceof LivingEntity) return BooleanValue.of(((LivingEntity) e).swinging); return Value.NULL; }); - put("air", (e, a) -> new NumericValue(e.getAir())); + put("air", (e, a) -> new NumericValue(e.getAirSupply())); put("language", (e, a)->{ - if(!(e instanceof ServerPlayerEntity)) + if(!(e instanceof ServerPlayer)) return NULL; String lang = ((ServerPlayerEntityInterface) e).getLanguage(); return StringValue.of(lang); }); put("persistence", (e, a) -> { - if (e instanceof MobEntity) return BooleanValue.of(((MobEntity) e).isPersistent()); + if (e instanceof Mob) return BooleanValue.of(((Mob) e).isPersistenceRequired()); return Value.NULL; }); put("hunger", (e, a) -> { - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).getHungerManager().getFoodLevel()); + if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getFoodLevel()); return Value.NULL; }); put("saturation", (e, a) -> { - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).getHungerManager().getSaturationLevel()); + if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getSaturationLevel()); return Value.NULL; }); put("exhaustion",(e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).getHungerManager().getExhaustion()); + if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getExhaustionLevel()); return Value.NULL; }); put("absorption",(e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).getAbsorptionAmount()); + if(e instanceof Player) return new NumericValue(((Player) e).getAbsorptionAmount()); return Value.NULL; }); put("xp",(e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).totalExperience); + if(e instanceof Player) return new NumericValue(((Player) e).totalExperience); return Value.NULL; }); put("xp_level", (e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).experienceLevel); + if(e instanceof Player) return new NumericValue(((Player) e).experienceLevel); return Value.NULL; }); put("xp_progress", (e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).experienceProgress); + if(e instanceof Player) return new NumericValue(((Player) e).experienceProgress); return Value.NULL; }); put("score", (e, a)->{ - if(e instanceof PlayerEntity) return new NumericValue(((PlayerEntity) e).getScore()); + if(e instanceof Player) return new NumericValue(((Player) e).getScore()); return Value.NULL; }); @@ -607,19 +604,19 @@ public class EntityValue extends Value return Value.NULL; }); put("gamemode", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - return new StringValue(((ServerPlayerEntity) e).interactionManager.getGameMode().getName()); + return new StringValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getName()); } return Value.NULL; }); put("path", (e, a) -> { - if (e instanceof MobEntity) + if (e instanceof Mob) { - Path path = ((MobEntity)e).getNavigation().getCurrentPath(); + Path path = ((Mob)e).getNavigation().getPath(); if (path == null) return Value.NULL; - return ValueConversions.fromPath((ServerWorld)e.getEntityWorld(), path); + return ValueConversions.fromPath((ServerLevel)e.getCommandSenderWorld(), path); } return Value.NULL; }); @@ -631,28 +628,28 @@ public class EntityValue extends Value if (e instanceof LivingEntity livingEntity) { Brain brain = livingEntity.getBrain(); - Map, Optional>> memories = brain.getMemories(); - Optional> optmemory = memories.get(moduleType); + Map, Optional>> memories = brain.getMemories(); + Optional> optmemory = memories.get(moduleType); if (optmemory==null || !optmemory.isPresent()) return Value.NULL; - Memory memory = optmemory.get(); - return ValueConversions.fromTimedMemory(e, memory.getExpiry(), memory.getValue()); + ExpirableValue memory = optmemory.get(); + return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue()); } return Value.NULL; }); put("gamemode_id", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - return new NumericValue(((ServerPlayerEntity) e).interactionManager.getGameMode().getId()); + return new NumericValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getId()); } return Value.NULL; }); put("permission_level", (e, a) -> { - if (e instanceof ServerPlayerEntity spe) + if (e instanceof ServerPlayer spe) { for (int i=4; i>=0; i--) { - if (spe.hasPermissionLevel(i)) + if (spe.hasPermissions(i)) return new NumericValue(i); } @@ -662,14 +659,14 @@ public class EntityValue extends Value }); put("player_type", (e, a) -> { - if (e instanceof PlayerEntity p) + if (e instanceof Player p) { if (e instanceof EntityPlayerMPFake) return new StringValue(((EntityPlayerMPFake) e).isAShadow?"shadow":"fake"); - MinecraftServer server = p.getEntityWorld().getServer(); - if (server.isDedicated()) return new StringValue("multiplayer"); - boolean runningLan = server.isRemote(); + MinecraftServer server = p.getCommandSenderWorld().getServer(); + if (server.isDedicatedServer()) return new StringValue("multiplayer"); + boolean runningLan = server.isPublished(); if (!runningLan) return new StringValue("singleplayer"); - boolean isowner = server.isHost(p.getGameProfile()); + boolean isowner = server.isSingleplayerOwner(p.getGameProfile()); if (isowner) return new StringValue("lan_host"); return new StringValue("lan player"); // realms? @@ -678,20 +675,20 @@ public class EntityValue extends Value }); put("client_brand", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - return StringValue.of(ServerNetworkHandler.getPlayerStatus((ServerPlayerEntity) e)); + return StringValue.of(ServerNetworkHandler.getPlayerStatus((ServerPlayer) e)); } return Value.NULL; }); - put("team", (e, a) -> e.getScoreboardTeam()==null?Value.NULL:new StringValue(e.getScoreboardTeam().getName())); + put("team", (e, a) -> e.getTeam()==null?Value.NULL:new StringValue(e.getTeam().getName())); put("ping", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - ServerPlayerEntity spe = (ServerPlayerEntity) e; - return new NumericValue(spe.pingMilliseconds); + ServerPlayer spe = (ServerPlayer) e; + return new NumericValue(spe.latency); } return Value.NULL; }); @@ -707,10 +704,10 @@ public class EntityValue extends Value if (a == null) { List effects = new ArrayList<>(); - for (StatusEffectInstance p : ((LivingEntity) e).getStatusEffects()) + for (MobEffectInstance p : ((LivingEntity) e).getActiveEffects()) { effects.add(ListValue.of( - new StringValue(p.getTranslationKey().replaceFirst("^effect\\.minecraft\\.", "")), + new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")), new NumericValue(p.getAmplifier()), new NumericValue(p.getDuration()) )); @@ -718,12 +715,12 @@ public class EntityValue extends Value return ListValue.wrap(effects); } String effectName = a.getString(); - StatusEffect potion = Registry.STATUS_EFFECT.get(InputValidator.identifierOf(effectName)); + MobEffect potion = Registry.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (potion == null) throw new InternalExpressionException("No such an effect: "+effectName); - if (!((LivingEntity) e).hasStatusEffect(potion)) + if (!((LivingEntity) e).hasEffect(potion)) return Value.NULL; - StatusEffectInstance pe = ((LivingEntity) e).getStatusEffect(potion); + MobEffectInstance pe = ((LivingEntity) e).getEffect(potion); return ListValue.of( new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration()) ); }); @@ -741,43 +738,43 @@ public class EntityValue extends Value }); put("may_fly", (e, a) -> { - if (e instanceof ServerPlayerEntity player) { - return BooleanValue.of(player.getAbilities().allowFlying); + if (e instanceof ServerPlayer player) { + return BooleanValue.of(player.getAbilities().mayfly); } return Value.NULL; }); put("flying", (e, v) -> { - if (e instanceof ServerPlayerEntity player) { + if (e instanceof ServerPlayer player) { return BooleanValue.of(player.getAbilities().flying); } return Value.NULL; }); put("may_build", (e, v) -> { - if (e instanceof ServerPlayerEntity player) { - return BooleanValue.of(player.getAbilities().allowModifyWorld); + if (e instanceof ServerPlayer player) { + return BooleanValue.of(player.getAbilities().mayBuild); } return Value.NULL; }); put("insta_build", (e, v) -> { - if (e instanceof ServerPlayerEntity player) { - return BooleanValue.of(player.getAbilities().creativeMode); + if (e instanceof ServerPlayer player) { + return BooleanValue.of(player.getAbilities().instabuild); } return Value.NULL; }); put("fly_speed", (e, v) -> { - if (e instanceof ServerPlayerEntity player) { - return NumericValue.of(player.getAbilities().getFlySpeed()); + if (e instanceof ServerPlayer player) { + return NumericValue.of(player.getAbilities().getFlyingSpeed()); } return Value.NULL; }); put("walk_speed", (e, v) -> { - if (e instanceof ServerPlayerEntity player) { - return NumericValue.of(player.getAbilities().getWalkSpeed()); + if (e instanceof ServerPlayer player) { + return NumericValue.of(player.getAbilities().getWalkingSpeed()); } return Value.NULL; }); @@ -789,31 +786,31 @@ public class EntityValue extends Value if (where == null) throw new InternalExpressionException("Unknown inventory slot: "+a.getString()); if (e instanceof LivingEntity) - return ValueConversions.of(((LivingEntity)e).getEquippedStack(where)); + return ValueConversions.of(((LivingEntity)e).getItemBySlot(where)); return Value.NULL; }); put("selected_slot", (e, a) -> { - if (e instanceof PlayerEntity) - return new NumericValue(((PlayerEntity) e).getInventory().selectedSlot); //getInventory + if (e instanceof Player) + return new NumericValue(((Player) e).getInventory().selected); //getInventory return Value.NULL; }); put("active_block", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayerEntity) e).interactionManager); + ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); BlockPos pos = manager.getCurrentBreakingBlock(); if (pos == null) return Value.NULL; - return new BlockValue(null, (ServerWorld) e.world, pos); + return new BlockValue(null, (ServerLevel) e.level, pos); } return Value.NULL; }); put("breaking_progress", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayerEntity) e).interactionManager); + ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); int progress = manager.getCurrentBlockBreakingProgress(); if (progress < 0) return Value.NULL; return new NumericValue(progress); @@ -829,7 +826,7 @@ public class EntityValue extends Value if (index < 0 || index > 5) throw new InternalExpressionException("Facing order should be between -6 and 5"); - return new StringValue(Direction.getEntityFacingOrder(e)[index].asString()); + return new StringValue(Direction.orderedByNearest(e)[index].getSerializedName()); }); put("trace", (e, a) -> @@ -873,7 +870,7 @@ public class EntityValue extends Value } } } - else if (e instanceof ServerPlayerEntity && ((ServerPlayerEntity) e).interactionManager.isCreative()) + else if (e instanceof ServerPlayer && ((ServerPlayer) e).gameMode.isCreative()) { reach = 5.0f; } @@ -887,11 +884,11 @@ public class EntityValue extends Value hitres = Tracer.rayTraceBlocks(e, 1, reach, liquids); if (hitres == null) return Value.NULL; - if (exact && hitres.getType() != HitResult.Type.MISS) return ValueConversions.of(hitres.getPos()); + if (exact && hitres.getType() != HitResult.Type.MISS) return ValueConversions.of(hitres.getLocation()); switch (hitres.getType()) { case MISS: return Value.NULL; - case BLOCK: return new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((BlockHitResult)hitres).getBlockPos() ); + case BLOCK: return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((BlockHitResult)hitres).getBlockPos() ); case ENTITY: return new EntityValue(((EntityHitResult)hitres).getEntity()); } return Value.NULL; @@ -902,11 +899,11 @@ public class EntityValue extends Value LivingEntity el = (LivingEntity)e; if (a == null) { - AttributeContainer container = el.getAttributes(); - return MapValue.wrap(Registry.ATTRIBUTE.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(Registry.ATTRIBUTE.getId(aa)), aa -> NumericValue.of(container.getValue(aa))))); + AttributeMap container = el.getAttributes(); + return MapValue.wrap(Registry.ATTRIBUTE.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(Registry.ATTRIBUTE.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); } - Identifier id = InputValidator.identifierOf(a.getString()); - EntityAttribute attrib = Registry.ATTRIBUTE.getOrEmpty(id).orElseThrow( + ResourceLocation id = InputValidator.identifierOf(a.getString()); + Attribute attrib = Registry.ATTRIBUTE.getOptional(id).orElseThrow( () -> new InternalExpressionException("Unknown attribute: "+a.getString()) ); if (!el.getAttributes().hasAttribute(attrib)) return Value.NULL; @@ -914,13 +911,13 @@ public class EntityValue extends Value }); put("nbt",(e, a) -> { - NbtCompound nbttagcompound = e.writeNbt((new NbtCompound())); + CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); if (a==null) return new NBTSerializableValue(nbttagcompound); return new NBTSerializableValue(nbttagcompound).get(a); }); - put("category",(e,a)->{return new StringValue(e.getType().getSpawnGroup().toString().toLowerCase(Locale.ROOT));}); + put("category",(e,a)->{return new StringValue(e.getType().getCategory().toString().toLowerCase(Locale.ROOT));}); }}; public void set(String what, Value toWhat) @@ -951,55 +948,55 @@ public class EntityValue extends Value !Float.isFinite(pitch) || Float.isNaN(pitch) ) return; - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { // this forces position but doesn't angles for some reason. Need both in the API in the future. - EnumSet set = EnumSet.noneOf(PlayerPositionLookS2CPacket.Flag.class); - set.add(PlayerPositionLookS2CPacket.Flag.X_ROT); - set.add(PlayerPositionLookS2CPacket.Flag.Y_ROT); - ((ServerPlayerEntity)e).networkHandler.requestTeleport(x, y, z, yaw, pitch, set ); + EnumSet set = EnumSet.noneOf(ClientboundPlayerPositionPacket.RelativeArgument.class); + set.add(ClientboundPlayerPositionPacket.RelativeArgument.X_ROT); + set.add(ClientboundPlayerPositionPacket.RelativeArgument.Y_ROT); + ((ServerPlayer)e).connection.teleport(x, y, z, yaw, pitch, set ); } else { - e.refreshPositionAndAngles(x, y, z, yaw, pitch); + e.moveTo(x, y, z, yaw, pitch); // we were sending to players for not-living entites, that were untracked. Living entities should be tracked. //((ServerWorld) e.getEntityWorld()).getChunkManager().sendToNearbyPlayers(e, new EntityS2CPacket.(e)); if (e instanceof LivingEntity le) { - le.prevBodyYaw = le.prevYaw = yaw; - le.prevHeadYaw = le.headYaw = yaw; + le.yBodyRotO = le.yRotO = yaw; + le.yHeadRotO = le.yHeadRot = yaw; // seems universal for: //e.setHeadYaw(yaw); //e.setYaw(yaw); } else { - ((ServerWorld) e.getEntityWorld()).getChunkManager().sendToNearbyPlayers(e, new EntityPositionS2CPacket(e)); + ((ServerLevel) e.getCommandSenderWorld()).getChunkSource().broadcastAndSend(e, new ClientboundTeleportEntityPacket(e)); } } } private static void updateVelocity(Entity e, double scale) { - e.velocityModified = true; + e.hurtMarked = true; if (Math.abs(scale) > 10000) - CarpetScriptServer.LOG.warn("Moved entity "+e.getEntityName()+" "+e.getName()+" at " +e.getPos()+" extremely fast: "+e.getVelocity()); + CarpetScriptServer.LOG.warn("Moved entity "+e.getScoreboardName()+" "+e.getName()+" at " +e.position()+" extremely fast: "+e.getDeltaMovement()); //((ServerWorld)e.getEntityWorld()).method_14178().sendToNearbyPlayers(e, new EntityVelocityUpdateS2CPacket(e)); } private static final Map> featureModifiers = new HashMap>() {{ put("remove", (entity, value) -> entity.discard()); // using discard here - will see other options if valid - put("age", (e, v) -> e.age = Math.abs((int)NumericValue.asNumber(v).getLong()) ); + put("age", (e, v) -> e.tickCount = Math.abs((int)NumericValue.asNumber(v).getLong()) ); put("health", (e, v) -> { float health = (float) NumericValue.asNumber(v).getDouble(); - if (health <= 0f && e instanceof ServerPlayerEntity player) + if (health <= 0f && e instanceof ServerPlayer player) { - if (player.currentScreenHandler != null) + if (player.containerMenu != null) { // if player dies with open container, then that causes NPE on the client side // its a client side bug that may never surface unless vanilla gets into scripting at some point // bug: #228 - player.closeHandledScreen(); + player.closeContainer(); } ((LivingEntity) e).setHealth(health); } @@ -1008,61 +1005,61 @@ public class EntityValue extends Value put("may_fly", (e, v) -> { boolean mayFly = v.getBoolean(); - if (e instanceof ServerPlayerEntity player) { - player.getAbilities().allowFlying = mayFly; + if (e instanceof ServerPlayer player) { + player.getAbilities().mayfly = mayFly; if (!mayFly && player.getAbilities().flying) { player.getAbilities().flying = false; } - player.sendAbilitiesUpdate(); + player.onUpdateAbilities(); } }); put("flying", (e, v) -> { boolean flying = v.getBoolean(); - if (e instanceof ServerPlayerEntity player) { + if (e instanceof ServerPlayer player) { player.getAbilities().flying = flying; - player.sendAbilitiesUpdate(); + player.onUpdateAbilities(); } }); put("may_build", (e, v) -> { boolean mayBuild = v.getBoolean(); - if (e instanceof ServerPlayerEntity player) { - player.getAbilities().allowModifyWorld = mayBuild; - player.sendAbilitiesUpdate(); + if (e instanceof ServerPlayer player) { + player.getAbilities().mayBuild = mayBuild; + player.onUpdateAbilities(); } }); put("insta_build", (e, v) -> { boolean instaBuild = v.getBoolean(); - if (e instanceof ServerPlayerEntity player) { - player.getAbilities().creativeMode = instaBuild; - player.sendAbilitiesUpdate(); + if (e instanceof ServerPlayer player) { + player.getAbilities().instabuild = instaBuild; + player.onUpdateAbilities(); } }); put("fly_speed", (e, v) -> { float flySpeed = NumericValue.asNumber(v).getFloat(); - if (e instanceof ServerPlayerEntity player) { - player.getAbilities().setFlySpeed(flySpeed); - player.sendAbilitiesUpdate(); + if (e instanceof ServerPlayer player) { + player.getAbilities().setFlyingSpeed(flySpeed); + player.onUpdateAbilities(); } }); put("walk_speed", (e, v) -> { float walkSpeed = NumericValue.asNumber(v).getFloat(); - if (e instanceof ServerPlayerEntity player) { - player.getAbilities().setWalkSpeed(walkSpeed); - player.sendAbilitiesUpdate(); + if (e instanceof ServerPlayer player) { + player.getAbilities().setWalkingSpeed(walkSpeed); + player.onUpdateAbilities(); } }); put("selected_slot", (e, v) -> { - if (e instanceof ServerPlayerEntity player) + if (e instanceof ServerPlayer player) { int slot = NumericValue.asNumber(v).getInt(); - player.networkHandler.sendPacket(new UpdateSelectedSlotS2CPacket(slot)); + player.connection.send(new ClientboundSetCarriedItemPacket(slot)); } }); @@ -1108,44 +1105,44 @@ public class EntityValue extends Value NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), NumericValue.asNumber(coords.get(2)).getDouble(), - e.getYaw(), - e.getPitch() + e.getYRot(), + e.getXRot() ); }); put("x", (e, v) -> { - updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.getYaw(), e.getPitch()); + updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.getYRot(), e.getXRot()); }); put("y", (e, v) -> { - updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.getYaw(), e.getPitch()); + updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.getYRot(), e.getXRot()); }); put("z", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.getYaw(), e.getPitch()); + updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.getYRot(), e.getXRot()); }); put("yaw", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float)NumericValue.asNumber(v).getDouble()) % 360, e.getPitch()); + updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float)NumericValue.asNumber(v).getDouble()) % 360, e.getXRot()); }); put("head_yaw", (e, v) -> { if (e instanceof LivingEntity) { - e.setHeadYaw((float)NumericValue.asNumber(v).getDouble() % 360); + e.setYHeadRot((float)NumericValue.asNumber(v).getDouble() % 360); } }); put("body_yaw", (e, v) -> { if (e instanceof LivingEntity) { - e.setYaw((float)NumericValue.asNumber(v).getDouble() % 360); + e.setYRot((float)NumericValue.asNumber(v).getDouble() % 360); } }); put("pitch", (e, v) -> { - updatePosition(e, e.getX(), e.getY(), e.getZ(), e.getYaw(), MathHelper.clamp((float)NumericValue.asNumber(v).getDouble(), -90, 90)); + updatePosition(e, e.getX(), e.getY(), e.getZ(), e.getYRot(), Mth.clamp((float)NumericValue.asNumber(v).getDouble(), -90, 90)); }); put("look", (e, v) -> { @@ -1154,13 +1151,13 @@ public class EntityValue extends Value float x = NumericValue.asNumber(vec.get(0)).getFloat(); float y = NumericValue.asNumber(vec.get(1)).getFloat(); float z = NumericValue.asNumber(vec.get(2)).getFloat(); - float l = MathHelper.sqrt(x*x + y*y + z*z); + float l = Mth.sqrt(x*x + y*y + z*z); if(l==0) return; x /= l; y /= l; z /= l; float pitch = (float) -Math.asin(y) / 0.017453292F; - float yaw = (float) (x==0 && z==0 ? e.getYaw() : MathHelper.atan2(-x,z) / 0.017453292F); + float yaw = (float) (x==0 && z==0 ? e.getYRot() : Mth.atan2(-x,z) / 0.017453292F); updatePosition(e, e.getX(), e.getY(), e.getZ(), yaw, pitch); }); @@ -1178,8 +1175,8 @@ public class EntityValue extends Value e.getX() + NumericValue.asNumber(coords.get(0)).getDouble(), e.getY() + NumericValue.asNumber(coords.get(1)).getDouble(), e.getZ() + NumericValue.asNumber(coords.get(2)).getDouble(), - e.getYaw(), - e.getPitch() + e.getYRot(), + e.getXRot() ); }); @@ -1193,28 +1190,28 @@ public class EntityValue extends Value double dx = NumericValue.asNumber(coords.get(0)).getDouble(); double dy = NumericValue.asNumber(coords.get(1)).getDouble(); double dz = NumericValue.asNumber(coords.get(2)).getDouble(); - e.setVelocity(dx, dy, dz); - updateVelocity(e, MathHelper.absMax(MathHelper.absMax(dx, dy), dz)); + e.setDeltaMovement(dx, dy, dz); + updateVelocity(e, Mth.absMax(Mth.absMax(dx, dy), dz)); }); put("motion_x", (e, v) -> { - Vec3d velocity = e.getVelocity(); + Vec3 velocity = e.getDeltaMovement(); double dv = NumericValue.asNumber(v).getDouble(); - e.setVelocity(dv, velocity.y, velocity.z); + e.setDeltaMovement(dv, velocity.y, velocity.z); updateVelocity(e, dv); }); put("motion_y", (e, v) -> { - Vec3d velocity = e.getVelocity(); + Vec3 velocity = e.getDeltaMovement(); double dv = NumericValue.asNumber(v).getDouble(); - e.setVelocity(velocity.x, dv, velocity.z); + e.setDeltaMovement(velocity.x, dv, velocity.z); updateVelocity(e, dv); }); put("motion_z", (e, v) -> { - Vec3d velocity = e.getVelocity(); + Vec3 velocity = e.getDeltaMovement(); double dv = NumericValue.asNumber(v).getDouble(); - e.setVelocity(velocity.x, velocity.y, dv); + e.setDeltaMovement(velocity.x, velocity.y, dv); updateVelocity(e, dv); }); @@ -1225,12 +1222,12 @@ public class EntityValue extends Value throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } List coords = ((ListValue) v).getItems(); - e.addVelocity( + e.push( NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), NumericValue.asNumber(coords.get(2)).getDouble() ); - updateVelocity(e, e.getVelocity().length()); + updateVelocity(e, e.getDeltaMovement().length()); }); put("custom_name", (e, v) -> { @@ -1252,7 +1249,7 @@ public class EntityValue extends Value put("persistence", (e, v) -> { - if (!(e instanceof MobEntity)) return; + if (!(e instanceof Mob)) return; if (v == null) v = Value.TRUE; ((MobEntityInterface)e).setPersistence(v.getBoolean()); }); @@ -1263,9 +1260,9 @@ public class EntityValue extends Value { e.startRiding(((EntityValue) v).getEntity(),true); } - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - ((ServerPlayerEntity)e).networkHandler.sendPacket(new EntityPassengersSetS2CPacket(e)); + ((ServerPlayer)e).connection.send(new ClientboundSetPassengersPacket(e)); //... } }); @@ -1274,7 +1271,7 @@ public class EntityValue extends Value v = Value.TRUE; ((EntityInterface)e).setPermanentVehicle(v.getBoolean()); }); - put("drop_passengers", (e, v) -> e.removeAllPassengers()); + put("drop_passengers", (e, v) -> e.ejectPassengers()); put("mount_passengers", (e, v) -> { if (v==null) throw new InternalExpressionException("'mount_passengers' needs entities to ride"); @@ -1289,17 +1286,17 @@ public class EntityValue extends Value if (v==null) throw new InternalExpressionException("'tag' requires parameters"); if (v instanceof ListValue) - for (Value element : ((ListValue) v).getItems()) e.addScoreboardTag(element.getString()); + for (Value element : ((ListValue) v).getItems()) e.addTag(element.getString()); else - e.addScoreboardTag(v.getString()); + e.addTag(v.getString()); }); put("clear_tag", (e, v) -> { if (v==null) throw new InternalExpressionException("'clear_tag' requires parameters"); if (v instanceof ListValue) - for (Value element : ((ListValue) v).getItems()) e.removeScoreboardTag(element.getString()); + for (Value element : ((ListValue) v).getItems()) e.removeTag(element.getString()); else - e.removeScoreboardTag(v.getString()); + e.removeTag(v.getString()); }); //put("target", (e, v) -> { // // attacks indefinitely - might need to do it through tasks @@ -1311,29 +1308,29 @@ public class EntityValue extends Value //}); put("breeding_age", (e, v) -> { - if (e instanceof PassiveEntity) + if (e instanceof AgeableMob) { - ((PassiveEntity) e).setBreedingAge((int)NumericValue.asNumber(v).getLong()); + ((AgeableMob) e).setAge((int)NumericValue.asNumber(v).getLong()); } }); put("talk", (e, v) -> { // attacks indefinitely - if (e instanceof MobEntity) + if (e instanceof Mob) { - ((MobEntity) e).playAmbientSound(); + ((Mob) e).playAmbientSound(); } }); put("home", (e, v) -> { - if (!(e instanceof PathAwareEntity)) + if (!(e instanceof PathfinderMob)) return; - PathAwareEntity ec = (PathAwareEntity)e; + PathfinderMob ec = (PathfinderMob)e; if (v == null) throw new InternalExpressionException("'home' requires at least one position argument, and optional distance, or null to cancel"); if (v instanceof NullValue) { - ec.setPositionTarget(BlockPos.ORIGIN, -1); + ec.restrictTo(BlockPos.ZERO, -1); Map tasks = ((MobEntityInterface)ec).getTemporaryTasks(); - ((MobEntityInterface)ec).getAI(false).remove(tasks.get("home")); + ((MobEntityInterface)ec).getAI(false).removeGoal(tasks.get("home")); tasks.remove("home"); return; } @@ -1358,34 +1355,34 @@ public class EntityValue extends Value } else throw new InternalExpressionException("'home' requires at least one position argument, and optional distance"); - ec.setPositionTarget(pos, distance); + ec.restrictTo(pos, distance); Map tasks = ((MobEntityInterface)ec).getTemporaryTasks(); if (!tasks.containsKey("home")) { - Goal task = new GoToWalkTargetGoal(ec, 1.0D); + Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); tasks.put("home", task); - ((MobEntityInterface)ec).getAI(false).add(10, task); + ((MobEntityInterface)ec).getAI(false).addGoal(10, task); } }); //requires mixing put("spawn_point", (e, a) -> { - if (!(e instanceof ServerPlayerEntity spe)) return; + if (!(e instanceof ServerPlayer spe)) return; if (a == null) { - spe.setSpawnPoint(null, null, 0, false, false); + spe.setRespawnPosition(null, null, 0, false, false); } else if (a instanceof ListValue) { List params= ((ListValue) a).getItems(); Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); BlockPos pos = new BlockPos(blockLocator.vec); - RegistryKey world = spe.getEntityWorld().getRegistryKey(); - float angle = spe.getHeadYaw(); + ResourceKey world = spe.getCommandSenderWorld().dimension(); + float angle = spe.getYHeadRot(); boolean forced = false; if (params.size() > blockLocator.offset) { Value worldValue = params.get(blockLocator.offset+0); - world = ValueConversions.dimFromValue(worldValue, spe.getServer()).getRegistryKey(); + world = ValueConversions.dimFromValue(worldValue, spe.getServer()).dimension(); if (params.size() > blockLocator.offset+1) { angle = NumericValue.asNumber(params.get(blockLocator.offset+1), "angle").getFloat(); @@ -1395,17 +1392,17 @@ public class EntityValue extends Value } } } - spe.setSpawnPoint(world, pos, angle, forced, false); + spe.setRespawnPosition(world, pos, angle, forced, false); } else if (a instanceof BlockValue bv) { if (bv.getPos()==null || bv.getWorld() == null) throw new InternalExpressionException("block for spawn modification should be localised in the world"); - spe.setSpawnPoint(bv.getWorld().getRegistryKey(), bv.getPos(), e.getYaw(), true, false); // yaw + spe.setRespawnPosition(bv.getWorld().dimension(), bv.getPos(), e.getYRot(), true, false); // yaw } else if (a.isNull()) { - spe.setSpawnPoint(null, null, 0, false, false); + spe.setRespawnPosition(null, null, 0, false, false); } else { @@ -1418,7 +1415,7 @@ public class EntityValue extends Value { if (e instanceof ItemEntity) { - ((ItemEntity) e).setPickupDelay((int)NumericValue.asNumber(v).getLong()); + ((ItemEntity) e).setPickUpDelay((int)NumericValue.asNumber(v).getLong()); } }); @@ -1426,7 +1423,7 @@ public class EntityValue extends Value { if (e instanceof LivingEntity) { - ((LivingEntity) e).setDespawnCounter((int)NumericValue.asNumber(v).getLong()); + ((LivingEntity) e).setNoActionTime((int)NumericValue.asNumber(v).getLong()); } }); @@ -1446,25 +1443,25 @@ public class EntityValue extends Value put("ai", (e, v) -> { - if (e instanceof MobEntity) + if (e instanceof Mob) { - ((MobEntity) e).setAiDisabled(!v.getBoolean()); + ((Mob) e).setNoAi(!v.getBoolean()); } }); put("no_clip", (e, v) -> { if (v == null) - e.noClip = true; + e.noPhysics = true; else - e.noClip = v.getBoolean(); + e.noPhysics = v.getBoolean(); }); put("effect", (e, v) -> { if (!(e instanceof LivingEntity le)) return; if (v == null) { - le.clearStatusEffects(); + le.removeAllEffects(); return; } else if (v instanceof ListValue) @@ -1473,18 +1470,18 @@ public class EntityValue extends Value if (lv.size() >= 1 && lv.size() <= 6) { String effectName = lv.get(0).getString(); - StatusEffect effect = Registry.STATUS_EFFECT.get(InputValidator.identifierOf(effectName)); + MobEffect effect = Registry.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) throw new InternalExpressionException("Wrong effect name: "+effectName); if (lv.size() == 1) { - le.removeStatusEffect(effect); + le.removeEffect(effect); return; } int duration = (int)NumericValue.asNumber(lv.get(1)).getLong(); if (duration <= 0) { - le.removeStatusEffect(effect); + le.removeEffect(effect); return; } int amplifier = 0; @@ -1499,28 +1496,28 @@ public class EntityValue extends Value boolean ambient = false; if (lv.size() > 5) showIcon = lv.get(5).getBoolean(); - le.addStatusEffect(new StatusEffectInstance(effect, duration, amplifier, ambient, showParticles, showIcon)); + le.addEffect(new MobEffectInstance(effect, duration, amplifier, ambient, showParticles, showIcon)); return; } } else { String effectName = v.getString(); - StatusEffect effect = Registry.STATUS_EFFECT.get(InputValidator.identifierOf(effectName)); + MobEffect effect = Registry.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) throw new InternalExpressionException("Wrong effect name: "+effectName); - le.removeStatusEffect(effect); + le.removeEffect(effect); return; } throw new InternalExpressionException("'effect' needs either no arguments (clear) or effect name, duration, and optional amplifier, show particles, show icon and ambient"); }); put("gamemode", (e,v)->{ - if(!(e instanceof ServerPlayerEntity)) return; - GameMode toSet = v instanceof NumericValue ? - GameMode.byId(((NumericValue) v).getInt(), null) : - GameMode.byName(v.getString().toLowerCase(Locale.ROOT), null); - if (toSet != null) ((ServerPlayerEntity) e).changeGameMode(toSet); + if(!(e instanceof ServerPlayer)) return; + GameType toSet = v instanceof NumericValue ? + GameType.byId(((NumericValue) v).getInt(), null) : + GameType.byName(v.getString().toLowerCase(Locale.ROOT), null); + if (toSet != null) ((ServerPlayer) e).setGameMode(toSet); }); put("jumping",(e,v)->{ @@ -1542,13 +1539,13 @@ public class EntityValue extends Value put("swing", (e, v) -> { if (e instanceof LivingEntity) { - Hand hand = Hand.MAIN_HAND; + InteractionHand hand = InteractionHand.MAIN_HAND; if (v != null) { String handString = v.getString().toLowerCase(Locale.ROOT); - if (handString.equals("offhand") || handString.equals("off_hand")) hand = Hand.OFF_HAND; + if (handString.equals("offhand") || handString.equals("off_hand")) hand = InteractionHand.OFF_HAND; } - ((LivingEntity)e).swingHand(hand, true); + ((LivingEntity)e).swing(hand, true); } }); @@ -1558,92 +1555,92 @@ public class EntityValue extends Value put("invulnerable",(e,v)-> { boolean invulnerable = v.getBoolean(); - if (e instanceof ServerPlayerEntity player) { + if (e instanceof ServerPlayer player) { player.getAbilities().invulnerable = invulnerable; - player.sendAbilitiesUpdate(); + player.onUpdateAbilities(); } else { e.setInvulnerable(invulnerable); } }); - put("fire",(e,v)-> e.setFireTicks((int)NumericValue.asNumber(v).getLong())); - put("frost",(e,v)-> e.setFrozenTicks((int)NumericValue.asNumber(v).getLong())); + put("fire",(e,v)-> e.setRemainingFireTicks((int)NumericValue.asNumber(v).getLong())); + put("frost",(e,v)-> e.setTicksFrozen((int)NumericValue.asNumber(v).getLong())); put("hunger", (e, v)-> { - if(e instanceof PlayerEntity) ((PlayerEntity) e).getHungerManager().setFoodLevel((int) NumericValue.asNumber(v).getLong()); + if(e instanceof Player) ((Player) e).getFoodData().setFoodLevel((int) NumericValue.asNumber(v).getLong()); }); put("exhaustion", (e, v)-> { - if(e instanceof PlayerEntity) ((PlayerEntity) e).getHungerManager().setExhaustion(NumericValue.asNumber(v).getFloat()); + if(e instanceof Player) ((Player) e).getFoodData().setExhaustion(NumericValue.asNumber(v).getFloat()); }); put("add_exhaustion", (e, v)-> { - if (e instanceof PlayerEntity) ((PlayerEntity) e).getHungerManager().addExhaustion(NumericValue.asNumber(v).getFloat()); + if (e instanceof Player) ((Player) e).getFoodData().addExhaustion(NumericValue.asNumber(v).getFloat()); }); put("absorption", (e, v) -> { - if (e instanceof PlayerEntity) ((PlayerEntity) e).setAbsorptionAmount(NumericValue.asNumber(v, "absorbtion").getFloat()); + if (e instanceof Player) ((Player) e).setAbsorptionAmount(NumericValue.asNumber(v, "absorbtion").getFloat()); }); put("add_xp", (e, v) -> { - if (e instanceof PlayerEntity) ((PlayerEntity) e).addExperience(NumericValue.asNumber(v, "add_xp").getInt()); + if (e instanceof Player) ((Player) e).giveExperiencePoints(NumericValue.asNumber(v, "add_xp").getInt()); }); put("xp_level", (e, v) -> { - if (e instanceof PlayerEntity) ((PlayerEntity) e).addExperienceLevels(NumericValue.asNumber(v, "xp_level").getInt()-((PlayerEntity) e).experienceLevel); + if (e instanceof Player) ((Player) e).giveExperienceLevels(NumericValue.asNumber(v, "xp_level").getInt()-((Player) e).experienceLevel); }); put("xp_progress", (e, v) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { - ServerPlayerEntity p = (ServerPlayerEntity) e; + ServerPlayer p = (ServerPlayer) e; p.experienceProgress = NumericValue.asNumber(v, "xp_progress").getFloat(); - p.networkHandler.sendPacket(new ExperienceBarUpdateS2CPacket(p.experienceProgress, p.totalExperience, p.experienceLevel)); + p.connection.send(new ClientboundSetExperiencePacket(p.experienceProgress, p.totalExperience, p.experienceLevel)); } }); put("xp_score", (e, v) -> { - if (e instanceof PlayerEntity) ((PlayerEntity) e).setScore(NumericValue.asNumber(v, "xp_score").getInt()); + if (e instanceof Player) ((Player) e).setScore(NumericValue.asNumber(v, "xp_score").getInt()); }); put("saturation", (e, v)-> { - if(e instanceof PlayerEntity) ((PlayerEntity) e).getHungerManager().setSaturationLevel(NumericValue.asNumber(v, "saturation").getFloat()); + if(e instanceof Player) ((Player) e).getFoodData().setSaturation(NumericValue.asNumber(v, "saturation").getFloat()); }); - put("air", (e, v) -> e.setAir(NumericValue.asNumber(v, "air").getInt())); + put("air", (e, v) -> e.setAirSupply(NumericValue.asNumber(v, "air").getInt())); put("breaking_progress", (e, a) -> { - if (e instanceof ServerPlayerEntity) + if (e instanceof ServerPlayer) { int progress = (a == null || a.isNull())?-1:NumericValue.asNumber(a).getInt(); - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayerEntity) e).interactionManager); + ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); manager.setBlockBreakingProgress(progress); } }); put("nbt", (e, v) -> { - if (!(e instanceof PlayerEntity)) + if (!(e instanceof Player)) { - UUID uUID = e.getUuid(); + UUID uUID = e.getUUID(); Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof NBTSerializableValue) { - e.readNbt(((NBTSerializableValue) tagValue).getCompoundTag()); - e.setUuid(uUID); + e.load(((NBTSerializableValue) tagValue).getCompoundTag()); + e.setUUID(uUID); } } }); put("nbt_merge", (e, v) -> { - if (!(e instanceof PlayerEntity)) + if (!(e instanceof Player)) { - UUID uUID = e.getUuid(); + UUID uUID = e.getUUID(); Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof NBTSerializableValue) { - NbtCompound nbttagcompound = e.writeNbt((new NbtCompound())); - nbttagcompound.copyFrom(((NBTSerializableValue) tagValue).getCompoundTag()); - e.readNbt(nbttagcompound); - e.setUuid(uUID); + CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); + nbttagcompound.merge(((NBTSerializableValue) tagValue).getCompoundTag()); + e.load(nbttagcompound); + e.setUUID(uUID); } } }); @@ -1663,12 +1660,12 @@ public class EntityValue extends Value } @Override - public NbtElement toTag(boolean force) + public net.minecraft.nbt.Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - NbtCompound tag = new NbtCompound(); - tag.put("Data", getEntity().writeNbt( new NbtCompound())); - tag.put("Name", NbtString.of(Registry.ENTITY_TYPE.getId(getEntity().getType()).toString())); + CompoundTag tag = new CompoundTag(); + tag.put("Data", getEntity().saveWithoutId( new CompoundTag())); + tag.put("Name", StringTag.valueOf(Registry.ENTITY_TYPE.getKey(getEntity().getType()).toString())); return tag; } } diff --git a/src/main/java/carpet/script/value/FormattedTextValue.java b/src/main/java/carpet/script/value/FormattedTextValue.java index ae71913f..6755d8a9 100644 --- a/src/main/java/carpet/script/value/FormattedTextValue.java +++ b/src/main/java/carpet/script/value/FormattedTextValue.java @@ -1,36 +1,36 @@ package carpet.script.value; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.text.BaseText; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; public class FormattedTextValue extends StringValue { - Text text; - public FormattedTextValue(Text text) + Component text; + public FormattedTextValue(Component text) { super(null); this.text = text; } public static Value combine(Value left, Value right) { - BaseText text; + BaseComponent text; if (left instanceof FormattedTextValue) { - text = (BaseText) ((FormattedTextValue) left).getText().shallowCopy(); + text = (BaseComponent) ((FormattedTextValue) left).getText().copy(); } else { if (left instanceof NullValue) return right; - text = new LiteralText(left.getString()); + text = new TextComponent(left.getString()); } if (right instanceof FormattedTextValue) { - text.append(((FormattedTextValue) right).getText().shallowCopy()); + text.append(((FormattedTextValue) right).getText().copy()); return new FormattedTextValue(text); } else @@ -42,7 +42,7 @@ public class FormattedTextValue extends StringValue } } - public static Value of(Text text) { + public static Value of(Component text) { if (text == null) return Value.NULL; return new FormattedTextValue(text); } @@ -69,16 +69,16 @@ public class FormattedTextValue extends StringValue return "text"; } - public Text getText() + public Component getText() { return text; } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return NbtString.of(Text.Serializer.toJson(text)); + return StringTag.valueOf(Component.Serializer.toJson(text)); } @Override @@ -88,16 +88,16 @@ public class FormattedTextValue extends StringValue public String serialize() { - return Text.Serializer.toJson(text); + return Component.Serializer.toJson(text); } public static FormattedTextValue deserialize(String serialized) { - return new FormattedTextValue(Text.Serializer.fromJson(serialized)); + return new FormattedTextValue(Component.Serializer.fromJson(serialized)); } - public static Text getTextByValue(Value value) { - return (value instanceof FormattedTextValue) ? ((FormattedTextValue) value).getText() : new LiteralText(value.getString()); + public static Component getTextByValue(Value value) { + return (value instanceof FormattedTextValue) ? ((FormattedTextValue) value).getText() : new TextComponent(value.getString()); } } diff --git a/src/main/java/carpet/script/value/FrameworkValue.java b/src/main/java/carpet/script/value/FrameworkValue.java index a330876f..a432974e 100644 --- a/src/main/java/carpet/script/value/FrameworkValue.java +++ b/src/main/java/carpet/script/value/FrameworkValue.java @@ -1,6 +1,6 @@ package carpet.script.value; -import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.Tag; public abstract class FrameworkValue extends Value { @@ -29,7 +29,7 @@ public abstract class FrameworkValue extends Value } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionAnnotationValue.java b/src/main/java/carpet/script/value/FunctionAnnotationValue.java index 4d213c89..41ba7914 100644 --- a/src/main/java/carpet/script/value/FunctionAnnotationValue.java +++ b/src/main/java/carpet/script/value/FunctionAnnotationValue.java @@ -1,7 +1,7 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.Tag; public class FunctionAnnotationValue extends Value { @@ -37,7 +37,7 @@ public class FunctionAnnotationValue extends Value } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { throw new UnsupportedOperationException("Global value cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index f7bdee6d..86161478 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -12,15 +12,14 @@ import carpet.script.exception.ContinueStatement; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ReturnStatement; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; public class FunctionValue extends Value implements Fluff.ILazyFunction { @@ -281,10 +280,10 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction public String getVarArgs() {return varArgs; } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return NbtString.of(getString()); + return StringTag.valueOf(getString()); } public void assertArgsOk(List list, Consumer feedback) diff --git a/src/main/java/carpet/script/value/LazyListValue.java b/src/main/java/carpet/script/value/LazyListValue.java index 0969c4bc..9c93139d 100644 --- a/src/main/java/carpet/script/value/LazyListValue.java +++ b/src/main/java/carpet/script/value/LazyListValue.java @@ -1,13 +1,12 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; public abstract class LazyListValue extends AbstractListValue implements Iterator { @@ -204,9 +203,9 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return NbtString.of(getString()); + return StringTag.valueOf(getString()); } } diff --git a/src/main/java/carpet/script/value/ListValue.java b/src/main/java/carpet/script/value/ListValue.java index 786415bf..7a4cab0b 100644 --- a/src/main/java/carpet/script/value/ListValue.java +++ b/src/main/java/carpet/script/value/ListValue.java @@ -4,15 +4,6 @@ import carpet.script.LazyValue; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import net.minecraft.nbt.AbstractNbtNumber; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtDouble; -import net.minecraft.nbt.NbtInt; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtLong; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -23,6 +14,14 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.LongTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; import static java.lang.Math.abs; @@ -484,31 +483,31 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf LIST, MAP, STRING; - private static TagTypeCompat getType(NbtElement tag) + private static TagTypeCompat getType(Tag tag) { - if (tag instanceof NbtInt) return INT; - if (tag instanceof NbtLong) return LONG; - if (tag instanceof NbtDouble) return DBL; - if (tag instanceof NbtList) return LIST; - if (tag instanceof NbtCompound) return MAP; + if (tag instanceof IntTag) return INT; + if (tag instanceof LongTag) return LONG; + if (tag instanceof DoubleTag) return DBL; + if (tag instanceof ListTag) return LIST; + if (tag instanceof CompoundTag) return MAP; return STRING; } } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { int argSize = items.size(); - if (argSize == 0) return new NbtList(); - NbtList tag = new NbtList(); + if (argSize == 0) return new ListTag(); + ListTag tag = new ListTag(); if (argSize ==1) { tag.add(items.get(0).toTag(force)); return tag; } // figuring out the types - List tags= new ArrayList<>(); + List tags= new ArrayList<>(); items.forEach(v -> tags.add(v.toTag(force))); Set cases = EnumSet.noneOf(TagTypeCompat.class); tags.forEach(t -> cases.add(TagTypeCompat.getType(t))); @@ -522,17 +521,17 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf || cases.contains(TagTypeCompat.STRING)) // incompatible types { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - tags.forEach(t -> tag.add(NbtString.of(t.asString()))); + tags.forEach(t -> tag.add(StringTag.valueOf(t.getAsString()))); return tag; } // only numbers / mixed types if (cases.contains(TagTypeCompat.DBL)) { - tags.forEach(t -> tag.add(NbtDouble.of(((AbstractNbtNumber)t).doubleValue()))); + tags.forEach(t -> tag.add(DoubleTag.valueOf(((NumericTag)t).getAsDouble()))); } else { - tags.forEach(t -> tag.add(NbtLong.of(((AbstractNbtNumber)t).longValue()))); + tags.forEach(t -> tag.add(LongTag.valueOf(((NumericTag)t).getAsLong()))); } return tag; } diff --git a/src/main/java/carpet/script/value/MapValue.java b/src/main/java/carpet/script/value/MapValue.java index 6923edec..d9f173b9 100644 --- a/src/main/java/carpet/script/value/MapValue.java +++ b/src/main/java/carpet/script/value/MapValue.java @@ -3,9 +3,6 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -14,6 +11,8 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; public class MapValue extends AbstractListValue implements ContainerValueInterface { @@ -260,9 +259,9 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { - NbtCompound tag = new NbtCompound() ; + CompoundTag tag = new CompoundTag() ; map.forEach( (k, v) -> { if (!force && !(k instanceof StringValue)) throw new NBTSerializableValue.IncompatibleTypeException(k); diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 9f558475..353a533a 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -8,38 +8,6 @@ import carpet.script.exception.Throwables; import carpet.script.utils.EquipmentInventory; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.ChestBlock; -import net.minecraft.block.InventoryProvider; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.ChestBlockEntity; -import net.minecraft.command.argument.ItemStackArgument; -import net.minecraft.command.argument.ItemStringReader; -import net.minecraft.command.argument.NbtPathArgumentType; -import net.minecraft.entity.Entity; -import net.minecraft.entity.InventoryOwner; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.AbstractNbtList; -import net.minecraft.nbt.AbstractNbtNumber; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtEnd; -import net.minecraft.nbt.NbtInt; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtLong; -import net.minecraft.nbt.StringNbtReader; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -50,12 +18,43 @@ import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import net.minecraft.commands.arguments.NbtPathArgument; +import net.minecraft.commands.arguments.item.ItemInput; +import net.minecraft.commands.arguments.item.ItemParser; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CollectionTag; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.EndTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.LongTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.nbt.TagParser; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.Container; +import net.minecraft.world.WorldlyContainerHolder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySelector; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.npc.InventoryCarrier; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.ChestBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; public class NBTSerializableValue extends Value implements ContainerValueInterface { private String nbtString = null; - private NbtElement nbtTag = null; - private Supplier nbtSupplier = null; + private Tag nbtTag = null; + private Supplier nbtSupplier = null; private boolean owned = false; private NBTSerializableValue() {} @@ -66,7 +65,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa { try { - return (new StringNbtReader(new StringReader(nbtString))).parseElement(); + return (new TagParser(new StringReader(nbtString))).readValue(); } catch (CommandSyntaxException e) { @@ -76,35 +75,35 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa owned = true; } - public NBTSerializableValue(NbtElement tag) + public NBTSerializableValue(Tag tag) { nbtTag = tag; owned = true; } - public static Value of(NbtElement tag) + public static Value of(Tag tag) { if (tag == null) return Value.NULL; return new NBTSerializableValue(tag); } - public NBTSerializableValue(Supplier tagSupplier) + public NBTSerializableValue(Supplier tagSupplier) { nbtSupplier = tagSupplier; } public static Value fromStack(ItemStack stack) { - if (stack.hasNbt()) + if (stack.hasTag()) { NBTSerializableValue value = new NBTSerializableValue(); - value.nbtSupplier = stack::getNbt; + value.nbtSupplier = stack::getTag; return value; } return Value.NULL; } - public static String nameFromRegistryId(Identifier id) + public static String nameFromRegistryId(ResourceLocation id) { if (id == null) // should be Value.NULL return ""; @@ -115,10 +114,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa public static NBTSerializableValue parseString(String nbtString, boolean fail) { - NbtElement tag; + Tag tag; try { - tag = (new StringNbtReader(new StringReader(nbtString))).parseElement(); + tag = (new TagParser(new StringReader(nbtString))).readValue(); } catch (CommandSyntaxException e) { @@ -157,33 +156,33 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } // stolen from HopperBlockEntity, adjusted for threaded operation - public static Inventory getInventoryAt(ServerWorld world, BlockPos blockPos) + public static Container getInventoryAt(ServerLevel world, BlockPos blockPos) { - Inventory inventory = null; + Container inventory = null; BlockState blockState = world.getBlockState(blockPos); Block block = blockState.getBlock(); - if (block instanceof InventoryProvider) { - inventory = ((InventoryProvider)block).getInventory(blockState, world, blockPos); + if (block instanceof WorldlyContainerHolder) { + inventory = ((WorldlyContainerHolder)block).getContainer(blockState, world, blockPos); } else if (blockState.hasBlockEntity()) { BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); - if (blockEntity instanceof Inventory) { - inventory = (Inventory)blockEntity; + if (blockEntity instanceof Container) { + inventory = (Container)blockEntity; if (inventory instanceof ChestBlockEntity && block instanceof ChestBlock) { - inventory = ChestBlock.getInventory((ChestBlock)block, blockState, world, blockPos, true); + inventory = ChestBlock.getContainer((ChestBlock)block, blockState, world, blockPos, true); } } } if (inventory == null) { - List list = world.getOtherEntities( - null, - new Box( + List list = world.getEntities( + (Entity)null, //TODO check this matches the correct method + new AABB( blockPos.getX() - 0.5D, blockPos.getY() - 0.5D, blockPos.getZ() - 0.5D, blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D), - EntityPredicates.VALID_INVENTORIES + EntitySelector.CONTAINER_ENTITY_SELECTOR ); if (!list.isEmpty()) { - inventory = (Inventory)list.get(world.random.nextInt(list.size())); + inventory = (Container)list.get(world.random.nextInt(list.size())); } } @@ -206,9 +205,9 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa if (strVal.equals("enderchest")) { Value v2 = params.get(1 + offset); - ServerPlayerEntity player = EntityValue.getPlayerByValue(c.s.getServer(), v2); + ServerPlayer player = EntityValue.getPlayerByValue(c.s.getServer(), v2); if (player == null) throw new InternalExpressionException("enderchest inventory requires player argument"); - return new InventoryLocator(player, player.getBlockPos(), player.getEnderChestInventory(), offset + 2, true); + return new InventoryLocator(player, player.blockPosition(), player.getEnderChestInventory(), offset + 2, true); } if (strVal.equals("equipment")) { @@ -216,15 +215,15 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa if (!(v2 instanceof EntityValue)) throw new InternalExpressionException("Equipment inventory requires a living entity argument"); Entity e = ((EntityValue) v2).getEntity(); if (!(e instanceof LivingEntity)) throw new InternalExpressionException("Equipment inventory requires a living entity argument"); - return new InventoryLocator(e, e.getBlockPos(), new EquipmentInventory((LivingEntity) e), offset + 2); + return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory((LivingEntity) e), offset + 2); } boolean isEnder = strVal.startsWith("enderchest_"); if (isEnder) strVal = strVal.substring(11); // len("enderchest_") - ServerPlayerEntity player = c.s.getServer().getPlayerManager().getPlayer(strVal); + ServerPlayer player = c.s.getServer().getPlayerList().getPlayerByName(strVal); if (player == null) throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); return new InventoryLocator( player, - player.getBlockPos(), + player.blockPosition(), isEnder ? player.getEnderChestInventory() : player.getInventory(), offset + 1, isEnder @@ -232,24 +231,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } if (v1 instanceof EntityValue) { - Inventory inv = null; + Container inv = null; Entity e = ((EntityValue) v1).getEntity(); - if (e instanceof PlayerEntity pe) inv = pe.getInventory(); - else if (e instanceof Inventory) inv = (Inventory) e; - else if (e instanceof InventoryOwner io) inv = io.getInventory(); + if (e instanceof Player pe) inv = pe.getInventory(); + else if (e instanceof Container) inv = (Container) e; + else if (e instanceof InventoryCarrier io) inv = io.getInventory(); else if (e instanceof InventoryBearerInterface ibi) inv = ibi.getCMInventory(); // horse only - else if (e instanceof LivingEntity le) return new InventoryLocator(e, e.getBlockPos(), new EquipmentInventory(le), offset+1); + else if (e instanceof LivingEntity le) return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset+1); if (inv == null) return null; - return new InventoryLocator(e, e.getBlockPos(), inv, offset+1); + return new InventoryLocator(e, e.blockPosition(), inv, offset+1); } if (v1 instanceof BlockValue) { BlockPos pos = ((BlockValue) v1).getPos(); if (pos == null) throw new InternalExpressionException("Block to access inventory needs to be positioned in the world"); - Inventory inv = getInventoryAt(c.s.getWorld(), pos); + Container inv = getInventoryAt(c.s.getLevel(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset+1); @@ -261,7 +260,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); - Inventory inv = getInventoryAt(c.s.getWorld(), pos); + Container inv = getInventoryAt(c.s.getLevel(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset+1); @@ -269,13 +268,13 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa if (v1 instanceof ScreenValue screenValue) { if(!screenValue.isOpen()) return null; - return new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().getBlockPos(), screenValue.getInventory(), offset+1); + return new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset+1); } BlockPos pos = new BlockPos( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.get(1 + offset)).getDouble(), NumericValue.asNumber(params.get(2 + offset)).getDouble()); - Inventory inv = getInventoryAt(c.s.getWorld(), pos); + Container inv = getInventoryAt(c.s.getLevel(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset + 3); @@ -286,33 +285,33 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } } - private static final Map itemCache = new HashMap<>(); + private static final Map itemCache = new HashMap<>(); - public static ItemStackArgument parseItem(String itemString) + public static ItemInput parseItem(String itemString) { return parseItem(itemString, null); } - public static ItemStackArgument parseItem(String itemString, NbtCompound customTag) + public static ItemInput parseItem(String itemString, CompoundTag customTag) { try { - ItemStackArgument res = itemCache.get(itemString); + ItemInput res = itemCache.get(itemString); if (res != null) if (customTag == null) return res; else - return new ItemStackArgument(res.getItem(), customTag); + return new ItemInput(res.getItem(), customTag); - ItemStringReader parser = (new ItemStringReader(new StringReader(itemString), false)).consume(); - res = new ItemStackArgument(parser.getItem(), parser.getNbt()); + ItemParser parser = (new ItemParser(new StringReader(itemString), false)).parse(); + res = new ItemInput(parser.getItem(), parser.getNbt()); itemCache.put(itemString, res); if (itemCache.size()>64000) itemCache.clear(); if (customTag == null) return res; else - return new ItemStackArgument(res.getItem(), customTag); + return new ItemInput(res.getItem(), customTag); } catch (CommandSyntaxException e) { @@ -320,59 +319,59 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } } - public static int validateSlot(int slot, Inventory inv) + public static int validateSlot(int slot, Container inv) { - int invSize = inv.size(); + int invSize = inv.getContainerSize(); if (slot < 0) slot = invSize + slot; if (slot < 0 || slot >= invSize) - return inv.size(); // outside of inventory + return inv.getContainerSize(); // outside of inventory return slot; } - private static Value decodeSimpleTag(NbtElement t) + private static Value decodeSimpleTag(Tag t) { - if (t instanceof AbstractNbtNumber) + if (t instanceof NumericTag) { - if (t instanceof NbtLong || t instanceof NbtInt) // short and byte will never exceed float's precision, even int won't + if (t instanceof LongTag || t instanceof IntTag) // short and byte will never exceed float's precision, even int won't { - return NumericValue.of(((AbstractNbtNumber) t).longValue()); + return NumericValue.of(((NumericTag) t).getAsLong()); } - return NumericValue.of(((AbstractNbtNumber) t).numberValue()); + return NumericValue.of(((NumericTag) t).getAsNumber()); } - if (t instanceof NbtString) - return StringValue.of(t.asString()); - if (t instanceof NbtEnd) + if (t instanceof StringTag) + return StringValue.of(t.getAsString()); + if (t instanceof EndTag) return Value.NULL; - throw new InternalExpressionException("How did we get here: Unknown nbt element class: "+t.getNbtType().getCrashReportName()); + throw new InternalExpressionException("How did we get here: Unknown nbt element class: "+t.getType().getName()); } - private static Value decodeTag(NbtElement t) + private static Value decodeTag(Tag t) { - if (t instanceof NbtCompound || t instanceof AbstractNbtList) + if (t instanceof CompoundTag || t instanceof CollectionTag) return new NBTSerializableValue(() -> t); return decodeSimpleTag(t); } - private static Value decodeTagDeep(NbtElement t) + private static Value decodeTagDeep(Tag t) { - if (t instanceof NbtCompound) + if (t instanceof CompoundTag) { Map pairs = new HashMap<>(); - NbtCompound ctag = (NbtCompound)t; - for (String key: ctag.getKeys()) + CompoundTag ctag = (CompoundTag)t; + for (String key: ctag.getAllKeys()) { pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key))); } return MapValue.wrap(pairs); } - if (t instanceof AbstractNbtList) + if (t instanceof CollectionTag) { List elems = new ArrayList<>(); - AbstractNbtList ltag = (AbstractNbtList)t; - for (NbtElement elem: ltag) + CollectionTag ltag = (CollectionTag)t; + for (Tag elem: ltag) { elems.add(decodeTagDeep(elem)); } @@ -395,7 +394,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return NBTSerializableValue.parseString(v.getString(), true); } - public NbtElement getTag() + public Tag getTag() { if (nbtTag == null) nbtTag = nbtSupplier.get(); @@ -421,24 +420,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override public boolean getBoolean() { - NbtElement tag = getTag(); - if (tag instanceof NbtCompound) - return !((NbtCompound) tag).isEmpty(); - if (tag instanceof AbstractNbtList) - return !((AbstractNbtList) tag).isEmpty(); - if (tag instanceof AbstractNbtNumber) - return ((AbstractNbtNumber) tag).doubleValue()!=0.0; - if (tag instanceof NbtString) - return !tag.asString().isEmpty(); + Tag tag = getTag(); + if (tag instanceof CompoundTag) + return !((CompoundTag) tag).isEmpty(); + if (tag instanceof CollectionTag) + return !((CollectionTag) tag).isEmpty(); + if (tag instanceof NumericTag) + return ((NumericTag) tag).getAsDouble()!=0.0; + if (tag instanceof StringTag) + return !tag.getAsString().isEmpty(); return true; } - public NbtCompound getCompoundTag() + public CompoundTag getCompoundTag() { try { ensureOwnership(); - return (NbtCompound) getTag(); + return (CompoundTag) getTag(); } catch (ClassCastException e) { @@ -457,8 +456,8 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa { /// WIP ensureOwnership(); - NbtPathArgumentType.NbtPath path = cachePath(where.getString()); - NbtElement tagToInsert = value instanceof NBTSerializableValue ? + NbtPathArgument.NbtPath path = cachePath(where.getString()); + Tag tagToInsert = value instanceof NBTSerializableValue ? ((NBTSerializableValue) value).getTag() : new NBTSerializableValue(value.getString()).getTag(); boolean modifiedTag; @@ -488,17 +487,17 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa - private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement) + private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement) { return modify_insert(index, nbtPath, newElement, this.getTag()); } - private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement, NbtElement currentTag) + private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement, Tag currentTag) { - Collection targets; + Collection targets; try { - targets = nbtPath.getOrInit(currentTag, NbtList::new); + targets = nbtPath.getOrCreate(currentTag, ListTag::new); } catch (CommandSyntaxException e) { @@ -506,16 +505,16 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } boolean modified = false; - for (NbtElement target : targets) + for (Tag target : targets) { - if (!(target instanceof AbstractNbtList)) + if (!(target instanceof CollectionTag)) { continue; } try { - AbstractNbtList targetList = (AbstractNbtList) target; - if (!targetList.addElement(index < 0 ? targetList.size() + index + 1 : index, newElement.copy())) + CollectionTag targetList = (CollectionTag) target; + if (!targetList.addTag(index < 0 ? targetList.size() + index + 1 : index, newElement.copy())) return false; modified = true; } @@ -527,22 +526,22 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa } - private boolean modify_merge(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modify_merge(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - if (!(replacement instanceof NbtCompound)) + if (!(replacement instanceof CompoundTag)) { return false; } - NbtElement ownTag = getTag(); + Tag ownTag = getTag(); try { - for (NbtElement target : nbtPath.getOrInit(ownTag, NbtCompound::new)) + for (Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new)) { - if (!(target instanceof NbtCompound)) + if (!(target instanceof CompoundTag)) { continue; } - ((NbtCompound) target).copyFrom((NbtCompound) replacement); + ((CompoundTag) target).merge((CompoundTag) replacement); } } catch (CommandSyntaxException ignored) @@ -552,9 +551,9 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return true; } - private boolean modify_replace(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modify_replace(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - NbtElement tag = getTag(); + Tag tag = getTag(); String pathText = nbtPath.toString(); if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement { @@ -581,12 +580,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return false; } } - NbtPathArgumentType.NbtPath newPath = cachePath(pathText.substring(0, pathText.length()-arrAccess.length())); + NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length()-arrAccess.length())); return modify_insert(pos,newPath,replacement, tag); } try { - nbtPath.put(tag, () -> replacement); + nbtPath.set(tag, () -> replacement); } catch (CommandSyntaxException e) { @@ -599,10 +598,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa public Value get(Value value) { String valString = value.getString(); - NbtPathArgumentType.NbtPath path = cachePath(valString); + NbtPathArgument.NbtPath path = cachePath(valString); try { - List tags = path.get(getTag()); + List tags = path.get(getTag()); if (tags.size()==0) return Value.NULL; if (tags.size()==1 && !valString.endsWith("[]")) @@ -616,7 +615,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override public boolean has(Value where) { - return cachePath(where.getString()).count(getTag()) > 0; + return cachePath(where.getString()).countMatching(getTag()) > 0; } private void ensureOwnership() @@ -638,7 +637,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override public boolean delete(Value where) { - NbtPathArgumentType.NbtPath path = cachePath(where.getString()); + NbtPathArgument.NbtPath path = cachePath(where.getString()); ensureOwnership(); int removed = path.remove(getTag()); if (removed > 0) @@ -649,23 +648,23 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa return false; } - public static record InventoryLocator(Object owner, BlockPos position, Inventory inventory, int offset, boolean isEnder) + public static record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset, boolean isEnder) { - InventoryLocator(Object owner, BlockPos pos, Inventory i, int o) + InventoryLocator(Object owner, BlockPos pos, Container i, int o) { this(owner, pos, i, o, false); } } - private static Map pathCache = new HashMap<>(); - private static NbtPathArgumentType.NbtPath cachePath(String arg) + private static Map pathCache = new HashMap<>(); + private static NbtPathArgument.NbtPath cachePath(String arg) { - NbtPathArgumentType.NbtPath res = pathCache.get(arg); + NbtPathArgument.NbtPath res = pathCache.get(arg); if (res != null) return res; try { - res = NbtPathArgumentType.nbtPath().parse(new StringReader(arg)); + res = NbtPathArgument.nbtPath().parse(new StringReader(arg)); } catch (CommandSyntaxException exc) { @@ -685,7 +684,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); ensureOwnership(); diff --git a/src/main/java/carpet/script/value/NullValue.java b/src/main/java/carpet/script/value/NullValue.java index cfbd60f2..23bba606 100644 --- a/src/main/java/carpet/script/value/NullValue.java +++ b/src/main/java/carpet/script/value/NullValue.java @@ -1,11 +1,10 @@ package carpet.script.value; import java.util.ArrayList; - +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; import com.google.gson.JsonElement; import com.google.gson.JsonNull; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; public class NullValue extends NumericValue // TODO check nonsingleton code { @@ -80,10 +79,10 @@ public class NullValue extends NumericValue // TODO check nonsingleton code } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - return NbtString.of("null"); + return StringTag.valueOf("null"); } @Override diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 9621cf53..09a6f98a 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -3,16 +3,16 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.NbtDouble; -import net.minecraft.nbt.NbtInt; -import net.minecraft.nbt.NbtLong; -import net.minecraft.nbt.NbtElement; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Locale; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.LongTag; +import net.minecraft.nbt.Tag; import static java.lang.Math.abs; import static java.lang.Math.signum; @@ -268,24 +268,24 @@ public class NumericValue extends Value } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (longValue != null) { if (abs(longValue) < Integer.MAX_VALUE-2) - return NbtInt.of((int)(long)longValue); - return NbtLong.of(longValue); + return IntTag.valueOf((int)(long)longValue); + return LongTag.valueOf(longValue); } long lv = getLong(); if (value == (double)lv) { if (abs(value) < Integer.MAX_VALUE-2) - return NbtInt.of((int)lv); - return NbtLong.of(getLong()); + return IntTag.valueOf((int)lv); + return LongTag.valueOf(getLong()); } else { - return NbtDouble.of(value); + return DoubleTag.valueOf(value); } } diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 592b6609..64534c0d 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -13,63 +13,62 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.InvalidCallbackException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; -import net.minecraft.nbt.NbtList; -import net.minecraft.recipe.Recipe; -import net.minecraft.screen.AbstractFurnaceScreenHandler; -import net.minecraft.screen.AnvilScreenHandler; -import net.minecraft.screen.ArrayPropertyDelegate; -import net.minecraft.screen.BeaconScreenHandler; -import net.minecraft.screen.BlastFurnaceScreenHandler; -import net.minecraft.screen.BrewingStandScreenHandler; -import net.minecraft.screen.CartographyTableScreenHandler; -import net.minecraft.screen.CraftingScreenHandler; -import net.minecraft.screen.EnchantmentScreenHandler; -import net.minecraft.screen.FurnaceScreenHandler; -import net.minecraft.screen.GenericContainerScreenHandler; -import net.minecraft.screen.GrindstoneScreenHandler; -import net.minecraft.screen.HopperScreenHandler; -import net.minecraft.screen.LecternScreenHandler; -import net.minecraft.screen.LoomScreenHandler; -import net.minecraft.screen.MerchantScreenHandler; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.screen.Property; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerListener; -import net.minecraft.screen.ShulkerBoxScreenHandler; -import net.minecraft.screen.SimpleNamedScreenHandlerFactory; -import net.minecraft.screen.SmithingScreenHandler; -import net.minecraft.screen.SmokerScreenHandler; -import net.minecraft.screen.StonecutterScreenHandler; -import net.minecraft.screen.slot.Slot; -import net.minecraft.screen.slot.SlotActionType; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; - import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.OptionalInt; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.Container; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.AbstractFurnaceMenu; +import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.inventory.BeaconMenu; +import net.minecraft.world.inventory.BlastFurnaceMenu; +import net.minecraft.world.inventory.BrewingStandMenu; +import net.minecraft.world.inventory.CartographyTableMenu; +import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.ContainerListener; +import net.minecraft.world.inventory.CraftingMenu; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.inventory.EnchantmentMenu; +import net.minecraft.world.inventory.FurnaceMenu; +import net.minecraft.world.inventory.GrindstoneMenu; +import net.minecraft.world.inventory.HopperMenu; +import net.minecraft.world.inventory.LecternMenu; +import net.minecraft.world.inventory.LoomMenu; +import net.minecraft.world.inventory.MerchantMenu; +import net.minecraft.world.inventory.ShulkerBoxMenu; +import net.minecraft.world.inventory.SimpleContainerData; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.inventory.SmithingMenu; +import net.minecraft.world.inventory.SmokerMenu; +import net.minecraft.world.inventory.StonecutterMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Recipe; -import static net.minecraft.screen.ScreenHandlerType.*; +import static net.minecraft.world.inventory.MenuType.*; public class ScreenValue extends Value { - private ScreenHandler screenHandler; + private AbstractContainerMenu screenHandler; private ScreenHandlerInventory inventory; - private final Text name; + private final Component name; private final String typestring; private final FunctionValue callback; private final String hostname; - private final ServerPlayerEntity player; + private final ServerPlayer player; public static Map screenHandlerFactories; @@ -78,80 +77,80 @@ public class ScreenValue extends Value { { screenHandlerFactories = new HashMap<>(); - screenHandlerFactories.put("anvil",(syncId, playerInventory) -> new AnvilScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("beacon",(syncId, playerInventory) -> new BeaconScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("blast_furnace",(syncId, playerInventory) -> new BlastFurnaceScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("brewing_stand",(syncId, playerInventory) -> new BrewingStandScreenHandler(syncId,playerInventory,new SimpleInventory(5),new ArrayPropertyDelegate(2))); - screenHandlerFactories.put("cartography_table",(syncId, playerInventory) -> new CartographyTableScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("crafting",(syncId, playerInventory) -> new CraftingScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("enchantment",(syncId, playerInventory) -> new EnchantmentScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("furnace",(syncId, playerInventory) -> new FurnaceScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("generic_3x3",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_3X3,syncId,playerInventory,new SimpleInventory(9),1))); - screenHandlerFactories.put("generic_9x1",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X1,syncId,playerInventory,new SimpleInventory(9),1))); - screenHandlerFactories.put("generic_9x2",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X2,syncId,playerInventory,new SimpleInventory(9*2),2))); - screenHandlerFactories.put("generic_9x3",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X3,syncId,playerInventory,new SimpleInventory(9*3),3))); - screenHandlerFactories.put("generic_9x4",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X4,syncId,playerInventory,new SimpleInventory(9*4),4))); - screenHandlerFactories.put("generic_9x5",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X5,syncId,playerInventory,new SimpleInventory(9*5),5))); - screenHandlerFactories.put("generic_9x6",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X6,syncId,playerInventory,new SimpleInventory(9*6),6))); - screenHandlerFactories.put("grindstone",(syncId, playerInventory) -> new GrindstoneScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("hopper",(syncId, playerInventory) -> new HopperScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("lectern",(syncId, playerInventory) -> new LecternScreenHandler(syncId,new SimpleInventory(1),new ArrayPropertyDelegate(1))); - screenHandlerFactories.put("loom",(syncId, playerInventory) -> new LoomScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("merchant",(syncId, playerInventory) -> new MerchantScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("shulker_box",(syncId, playerInventory) -> new ShulkerBoxScreenHandler(syncId,playerInventory,new SimpleInventory(9*3))); - screenHandlerFactories.put("smithing",(syncId, playerInventory) -> new SmithingScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("smoker",(syncId, playerInventory) -> new SmokerScreenHandler(syncId,playerInventory)); - screenHandlerFactories.put("stonecutter",(syncId, playerInventory) -> new StonecutterScreenHandler(syncId,playerInventory)); + screenHandlerFactories.put("anvil",(syncId, playerInventory) -> new AnvilMenu(syncId,playerInventory)); + screenHandlerFactories.put("beacon",(syncId, playerInventory) -> new BeaconMenu(syncId,playerInventory)); + screenHandlerFactories.put("blast_furnace",(syncId, playerInventory) -> new BlastFurnaceMenu(syncId,playerInventory)); + screenHandlerFactories.put("brewing_stand",(syncId, playerInventory) -> new BrewingStandMenu(syncId,playerInventory,new SimpleContainer(5),new SimpleContainerData(2))); + screenHandlerFactories.put("cartography_table",(syncId, playerInventory) -> new CartographyTableMenu(syncId,playerInventory)); + screenHandlerFactories.put("crafting",(syncId, playerInventory) -> new CraftingMenu(syncId,playerInventory)); + screenHandlerFactories.put("enchantment",(syncId, playerInventory) -> new EnchantmentMenu(syncId,playerInventory)); + screenHandlerFactories.put("furnace",(syncId, playerInventory) -> new FurnaceMenu(syncId,playerInventory)); + screenHandlerFactories.put("generic_3x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_3x3,syncId,playerInventory,new SimpleContainer(9),1))); + screenHandlerFactories.put("generic_9x1",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x1,syncId,playerInventory,new SimpleContainer(9),1))); + screenHandlerFactories.put("generic_9x2",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x2,syncId,playerInventory,new SimpleContainer(9*2),2))); + screenHandlerFactories.put("generic_9x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x3,syncId,playerInventory,new SimpleContainer(9*3),3))); + screenHandlerFactories.put("generic_9x4",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x4,syncId,playerInventory,new SimpleContainer(9*4),4))); + screenHandlerFactories.put("generic_9x5",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x5,syncId,playerInventory,new SimpleContainer(9*5),5))); + screenHandlerFactories.put("generic_9x6",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x6,syncId,playerInventory,new SimpleContainer(9*6),6))); + screenHandlerFactories.put("grindstone",(syncId, playerInventory) -> new GrindstoneMenu(syncId,playerInventory)); + screenHandlerFactories.put("hopper",(syncId, playerInventory) -> new HopperMenu(syncId,playerInventory)); + screenHandlerFactories.put("lectern",(syncId, playerInventory) -> new LecternMenu(syncId,new SimpleContainer(1),new SimpleContainerData(1))); + screenHandlerFactories.put("loom",(syncId, playerInventory) -> new LoomMenu(syncId,playerInventory)); + screenHandlerFactories.put("merchant",(syncId, playerInventory) -> new MerchantMenu(syncId,playerInventory)); + screenHandlerFactories.put("shulker_box",(syncId, playerInventory) -> new ShulkerBoxMenu(syncId,playerInventory,new SimpleContainer(9*3))); + screenHandlerFactories.put("smithing",(syncId, playerInventory) -> new SmithingMenu(syncId,playerInventory)); + screenHandlerFactories.put("smoker",(syncId, playerInventory) -> new SmokerMenu(syncId,playerInventory)); + screenHandlerFactories.put("stonecutter",(syncId, playerInventory) -> new StonecutterMenu(syncId,playerInventory)); } protected interface ScarpetScreenHandlerFactory { - ScreenHandler create(int syncId, PlayerInventory playerInventory); + AbstractContainerMenu create(int syncId, Inventory playerInventory); } - public ScreenValue(ServerPlayerEntity player, String type, Text name, FunctionValue callback, Context c) { + public ScreenValue(ServerPlayer player, String type, Component name, FunctionValue callback, Context c) { this.name = name; this.typestring = type.toLowerCase(); if(callback != null) callback.checkArgs(4); this.callback = callback; this.hostname = c.host.getName(); this.player = player; - NamedScreenHandlerFactory factory = this.createScreenHandlerFactory(); + MenuProvider factory = this.createScreenHandlerFactory(); if(factory == null) throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN); this.openScreen(factory); this.inventory = new ScreenHandlerInventory(this.screenHandler); } - private NamedScreenHandlerFactory createScreenHandlerFactory() { + private MenuProvider createScreenHandlerFactory() { if(!screenHandlerFactories.containsKey(this.typestring)) { return null; } - return new SimpleNamedScreenHandlerFactory((i, playerInventory, playerEntity) -> { - ScreenHandler screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i,playerInventory); + return new SimpleMenuProvider((i, playerInventory, playerEntity) -> { + AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i,playerInventory); ScreenValue.this.addListenerCallback(screen); ScreenValue.this.screenHandler = screen; return screen; }, this.name); } - private void openScreen(NamedScreenHandlerFactory factory) { + private void openScreen(MenuProvider factory) { if(this.player == null) return; - OptionalInt optionalSyncId = this.player.openHandledScreen(factory); - if(optionalSyncId.isPresent() && this.player.currentScreenHandler.syncId == optionalSyncId.getAsInt()) { - this.screenHandler = this.player.currentScreenHandler; + OptionalInt optionalSyncId = this.player.openMenu(factory); + if(optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt()) { + this.screenHandler = this.player.containerMenu; } } public void close() { - if(this.player.currentScreenHandler != this.player.playerScreenHandler) { + if(this.player.containerMenu != this.player.inventoryMenu) { //prevent recursion when closing screen in closing screen callback by doing this before triggering event this.inventory = null; - this.player.currentScreenHandler = this.player.playerScreenHandler; - this.player.closeHandledScreen(); + this.player.containerMenu = this.player.inventoryMenu; + this.player.closeContainer(); this.screenHandler = null; } } @@ -160,7 +159,7 @@ public class ScreenValue extends Value { if(this.screenHandler == null) { return false; } - if(this.player.currentScreenHandler.syncId == this.screenHandler.syncId) { + if(this.player.containerMenu.containerId == this.screenHandler.containerId) { return true; } this.screenHandler = null; @@ -168,7 +167,7 @@ public class ScreenValue extends Value { } - private boolean callListener(ServerPlayerEntity player, String action, Map data) { + private boolean callListener(ServerPlayer player, String action, Map data) { Value playerValue = EntityValue.of(player); Value actionValue = StringValue.of(action); Value dataValue = MapValue.wrap(data); @@ -179,11 +178,11 @@ public class ScreenValue extends Value { this.screenHandler = null; return false; } - ServerCommandSource source = player.getCommandSource().withLevel(CarpetSettings.runPermissionLevel); + CommandSourceStack source = player.createCommandSourceStack().withPermission(CarpetSettings.runPermissionLevel); CarpetScriptHost executingHost = appHost.retrieveForExecution(source,player); try { - Value cancelValue = executingHost.callUDF(player.getBlockPos(), source.withLevel(CarpetSettings.runPermissionLevel), callback, args); + Value cancelValue = executingHost.callUDF(player.blockPosition(), source.withPermission(CarpetSettings.runPermissionLevel), callback, args); return cancelValue.getString().equals("cancel"); } catch (NullPointerException | InvalidCallbackException | IntegrityException error) @@ -193,52 +192,52 @@ public class ScreenValue extends Value { } } - private void addListenerCallback(ScreenHandler screenHandler) { + private void addListenerCallback(AbstractContainerMenu screenHandler) { if(this.callback == null) return; - screenHandler.addListener(new ScarpetScreenHandlerListener() { + screenHandler.addSlotListener(new ScarpetScreenHandlerListener() { @Override - public boolean onSlotClick(ServerPlayerEntity player, SlotActionType actionType, int slot, int button) { + public boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button) { Map data = new HashMap<>(); - data.put(StringValue.of("slot"),slot == ScreenHandler.EMPTY_SPACE_SLOT_INDEX ? Value.NULL : NumericValue.of(slot)); - if(actionType == SlotActionType.QUICK_CRAFT) { - data.put(StringValue.of("quick_craft_stage"),NumericValue.of(ScreenHandler.unpackQuickCraftStage(button))); - button = ScreenHandler.unpackQuickCraftButton(button); + data.put(StringValue.of("slot"),slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot)); + if(actionType == ClickType.QUICK_CRAFT) { + data.put(StringValue.of("quick_craft_stage"),NumericValue.of(AbstractContainerMenu.getQuickcraftHeader(button))); + button = AbstractContainerMenu.getQuickcraftType(button); } data.put(StringValue.of("button"),NumericValue.of(button)); return ScreenValue.this.callListener(player,actionTypeToString(actionType),data); } @Override - public boolean onButtonClick(ServerPlayerEntity player, int button) { + public boolean onButtonClick(ServerPlayer player, int button) { Map data = new HashMap<>(); data.put(StringValue.of("button"),NumericValue.of(button)); return ScreenValue.this.callListener(player,"button",data); } @Override - public void onClose(ServerPlayerEntity player) { + public void onClose(ServerPlayer player) { Map data = new HashMap<>(); ScreenValue.this.callListener(player,"close",data); } @Override - public boolean onSelectRecipe(ServerPlayerEntity player, Recipe recipe, boolean craftAll) { + public boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll) { Map data = new HashMap<>(); data.put(StringValue.of("recipe"),StringValue.of(recipe.getId().toString())); data.put(StringValue.of("craft_all"),BooleanValue.of(craftAll)); return ScreenValue.this.callListener(player,"select_recipe",data); } @Override - public void onSlotUpdate(ScreenHandler handler, int slotId, ItemStack stack) { + public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) { Map data = new HashMap<>(); data.put(StringValue.of("slot"),NumericValue.of(slotId)); data.put(StringValue.of("stack"),ValueConversions.of(stack)); ScreenValue.this.callListener(ScreenValue.this.player,"slot_update",data); } @Override - public void onPropertyUpdate(ScreenHandler handler, int property, int value) {} + public void dataChanged(AbstractContainerMenu handler, int property, int value) {} }); } - private Property getPropertyForType(Class screenHandlerClass, String requiredType, int propertyIndex, String propertyName) { + private DataSlot getPropertyForType(Class screenHandlerClass, String requiredType, int propertyIndex, String propertyName) { if(screenHandlerClass.isInstance(this.screenHandler)) { return ((ScreenHandlerInterface) this.screenHandler).getProperty(propertyIndex); } @@ -248,38 +247,38 @@ public class ScreenValue extends Value { throw new InternalExpressionException("Screen property " + propertyName + " expected a " + requiredType + " screen."); } - private Property getProperty(String propertyName) { + private DataSlot getProperty(String propertyName) { return switch (propertyName) { - case "fuel_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 0, propertyName); - case "max_fuel_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 1, propertyName); - case "cook_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 2, propertyName); - case "max_cook_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 3, propertyName); + case "fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 0, propertyName); + case "max_fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 1, propertyName); + case "cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 2, propertyName); + case "max_cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 3, propertyName); - case "level_cost" -> getPropertyForType(AnvilScreenHandler.class, "anvil", 0, propertyName); + case "level_cost" -> getPropertyForType(AnvilMenu.class, "anvil", 0, propertyName); - case "page" -> getPropertyForType(LecternScreenHandler.class, "lectern", 0, propertyName); + case "page" -> getPropertyForType(LecternMenu.class, "lectern", 0, propertyName); - case "beacon_level" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 0, propertyName); - case "primary_effect" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 1, propertyName); - case "secondary_effect" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 2, propertyName); + case "beacon_level" -> getPropertyForType(BeaconMenu.class, "beacon", 0, propertyName); + case "primary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 1, propertyName); + case "secondary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 2, propertyName); - case "brew_time" -> getPropertyForType(BrewingStandScreenHandler.class, "brewing_stand", 0, propertyName); - case "brewing_fuel" -> getPropertyForType(BrewingStandScreenHandler.class, "brewing_stand", 1, propertyName); + case "brew_time" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 0, propertyName); + case "brewing_fuel" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 1, propertyName); - case "enchantment_power_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 0, propertyName); - case "enchantment_power_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 1, propertyName); - case "enchantment_power_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 2, propertyName); - case "enchantment_seed" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 3, propertyName); - case "enchantment_id_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 4, propertyName); - case "enchantment_id_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 5, propertyName); - case "enchantment_id_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 6, propertyName); - case "enchantment_level_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 7, propertyName); - case "enchantment_level_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 8, propertyName); - case "enchantment_level_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 9, propertyName); + case "enchantment_power_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 0, propertyName); + case "enchantment_power_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 1, propertyName); + case "enchantment_power_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 2, propertyName); + case "enchantment_seed" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 3, propertyName); + case "enchantment_id_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 4, propertyName); + case "enchantment_id_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 5, propertyName); + case "enchantment_id_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 6, propertyName); + case "enchantment_level_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 7, propertyName); + case "enchantment_level_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 8, propertyName); + case "enchantment_level_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 9, propertyName); - case "banner_pattern" -> getPropertyForType(LoomScreenHandler.class, "loom", 0, propertyName); + case "banner_pattern" -> getPropertyForType(LoomMenu.class, "loom", 0, propertyName); - case "stonecutter_recipe" -> getPropertyForType(StonecutterScreenHandler.class, "stonecutter", 0, propertyName); + case "stonecutter_recipe" -> getPropertyForType(StonecutterMenu.class, "stonecutter", 0, propertyName); default -> throw new InternalExpressionException("Invalid screen property: " + propertyName); }; @@ -289,27 +288,27 @@ public class ScreenValue extends Value { public Value queryProperty(String propertyName) { if(propertyName.equals("name")) return FormattedTextValue.of(this.name); if(propertyName.equals("open")) return BooleanValue.of(this.isOpen()); - Property property = getProperty(propertyName); + DataSlot property = getProperty(propertyName); return NumericValue.of(property.get()); } public Value modifyProperty(String propertyName, List lv) { - Property property = getProperty(propertyName); + DataSlot property = getProperty(propertyName); int intValue = NumericValue.asNumber(lv.get(0)).getInt(); property.set(intValue); - this.screenHandler.syncState(); + this.screenHandler.sendAllDataToRemote(); return Value.TRUE; } - public ScreenHandler getScreenHandler() { + public AbstractContainerMenu getScreenHandler() { return this.screenHandler; } - public ServerPlayerEntity getPlayer() { + public ServerPlayer getPlayer() { return this.player; } - public Inventory getInventory() { + public Container getInventory() { return this.inventory; } @@ -330,124 +329,124 @@ public class ScreenValue extends Value { } @Override - public NbtElement toTag(boolean force) { + public Tag toTag(boolean force) { if(this.screenHandler == null) { return Value.NULL.toTag(true); } - NbtList nbtList = new NbtList(); + ListTag nbtList = new ListTag(); for(int i = 0; i < this.screenHandler.slots.size(); i++) { - ItemStack itemStack = this.screenHandler.getSlot(i).getStack(); - nbtList.add(itemStack.writeNbt(new NbtCompound())); + ItemStack itemStack = this.screenHandler.getSlot(i).getItem(); + nbtList.add(itemStack.save(new CompoundTag())); } return nbtList; } - public interface ScarpetScreenHandlerListener extends ScreenHandlerListener { - boolean onSlotClick(ServerPlayerEntity player, SlotActionType actionType, int slot, int button); - boolean onButtonClick(ServerPlayerEntity player, int button); - void onClose(ServerPlayerEntity player); - boolean onSelectRecipe(ServerPlayerEntity player, Recipe recipe, boolean craftAll); + public interface ScarpetScreenHandlerListener extends ContainerListener { + boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button); + boolean onButtonClick(ServerPlayer player, int button); + void onClose(ServerPlayer player); + boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll); } - public static class ScreenHandlerInventory implements Inventory { + public static class ScreenHandlerInventory implements Container { - protected ScreenHandler screenHandler; + protected AbstractContainerMenu screenHandler; - public ScreenHandlerInventory(ScreenHandler screenHandler) { + public ScreenHandlerInventory(AbstractContainerMenu screenHandler) { this.screenHandler = screenHandler; } @Override - public int size() { + public int getContainerSize() { return this.screenHandler.slots.size() + 1; } @Override public boolean isEmpty() { for(Slot slot : this.screenHandler.slots) { - if(slot.hasStack() && !slot.getStack().isEmpty()) return false; + if(slot.hasItem() && !slot.getItem().isEmpty()) return false; } - return this.screenHandler.getCursorStack().isEmpty(); + return this.screenHandler.getCarried().isEmpty(); } @Override - public ItemStack getStack(int slot) { - if(slot == this.size()-1) return this.screenHandler.getCursorStack(); - return slot >= -1 && slot < this.size() ? this.screenHandler.slots.get(slot).getStack() : ItemStack.EMPTY; + public ItemStack getItem(int slot) { + if(slot == this.getContainerSize()-1) return this.screenHandler.getCarried(); + return slot >= -1 && slot < this.getContainerSize() ? this.screenHandler.slots.get(slot).getItem() : ItemStack.EMPTY; } @Override - public ItemStack removeStack(int slot, int amount) { + public ItemStack removeItem(int slot, int amount) { ItemStack itemStack; - if(slot == this.size()-1) - itemStack = this.screenHandler.getCursorStack().split(amount); + if(slot == this.getContainerSize()-1) + itemStack = this.screenHandler.getCarried().split(amount); else itemStack = ScreenHandlerInventory.splitStack(this.screenHandler.slots, slot, amount); if (!itemStack.isEmpty()) { - this.markDirty(); + this.setChanged(); } return itemStack; } @Override - public ItemStack removeStack(int slot) { + public ItemStack removeItemNoUpdate(int slot) { ItemStack itemStack; - if(slot == this.size()-1) - itemStack = this.screenHandler.getCursorStack(); + if(slot == this.getContainerSize()-1) + itemStack = this.screenHandler.getCarried(); else - itemStack = this.screenHandler.slots.get(slot).getStack(); + itemStack = this.screenHandler.slots.get(slot).getItem(); if (itemStack.isEmpty()) { return ItemStack.EMPTY; } else { - if(slot == this.size()-1) - this.screenHandler.setCursorStack(ItemStack.EMPTY); + if(slot == this.getContainerSize()-1) + this.screenHandler.setCarried(ItemStack.EMPTY); else - this.screenHandler.slots.get(slot).setStack(ItemStack.EMPTY); + this.screenHandler.slots.get(slot).set(ItemStack.EMPTY); return itemStack; } } @Override - public void setStack(int slot, ItemStack stack) { - if(slot == this.size()-1) - this.screenHandler.setCursorStack(stack); + public void setItem(int slot, ItemStack stack) { + if(slot == this.getContainerSize()-1) + this.screenHandler.setCarried(stack); else - this.screenHandler.slots.get(slot).setStack(stack); - if (!stack.isEmpty() && stack.getCount() > this.getMaxCountPerStack()) { - stack.setCount(this.getMaxCountPerStack()); + this.screenHandler.slots.get(slot).set(stack); + if (!stack.isEmpty() && stack.getCount() > this.getMaxStackSize()) { + stack.setCount(this.getMaxStackSize()); } - this.markDirty(); + this.setChanged(); } @Override - public void markDirty() { + public void setChanged() { } @Override - public boolean canPlayerUse(PlayerEntity player) { + public boolean stillValid(Player player) { return true; } @Override - public void clear() { + public void clearContent() { for(Slot slot : this.screenHandler.slots) { - slot.setStack(ItemStack.EMPTY); + slot.set(ItemStack.EMPTY); } - this.screenHandler.setCursorStack(ItemStack.EMPTY); - this.markDirty(); + this.screenHandler.setCarried(ItemStack.EMPTY); + this.setChanged(); } public static ItemStack splitStack(List slots, int slot, int amount) { - return slot >= 0 && slot < slots.size() && !slots.get(slot).getStack().isEmpty() && amount > 0 ? slots.get(slot).getStack().split(amount) : ItemStack.EMPTY; + return slot >= 0 && slot < slots.size() && !slots.get(slot).getItem().isEmpty() && amount > 0 ? slots.get(slot).getItem().split(amount) : ItemStack.EMPTY; } } - private static String actionTypeToString(SlotActionType actionType) { + private static String actionTypeToString(ClickType actionType) { return switch (actionType) { case PICKUP -> "pickup"; case QUICK_MOVE -> "quick_move"; diff --git a/src/main/java/carpet/script/value/StringValue.java b/src/main/java/carpet/script/value/StringValue.java index 65d7553c..c177aa8d 100644 --- a/src/main/java/carpet/script/value/StringValue.java +++ b/src/main/java/carpet/script/value/StringValue.java @@ -1,7 +1,7 @@ package carpet.script.value; -import net.minecraft.nbt.NbtString; -import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; public class StringValue extends Value { @@ -43,8 +43,8 @@ public class StringValue extends Value } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { - return NbtString.of(str); + return StringTag.valueOf(str); } } diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index 21b2e224..d5b37683 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -6,12 +6,11 @@ import carpet.script.Tokenizer; import carpet.script.exception.ExitStatement; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; -import net.minecraft.nbt.NbtElement; - import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; +import net.minecraft.nbt.Tag; public class ThreadValue extends Value { @@ -127,7 +126,7 @@ public class ThreadValue extends Value } @Override - public NbtElement toTag(boolean force) + public Tag toTag(boolean force) { if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); return getValue().toTag(true); diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index 8a0cf9b0..f2919f47 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -4,8 +4,6 @@ import carpet.CarpetSettings; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import net.minecraft.nbt.NbtElement; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -13,6 +11,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; +import net.minecraft.nbt.Tag; public abstract class Value implements Comparable, Cloneable { @@ -237,7 +236,7 @@ public abstract class Value implements Comparable, Cloneable } } - public abstract NbtElement toTag(boolean force); + public abstract Tag toTag(boolean force); public JsonElement toJson() { diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index f15253cb..086cde05 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -5,41 +5,38 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; import carpet.utils.BlockInfo; -import net.minecraft.block.BlockState; -import net.minecraft.block.MapColor; -import net.minecraft.block.pattern.CachedBlockPosition; -import net.minecraft.entity.Entity; -import net.minecraft.entity.ai.brain.LookTarget; -import net.minecraft.entity.ai.brain.WalkTarget; -import net.minecraft.entity.ai.pathing.Path; -import net.minecraft.entity.ai.pathing.PathNode; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.item.ItemStack; -import net.minecraft.particle.ParticleEffect; -import net.minecraft.predicate.NumberRange; -import net.minecraft.scoreboard.ScoreboardCriterion; -import net.minecraft.scoreboard.ScoreboardObjective; +import net.minecraft.advancements.critereon.MinMaxBounds; +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.Registry; +import net.minecraft.core.Vec3i; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.world.ServerWorld; - -import net.minecraft.state.property.Property; -import net.minecraft.structure.StructurePiece; -import net.minecraft.structure.StructureStart; -import net.minecraft.tag.TagManager; -import net.minecraft.util.Identifier; - -import net.minecraft.util.StringIdentifiable; -import net.minecraft.util.dynamic.GlobalPos; -import net.minecraft.util.math.BlockBox; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.ColumnPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.Vec3i; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; - +import net.minecraft.server.level.ColumnPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.TagContainer; +import net.minecraft.util.StringRepresentable; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ai.behavior.PositionTracker; +import net.minecraft.world.entity.ai.memory.WalkTarget; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.material.MaterialColor; +import net.minecraft.world.level.pathfinder.Node; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -63,43 +60,43 @@ public class ValueConversions return ListValue.of(new NumericValue(pos.getX()), new NumericValue(pos.getY()), new NumericValue(pos.getZ())); } - public static Value of(Vec3d vec) + public static Value of(Vec3 vec) { return ListValue.of(new NumericValue(vec.x), new NumericValue(vec.y), new NumericValue(vec.z)); } public static Value of(ColumnPos cpos) { return ListValue.of(new NumericValue(cpos.x), new NumericValue(cpos.z));} - public static Value of(ServerWorld world) + public static Value of(ServerLevel world) { - return of(world.getRegistryKey().getValue()); + return of(world.dimension().location()); } - public static Value of(MapColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.color));} + public static Value of(MaterialColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.col));} - public static Value of(NumberRange range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} + public static Value of(MinMaxBounds range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} public static Value of(ItemStack stack) { if (stack == null || stack.isEmpty()) return Value.NULL; return ListValue.of( - of(Registry.ITEM.getId(stack.getItem())), + of(Registry.ITEM.getKey(stack.getItem())), new NumericValue(stack.getCount()), NBTSerializableValue.fromStack(stack) ); } - public static Value of(ScoreboardObjective objective) + public static Value of(Objective objective) { return ListValue.of( StringValue.of(objective.getName()), - StringValue.of(objective.getCriterion().getName()) + StringValue.of(objective.getCriteria().getName()) ); } - public static Value of(ScoreboardCriterion criteria) + public static Value of(ObjectiveCriteria criteria) { return ListValue.of( StringValue.of(criteria.getName()), @@ -108,20 +105,20 @@ public class ValueConversions } - public static Value of(ParticleEffect particle) + public static Value of(ParticleOptions particle) { - String repr = particle.asString(); + String repr = particle.writeToString(); if (repr.startsWith("minecraft:")) return StringValue.of(repr.substring(10)); return StringValue.of(repr); } public static Value ofRGB(int value) {return new NumericValue(value*256+255 );} - public static World dimFromValue(Value dimensionValue, MinecraftServer server) + public static Level dimFromValue(Value dimensionValue, MinecraftServer server) { if (dimensionValue instanceof EntityValue) { - return ((EntityValue)dimensionValue).getEntity().getEntityWorld(); + return ((EntityValue)dimensionValue).getEntity().getCommandSenderWorld(); } else if (dimensionValue instanceof BlockValue bv) { @@ -141,20 +138,20 @@ public class ValueConversions { case "nether": case "the_nether": - return server.getWorld(World.NETHER); + return server.getLevel(Level.NETHER); case "end": case "the_end": - return server.getWorld(World.END); + return server.getLevel(Level.END); case "overworld": case "over_world": - return server.getWorld(World.OVERWORLD); + return server.getLevel(Level.OVERWORLD); default: - RegistryKey dim = null; - Identifier id = new Identifier(dimString); + ResourceKey dim = null; + ResourceLocation id = new ResourceLocation(dimString); // not using RegistryKey.of since that one creates on check - for (RegistryKey world : (server.getWorldRegistryKeys())) + for (ResourceKey world : (server.levelKeys())) { - if (id.equals(world.getValue())) + if (id.equals(world.location())) { dim = world; break; @@ -162,17 +159,17 @@ public class ValueConversions } if (dim == null) throw new ThrowStatement(dimString, Throwables.UNKNOWN_DIMENSION); - return server.getWorld(dim); + return server.getLevel(dim); } } } - public static Value of(RegistryKey dim) + public static Value of(ResourceKey dim) { - return of(dim.getValue()); + return of(dim.location()); } - public static Value of(Identifier id) + public static Value of(ResourceLocation id) { if (id == null) // should be Value.NULL return Value.NULL; @@ -181,7 +178,7 @@ public class ValueConversions return new StringValue(id.toString()); } - public static String simplify(Identifier id) + public static String simplify(ResourceLocation id) { if (id == null) // should be Value.NULL return ""; @@ -193,23 +190,23 @@ public class ValueConversions public static Value of(GlobalPos pos) { return ListValue.of( - ValueConversions.of(pos.getDimension()), - ValueConversions.of(pos.getPos()) + ValueConversions.of(pos.dimension()), + ValueConversions.of(pos.pos()) ); } - public static Value fromPath(ServerWorld world, Path path) + public static Value fromPath(ServerLevel world, Path path) { List nodes = new ArrayList<>(); //for (PathNode node: path.getNodes()) - for (int i = 0, len = path.getLength(); i < len; i++) + for (int i = 0, len = path.getNodeCount(); i < len; i++) { - PathNode node = path.getNode(i); + Node node = path.getNode(i); nodes.add( ListValue.of( - new BlockValue(null, world, node.getBlockPos()), + new BlockValue(null, world, node.asBlockPos()), new StringValue(node.type.name().toLowerCase(Locale.ROOT)), - new NumericValue(node.penalty), - BooleanValue.of(node.visited) + new NumericValue(node.costMalus), + BooleanValue.of(node.closed) )); } return ListValue.wrap(nodes); @@ -234,7 +231,7 @@ public class ValueConversions } if (v instanceof BlockPos) { - return new BlockValue(null, (ServerWorld) e.getEntityWorld(), (BlockPos) v); + return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), (BlockPos) v); } if (v instanceof Number) { @@ -246,29 +243,29 @@ public class ValueConversions } if (v instanceof UUID) { - return ofUUID( (ServerWorld) e.getEntityWorld(), (UUID)v); + return ofUUID( (ServerLevel) e.getCommandSenderWorld(), (UUID)v); } if (v instanceof DamageSource source) { return ListValue.of( - new StringValue(source.getName()), - source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker()) + new StringValue(source.getMsgId()), + source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) ); } if (v instanceof Path) { - return fromPath((ServerWorld)e.getEntityWorld(), (Path)v); + return fromPath((ServerLevel)e.getCommandSenderWorld(), (Path)v); } - if (v instanceof LookTarget) + if (v instanceof PositionTracker) { - return new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((LookTarget)v).getBlockPos()); + return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PositionTracker)v).currentBlockPosition()); } if (v instanceof WalkTarget) { return ListValue.of( - new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((WalkTarget)v).getLookTarget().getBlockPos()), - new NumericValue(((WalkTarget) v).getSpeed()), - new NumericValue(((WalkTarget) v).getCompletionRange()) + new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((WalkTarget)v).getTarget().currentBlockPosition()), + new NumericValue(((WalkTarget) v).getSpeedModifier()), + new NumericValue(((WalkTarget) v).getCloseEnoughDist()) ); } if (v instanceof Set) @@ -291,7 +288,7 @@ public class ValueConversions return Value.NULL; } - private static Value ofUUID(ServerWorld entityWorld, UUID uuid) + private static Value ofUUID(ServerLevel entityWorld, UUID uuid) { Entity current = entityWorld.getEntity(uuid); return ListValue.of( @@ -299,39 +296,39 @@ public class ValueConversions new StringValue(uuid.toString()) ); } - public static Value of(Box box) + public static Value of(AABB box) { return ListValue.of( ListValue.fromTriple(box.minX, box.minY, box.minZ), ListValue.fromTriple(box.maxX, box.maxY, box.maxZ) ); } - public static Value of(BlockBox box) + public static Value of(BoundingBox box) { return ListValue.of( - ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), - ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ()) + ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), + ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ()) ); } public static Value of(StructureStart structure) { - if (structure == null || structure == StructureStart.DEFAULT) return Value.NULL; - BlockBox boundingBox = structure.getBoundingBox(); - if (boundingBox.getMaxX() < boundingBox.getMinX() || boundingBox.getMaxY() < boundingBox.getMinY() || boundingBox.getMaxZ() < boundingBox.getMinZ()) return Value.NULL; + if (structure == null || structure == StructureStart.INVALID_START) return Value.NULL; + BoundingBox boundingBox = structure.getBoundingBox(); + if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ()) return Value.NULL; Map ret = new HashMap<>(); ret.put(new StringValue("box"), of(boundingBox)); List pieces = new ArrayList<>(); - for (StructurePiece piece : structure.getChildren()) + for (StructurePiece piece : structure.getPieces()) { - BlockBox box = piece.getBoundingBox(); - if (box.getMaxX() >= box.getMinX() && box.getMaxY() >= box.getMinY() && box.getMaxZ() >= box.getMinZ()) + BoundingBox box = piece.getBoundingBox(); + if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ()) { pieces.add(ListValue.of( - new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_PIECE.getId(piece.getType()))), - (piece.getFacing() == null) ? Value.NULL : new StringValue(piece.getFacing().getName()), - ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()), - ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ()) + new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_PIECE.getKey(piece.getType()))), + (piece.getOrientation() == null) ? Value.NULL : new StringValue(piece.getOrientation().getName()), + ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), + ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ()) )); } } @@ -341,11 +338,11 @@ public class ValueConversions public static Value fromProperty(BlockState state, Property p) { - Comparable object = state.get(p); + Comparable object = state.getValue(p); if (object instanceof Boolean || object instanceof Number) return StringValue.of(object.toString()); - if (object instanceof StringIdentifiable) + if (object instanceof StringRepresentable) { - return StringValue.of(((StringIdentifiable) object).asString()); + return StringValue.of(((StringRepresentable) object).getSerializedName()); } throw new InternalExpressionException("Unknown property type: "+p.getName()); } @@ -395,18 +392,18 @@ public class ValueConversions return ret; } - public static Value ofBlockPredicate(TagManager tagManager, Predicate blockPredicate) + public static Value ofBlockPredicate(TagContainer tagManager, Predicate blockPredicate) { BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; return ListValue.of( - predicateData.getCMBlockState()==null?Value.NULL:of(Registry.BLOCK.getId(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getUncheckedTagId(predicateData.getCMBlockTag())), + predicateData.getCMBlockState()==null?Value.NULL:of(Registry.BLOCK.getKey(predicateData.getCMBlockState().getBlock())), + predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getId(predicateData.getCMBlockTag())), MapValue.wrap(predicateData.getCMProperties()), predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag()) ); } - public static Value guess(ServerWorld serverWorld, Object o) { + public static Value guess(ServerLevel serverWorld, Object o) { if (o == null) return Value.NULL; if (o instanceof List) @@ -415,22 +412,22 @@ public class ValueConversions return new BlockValue(null, serverWorld, (BlockPos)o); if (o instanceof Entity) return EntityValue.of((Entity) o); - if (o instanceof Vec3d) - return of((Vec3d)o); + if (o instanceof Vec3) + return of((Vec3)o); if (o instanceof Vec3i) return of(new BlockPos((Vec3i)o)); - if (o instanceof Box) - return of((Box)o); - if (o instanceof BlockBox) - return of((BlockBox) o); + if (o instanceof AABB) + return of((AABB)o); + if (o instanceof BoundingBox) + return of((BoundingBox) o); if (o instanceof ItemStack) return of((ItemStack)o); if (o instanceof Boolean) return BooleanValue.of((Boolean) o); if (o instanceof Number) return NumericValue.of((Number) o); - if (o instanceof Identifier) - return of((Identifier)o); + if (o instanceof ResourceLocation) + return of((ResourceLocation)o); return StringValue.of(o.toString()); } } diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 2c7254bd..98660f72 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -2,8 +2,6 @@ package carpet.settings; import carpet.utils.Translations; import carpet.utils.Messenger; -import net.minecraft.server.command.ServerCommandSource; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; @@ -11,7 +9,7 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; - +import net.minecraft.commands.CommandSourceStack; import org.apache.commons.lang3.ClassUtils; import static carpet.utils.Translations.tr; @@ -120,7 +118,7 @@ public final class ParsedRule implements Comparable { } } - public ParsedRule set(ServerCommandSource source, String value) + public ParsedRule set(CommandSourceStack source, String value) { if (settingsManager != null && settingsManager.locked) return null; @@ -152,7 +150,7 @@ public final class ParsedRule implements Comparable { } } - ParsedRule set(ServerCommandSource source, T value, String stringValue) + ParsedRule set(CommandSourceStack source, T value, String stringValue) { try { @@ -230,7 +228,7 @@ public final class ParsedRule implements Comparable { /** * Resets this rule to its default value */ - public void resetToDefault(ServerCommandSource source) + public void resetToDefault(CommandSourceStack source) { set(source, defaultValue, defaultAsString); } diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index f9dd5bcf..f1f490c0 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -17,14 +17,14 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.fabricmc.api.EnvType; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.command.CommandSource; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.network.chat.BaseComponent; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerTask; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.util.WorldSavePath; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.storage.LevelResource; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.util.TriConsumer; @@ -54,9 +54,9 @@ import java.util.stream.Stream; import static carpet.utils.Translations.tr; import static carpet.script.CarpetEventServer.Event.CARPET_RULE_CHANGES; -import static net.minecraft.command.CommandSource.suggestMatching; -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.SharedSuggestionProvider.suggest; +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; /** * Manages and parses Carpet rules with their own command. @@ -76,8 +76,8 @@ public class SettingsManager private final String identifier; private final String fancyName; private MinecraftServer server; - private List, String>> observers = new ArrayList<>(); - private static List, String>> staticObservers = new ArrayList<>(); + private List, String>> observers = new ArrayList<>(); + private static List, String>> staticObservers = new ArrayList<>(); static record ConfigReadResult(Map ruleMap, boolean locked) {} /** @@ -174,11 +174,11 @@ public class SettingsManager * @see SettingsManager#addGlobalRuleObserver(TriConsumer) * * @param observer A {@link TriConsumer} that will be called with - * the used {@link ServerCommandSource}, the changed + * the used {@link CommandSourceStack}, the changed * {@link ParsedRule} and a {@link String} being the * value that the user typed. */ - public void addRuleObserver(TriConsumer, String> observer) + public void addRuleObserver(TriConsumer, String> observer) { observers.add(observer); } @@ -189,17 +189,17 @@ public class SettingsManager * @see SettingsManager#addRuleObserver(TriConsumer) * * @param observer A {@link TriConsumer} that will be called with - * the used {@link ServerCommandSource}, the changed + * the used {@link CommandSourceStack}, the changed * {@link ParsedRule} and a {@link String} being the * value that the user typed. */ - public static void addGlobalRuleObserver(TriConsumer, String> observer) + public static void addGlobalRuleObserver(TriConsumer, String> observer) { staticObservers.add(observer); } - void notifyRuleChanged(ServerCommandSource source, ParsedRule rule, String userTypedValue) + void notifyRuleChanged(CommandSourceStack source, ParsedRule rule, String userTypedValue) { observers.forEach(observer -> observer.accept(source, rule, userTypedValue)); staticObservers.forEach(observer -> observer.accept(source, rule, userTypedValue)); @@ -208,7 +208,7 @@ public class SettingsManager if (CARPET_RULE_CHANGES.isNeeded()) CARPET_RULE_CHANGES.onCarpetRuleChanges(rule, source); } - private void switchScarpetRuleIfNeeded(ServerCommandSource source, ParsedRule rule) + private void switchScarpetRuleIfNeeded(CommandSourceStack source, ParsedRule rule) { if (!rule.scarpetApp.isEmpty()) { @@ -229,7 +229,7 @@ public class SettingsManager for (ParsedRule rule : rules.values()) { if (!rule.scarpetApp.isEmpty()) { - switchScarpetRuleIfNeeded(server.getCommandSource(), rule); + switchScarpetRuleIfNeeded(server.createCommandSourceStack(), rule); } } } @@ -287,7 +287,7 @@ public class SettingsManager private Path getFile() { - return server.getSavePath(WorldSavePath.ROOT).resolve(identifier+".conf"); + return server.getWorldPath(LevelResource.ROOT).resolve(identifier+".conf"); } /** @@ -301,9 +301,9 @@ public class SettingsManager if (!rule.categories.contains(RuleCategory.COMMAND)) continue; if (rule.type == boolean.class) - ((ParsedRule) rule).set(server.getCommandSource(), false, "false"); + ((ParsedRule) rule).set(server.createCommandSourceStack(), false, "false"); if (rule.type == String.class && rule.options.contains("false")) - ((ParsedRule) rule).set(server.getCommandSource(), "false", "false"); + ((ParsedRule) rule).set(server.createCommandSourceStack(), "false", "false"); } } @@ -332,15 +332,15 @@ public class SettingsManager */ public void notifyPlayersCommandsChanged() { - if (server == null || server.getPlayerManager() == null) + if (server == null || server.getPlayerList() == null) { return; } - server.send(new ServerTask(this.server.getTicks(), () -> + server.tell(new TickTask(this.server.getTickCount(), () -> { try { - for (ServerPlayerEntity entityplayermp : server.getPlayerManager().getPlayerList()) { - server.getCommandManager().sendCommandTree(entityplayermp); + for (ServerPlayer entityplayermp : server.getPlayerList().getPlayers()) { + server.getCommands().sendCommands(entityplayermp); } } catch (NullPointerException ignored) {} @@ -348,15 +348,15 @@ public class SettingsManager } /** - * Returns whether the the {@link ServerCommandSource} can execute + * Returns whether the the {@link CommandSourceStack} can execute * a command given the required permission level, according to * Carpet's standard for permissions. - * @param source The origin {@link ServerCommandSource} + * @param source The origin {@link CommandSourceStack} * @param commandLevel A {@link String} being the permission level (either 0-4, a * {@link boolean} value or "ops". - * @return Whether or not the {@link ServerCommandSource} meets the required level + * @return Whether or not the {@link CommandSourceStack} meets the required level */ - public static boolean canUseCommand(ServerCommandSource source, Object commandLevel) + public static boolean canUseCommand(CommandSourceStack source, Object commandLevel) { if (commandLevel instanceof Boolean) return (Boolean) commandLevel; String commandLevelString = commandLevel.toString(); @@ -364,13 +364,13 @@ public class SettingsManager { case "true": return true; case "false": return false; - case "ops": return source.hasPermissionLevel(2); // typical for other cheaty commands + case "ops": return source.hasPermission(2); // typical for other cheaty commands case "0": case "1": case "2": case "3": case "4": - return source.hasPermissionLevel(Integer.parseInt(commandLevelString)); + return source.hasPermission(Integer.parseInt(commandLevelString)); } return false; } @@ -401,7 +401,7 @@ public class SettingsManager private void loadConfigurationFromConf() { - for (ParsedRule rule : rules.values()) rule.resetToDefault(server.getCommandSource()); + for (ParsedRule rule : rules.values()) rule.resetToDefault(server.createCommandSourceStack()); ConfigReadResult conf = readSettingsFromConf(getFile()); locked = false; if (conf.locked()) @@ -413,7 +413,7 @@ public class SettingsManager { try { - if (rules.get(key).set(server.getCommandSource(), conf.ruleMap().get(key)) != null) + if (rules.get(key).set(server.createCommandSourceStack(), conf.ruleMap().get(key)) != null) CarpetSettings.LOG.info("[CM]: loaded setting " + key + " as " + conf.ruleMap().get(key) + " from " + identifier + ".conf"); } catch (Exception exc) @@ -541,7 +541,7 @@ public class SettingsManager } - private ParsedRule contextRule(CommandContext ctx) throws CommandSyntaxException + private ParsedRule contextRule(CommandContext ctx) throws CommandSyntaxException { String ruleName = StringArgumentType.getString(ctx, "rule"); ParsedRule rule = getRule(ruleName); @@ -564,7 +564,7 @@ public class SettingsManager smartSuggestionList.add(listItem); } // Regular prefix matching, reference: CommandSource.suggestMatching - if (CommandSource.shouldSuggest(query, listItem.toLowerCase(Locale.ROOT))) { + if (SharedSuggestionProvider.matchesSubStr(query, listItem.toLowerCase(Locale.ROOT))) { regularSuggestionList.add(listItem); } }); @@ -579,7 +579,7 @@ public class SettingsManager * It is handled automatically by Carpet. * @param dispatcher The current {@link CommandDispatcher} */ - public void registerCommand(CommandDispatcher dispatcher) + public void registerCommand(CommandDispatcher dispatcher) { if (dispatcher.getRoot().getChildren().stream().anyMatch(node -> node.getName().equalsIgnoreCase(identifier))) { @@ -587,7 +587,7 @@ public class SettingsManager return; } - LiteralArgumentBuilder literalargumentbuilder = literal(identifier).requires((player) -> + LiteralArgumentBuilder literalargumentbuilder = literal(identifier).requires((player) -> canUseCommand(player, CarpetSettings.carpetCommandPermissionLevel) && !locked); literalargumentbuilder.executes((context)-> listAllSettings(context.getSource())). @@ -599,7 +599,7 @@ public class SettingsManager String.format(tr("ui.current_%(mod)s_startup_settings_from_%(conf)s","Current %s Startup Settings from %s"), fancyName, (identifier+".conf")), findStartupOverrides()))). then(argument("tag",StringArgumentType.word()). - suggests( (c, b)->suggestMatching(getCategories(), b)). + suggests( (c, b)->suggest(getCategories(), b)). executes( (c) -> listSettings(c.getSource(), String.format(tr("ui.%(mod)s_settings_matching_'%(query)s'","%s Settings matching \"%s\""), fancyName, tr("category." + StringArgumentType.getString(c, "tag"),StringArgumentType.getString(c, "tag"))), getRulesMatching(StringArgumentType.getString(c, "tag")))))). @@ -613,22 +613,22 @@ public class SettingsManager then(argument("rule", StringArgumentType.word()). suggests( (c, b) -> suggestMatchingContains(getRules().stream().map(r -> r.name), b)). then(argument("value", StringArgumentType.greedyString()). - suggests((c, b)-> suggestMatching(contextRule(c).options, b)). + suggests((c, b)-> suggest(contextRule(c).options, b)). executes((c) -> setDefault(c.getSource(), contextRule(c), StringArgumentType.getString(c, "value")))))). then(argument("rule", StringArgumentType.word()). suggests( (c, b) -> suggestMatchingContains(getRules().stream().map(r -> r.name), b)). requires(s -> !locked ). executes( (c) -> displayRuleMenu(c.getSource(), contextRule(c))). then(argument("value", StringArgumentType.greedyString()). - suggests((c, b)-> suggestMatching(contextRule(c).options,b)). + suggests((c, b)-> suggest(contextRule(c).options,b)). executes((c) -> setRule(c.getSource(), contextRule(c), StringArgumentType.getString(c, "value"))))); dispatcher.register(literalargumentbuilder); } - private int displayRuleMenu(ServerCommandSource source, ParsedRule rule) + private int displayRuleMenu(CommandSourceStack source, ParsedRule rule) { - PlayerEntity player; + Player player; String displayName = rule.translatedName(); Messenger.m(source, ""); @@ -637,7 +637,7 @@ public class SettingsManager rule.translatedExtras().forEach(s -> Messenger.m(source, "g "+s)); - List tags = new ArrayList<>(); + List tags = new ArrayList<>(); tags.add(Messenger.c("w "+ tr("ui.tags", "Tags")+": ")); for (String t: rule.categories) { @@ -649,7 +649,7 @@ public class SettingsManager Messenger.m(source, tags.toArray(new Object[0])); Messenger.m(source, "w "+ tr("ui.current_value", "Current value")+": ",String.format("%s %s (%s value)",rule.getBoolValue()?"lb":"nb", rule.getAsString(),rule.isDefault()?"default":"modified")); - List options = new ArrayList<>(); + List options = new ArrayList<>(); options.add(Messenger.c("w Options: ", "y [ ")); for (String o: rule.options) { @@ -663,7 +663,7 @@ public class SettingsManager return 1; } - private int setRule(ServerCommandSource source, ParsedRule rule, String newValue) + private int setRule(CommandSourceStack source, ParsedRule rule, String newValue) { if (rule.set(source, newValue) != null) Messenger.m(source, "w "+rule.toString()+", ", "c ["+ tr("ui.change_permanently","change permanently")+"?]", @@ -673,7 +673,7 @@ public class SettingsManager } // stores different defaults in the file - private int setDefault(ServerCommandSource source, ParsedRule rule, String stringValue) + private int setDefault(CommandSourceStack source, ParsedRule rule, String stringValue) { if (locked) return 0; if (!rules.containsKey(rule.name)) return 0; @@ -686,7 +686,7 @@ public class SettingsManager return 1; } // removes overrides of the default values in the file - private int removeDefault(ServerCommandSource source, ParsedRule rule) + private int removeDefault(CommandSourceStack source, ParsedRule rule) { if (locked) return 0; if (!rules.containsKey(rule.name)) return 0; @@ -698,7 +698,7 @@ public class SettingsManager return 1; } - private BaseText displayInteractiveSetting(ParsedRule rule) + private BaseComponent displayInteractiveSetting(ParsedRule rule) { String displayName = rule.translatedName(); List args = new ArrayList<>(); @@ -719,7 +719,7 @@ public class SettingsManager return Messenger.c(args.toArray(new Object[0])); } - private BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) + private BaseComponent makeSetRuleButton(ParsedRule rule, String option, boolean brackets) { String style = rule.isDefault()?"g":(option.equalsIgnoreCase(rule.defaultAsString)?"e":"y"); if (option.equalsIgnoreCase(rule.getAsString())) @@ -736,14 +736,14 @@ public class SettingsManager return Messenger.c(baseText, "^g "+ tr("ui.switch_to","Switch to") +" " + option+(option.equalsIgnoreCase(rule.defaultAsString)?" (default)":""), "?/"+identifier+" " + rule.name + " " + option); } - private int listSettings(ServerCommandSource source, String title, Collection> settings_list) + private int listSettings(CommandSourceStack source, String title, Collection> settings_list) { Messenger.m(source,String.format("wb %s:",title)); settings_list.forEach(e -> Messenger.m(source,displayInteractiveSetting(e))); return settings_list.size(); } - private int listAllSettings(ServerCommandSource source) + private int listAllSettings(CommandSourceStack source) { int count = listSettings(source, String.format(tr("ui.current_%(mod)s_settings","Current %s Settings"), fancyName), getNonDefault()); @@ -768,7 +768,7 @@ public class SettingsManager return count; } - public void inspectClientsideCommand(ServerCommandSource source, String string) + public void inspectClientsideCommand(CommandSourceStack source, String string) { if (string.startsWith("/"+identifier+" ")) { diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java index f4cabfad..4112891b 100644 --- a/src/main/java/carpet/settings/Validator.java +++ b/src/main/java/carpet/settings/Validator.java @@ -2,11 +2,10 @@ package carpet.settings; import carpet.CarpetServer; import carpet.utils.Messenger; -import net.minecraft.server.command.ServerCommandSource; - import java.util.List; import java.util.Locale; import java.util.stream.Collectors; +import net.minecraft.commands.CommandSourceStack; public abstract class Validator { @@ -14,9 +13,9 @@ public abstract class Validator * Validate the new value of a rule * @return true if valid, false if new rule invalid. */ - public abstract T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); + public abstract T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string); public String description() {return null;} - public void notifyFailure(ServerCommandSource source, ParsedRule currentRule, String providedValue) + public void notifyFailure(CommandSourceStack source, ParsedRule currentRule, String providedValue) { Messenger.m(source, "r Wrong value for " + currentRule.name + ": " + providedValue); } @@ -24,7 +23,7 @@ public abstract class Validator public static class _COMMAND extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { if (CarpetServer.settingsManager != null && source != null) CarpetServer.settingsManager.notifyPlayersCommandsChanged(); @@ -37,7 +36,7 @@ public abstract class Validator public static class _CLIENT extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { return newValue; } @@ -49,7 +48,7 @@ public abstract class Validator public static class _COMMAND_LEVEL_VALIDATOR extends Validator { private static List OPTIONS = List.of("true", "false", "ops", "0", "1", "2", "3", "4"); - @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String userString) { + @Override public String validate(CommandSourceStack source, ParsedRule currentRule, String newValue, String userString) { if (!OPTIONS.contains(userString.toLowerCase(Locale.ROOT))) { Messenger.m(source, "r Valid options for command type rules is 'true' or 'false'"); @@ -64,7 +63,7 @@ public abstract class Validator public static class _SCARPET extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { return newValue; } @@ -76,7 +75,7 @@ public abstract class Validator public static class WIP extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { Messenger.m(source, "r "+currentRule.name+" is missing a few bits - we are still working on it."); return newValue; @@ -87,7 +86,7 @@ public abstract class Validator public static class _STRICT extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { if (!currentRule.options.contains(string)) { @@ -101,7 +100,7 @@ public abstract class Validator public static class _STRICT_IGNORECASE extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { if (!currentRule.options.stream().map(s->s.toLowerCase(Locale.ROOT)).collect(Collectors.toSet()) .contains(string.toLowerCase(Locale.ROOT))) @@ -116,7 +115,7 @@ public abstract class Validator public static class NONNEGATIVE_NUMBER extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { return newValue.doubleValue() >= 0 ? newValue : null; } @@ -127,7 +126,7 @@ public abstract class Validator public static class PROBABILITY extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + public T validate(CommandSourceStack source, ParsedRule currentRule, T newValue, String string) { return (newValue.doubleValue() >= 0 && newValue.doubleValue() <= 1 )? newValue : null; } diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index 2d1633e0..26560c71 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -1,290 +1,288 @@ package carpet.utils; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.block.MapColor; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.ai.NoPenaltyTargeting; -import net.minecraft.entity.ai.goal.WanderAroundGoal; -import net.minecraft.entity.ai.pathing.NavigationType; -import net.minecraft.entity.mob.PathAwareEntity; -import net.minecraft.entity.mob.ZombifiedPiglinEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.sound.BlockSoundGroup; -import net.minecraft.text.BaseText; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.LightType; -import net.minecraft.world.World; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.RandomStrollGoal; +import net.minecraft.world.entity.ai.util.DefaultRandomPos; +import net.minecraft.world.entity.monster.ZombifiedPiglin; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.material.MaterialColor; +import net.minecraft.world.level.pathfinder.PathComputationType; +import net.minecraft.world.phys.Vec3; public class BlockInfo { - public static final Map soundName = new HashMap() {{ - put(BlockSoundGroup.WOOD, "wood" ); - put(BlockSoundGroup.GRAVEL, "gravel"); - put(BlockSoundGroup.GRASS, "grass" ); - put(BlockSoundGroup.LILY_PAD, "lily_pad"); - put(BlockSoundGroup.STONE, "stone" ); - put(BlockSoundGroup.METAL, "metal" ); - put(BlockSoundGroup.GLASS , "glass" ); - put(BlockSoundGroup.WOOL , "wool" ); - put(BlockSoundGroup.SAND , "sand" ); - put(BlockSoundGroup.SNOW , "snow" ); - put(BlockSoundGroup.POWDER_SNOW , "powder_snow" ); - put(BlockSoundGroup.LADDER, "ladder"); - put(BlockSoundGroup.ANVIL , "anvil" ); - put(BlockSoundGroup.SLIME , "slime" ); - put(BlockSoundGroup.HONEY , "honey" ); - put(BlockSoundGroup.WET_GRASS , "sea_grass" ); - put(BlockSoundGroup.CORAL , "coral" ); - put(BlockSoundGroup.BAMBOO , "bamboo" ); - put(BlockSoundGroup.BAMBOO_SAPLING , "shoots" ); - put(BlockSoundGroup.SCAFFOLDING , "scaffolding" ); - put(BlockSoundGroup.SWEET_BERRY_BUSH , "berry" ); - put(BlockSoundGroup.CROP , "crop" ); - put(BlockSoundGroup.STEM , "stem" ); - put(BlockSoundGroup.VINE , "vine" ); - put(BlockSoundGroup.NETHER_WART , "wart" ); - put(BlockSoundGroup.LANTERN , "lantern" ); - put(BlockSoundGroup.NETHER_STEM, "fungi_stem"); - put(BlockSoundGroup.NYLIUM, "nylium"); - put(BlockSoundGroup.FUNGUS, "fungus"); - put(BlockSoundGroup.ROOTS, "roots"); - put(BlockSoundGroup.SHROOMLIGHT, "shroomlight"); - put(BlockSoundGroup.WEEPING_VINES, "weeping_vine"); - put(BlockSoundGroup.WEEPING_VINES_LOW_PITCH, "twisting_vine"); - put(BlockSoundGroup.SOUL_SAND, "soul_sand"); - put(BlockSoundGroup.SOUL_SOIL, "soul_soil"); - put(BlockSoundGroup.BASALT, "basalt"); - put(BlockSoundGroup.WART_BLOCK, "wart"); - put(BlockSoundGroup.NETHERRACK, "netherrack"); - put(BlockSoundGroup.NETHER_BRICKS, "nether_bricks"); - put(BlockSoundGroup.NETHER_SPROUTS, "nether_sprouts"); - put(BlockSoundGroup.NETHER_ORE, "nether_ore"); - put(BlockSoundGroup.BONE, "bone"); - put(BlockSoundGroup.NETHERITE, "netherite"); - put(BlockSoundGroup.ANCIENT_DEBRIS, "ancient_debris"); - put(BlockSoundGroup.LODESTONE, "lodestone"); - put(BlockSoundGroup.CHAIN, "chain"); - put(BlockSoundGroup.NETHER_GOLD_ORE, "nether_gold_ore"); - put(BlockSoundGroup.GILDED_BLACKSTONE, "gilded_blackstone"); - put(BlockSoundGroup.CANDLE, "candle"); - put(BlockSoundGroup.AMETHYST_BLOCK, "amethyst"); - put(BlockSoundGroup.AMETHYST_CLUSTER, "amethyst_cluster"); - put(BlockSoundGroup.SMALL_AMETHYST_BUD, "small_amethyst_bud"); - put(BlockSoundGroup.MEDIUM_AMETHYST_BUD, "medium_amethyst_bud"); - put(BlockSoundGroup.LARGE_AMETHYST_BUD, "large_amethyst_bud"); + public static final Map soundName = new HashMap() {{ + put(SoundType.WOOD, "wood" ); + put(SoundType.GRAVEL, "gravel"); + put(SoundType.GRASS, "grass" ); + put(SoundType.LILY_PAD, "lily_pad"); + put(SoundType.STONE, "stone" ); + put(SoundType.METAL, "metal" ); + put(SoundType.GLASS , "glass" ); + put(SoundType.WOOL , "wool" ); + put(SoundType.SAND , "sand" ); + put(SoundType.SNOW , "snow" ); + put(SoundType.POWDER_SNOW , "powder_snow" ); + put(SoundType.LADDER, "ladder"); + put(SoundType.ANVIL , "anvil" ); + put(SoundType.SLIME_BLOCK , "slime" ); + put(SoundType.HONEY_BLOCK , "honey" ); + put(SoundType.WET_GRASS , "sea_grass" ); + put(SoundType.CORAL_BLOCK , "coral" ); + put(SoundType.BAMBOO , "bamboo" ); + put(SoundType.BAMBOO_SAPLING , "shoots" ); + put(SoundType.SCAFFOLDING , "scaffolding" ); + put(SoundType.SWEET_BERRY_BUSH , "berry" ); + put(SoundType.CROP , "crop" ); + put(SoundType.HARD_CROP , "stem" ); + put(SoundType.VINE , "vine" ); + put(SoundType.NETHER_WART , "wart" ); + put(SoundType.LANTERN , "lantern" ); + put(SoundType.STEM, "fungi_stem"); + put(SoundType.NYLIUM, "nylium"); + put(SoundType.FUNGUS, "fungus"); + put(SoundType.ROOTS, "roots"); + put(SoundType.SHROOMLIGHT, "shroomlight"); + put(SoundType.WEEPING_VINES, "weeping_vine"); + put(SoundType.TWISTING_VINES, "twisting_vine"); + put(SoundType.SOUL_SAND, "soul_sand"); + put(SoundType.SOUL_SOIL, "soul_soil"); + put(SoundType.BASALT, "basalt"); + put(SoundType.WART_BLOCK, "wart"); + put(SoundType.NETHERRACK, "netherrack"); + put(SoundType.NETHER_BRICKS, "nether_bricks"); + put(SoundType.NETHER_SPROUTS, "nether_sprouts"); + put(SoundType.NETHER_ORE, "nether_ore"); + put(SoundType.BONE_BLOCK, "bone"); + put(SoundType.NETHERITE_BLOCK, "netherite"); + put(SoundType.ANCIENT_DEBRIS, "ancient_debris"); + put(SoundType.LODESTONE, "lodestone"); + put(SoundType.CHAIN, "chain"); + put(SoundType.NETHER_GOLD_ORE, "nether_gold_ore"); + put(SoundType.GILDED_BLACKSTONE, "gilded_blackstone"); + put(SoundType.CANDLE, "candle"); + put(SoundType.AMETHYST, "amethyst"); + put(SoundType.AMETHYST_CLUSTER, "amethyst_cluster"); + put(SoundType.SMALL_AMETHYST_BUD, "small_amethyst_bud"); + put(SoundType.MEDIUM_AMETHYST_BUD, "medium_amethyst_bud"); + put(SoundType.LARGE_AMETHYST_BUD, "large_amethyst_bud"); - put(BlockSoundGroup.TUFF, "tuff"); - put(BlockSoundGroup.CALCITE, "calcite"); - put(BlockSoundGroup.DRIPSTONE_BLOCK, "dripstone"); - put(BlockSoundGroup.POINTED_DRIPSTONE, "pointed_dripstone"); - put(BlockSoundGroup.COPPER, "copper"); - put(BlockSoundGroup.CAVE_VINES, "cave_vine"); - put(BlockSoundGroup.SPORE_BLOSSOM, "spore_blossom"); - put(BlockSoundGroup.AZALEA, "azalea"); - put(BlockSoundGroup.FLOWERING_AZALEA, "flowering_azalea"); - put(BlockSoundGroup.MOSS_CARPET, "moss_carpet"); - put(BlockSoundGroup.MOSS_BLOCK, "moss"); - put(BlockSoundGroup.BIG_DRIPLEAF, "big_dripleaf"); - put(BlockSoundGroup.SMALL_DRIPLEAF, "small_dripleaf"); - put(BlockSoundGroup.ROOTED_DIRT, "rooted_dirt"); - put(BlockSoundGroup.HANGING_ROOTS, "hanging_roots"); - put(BlockSoundGroup.AZALEA_LEAVES, "azalea_leaves"); - put(BlockSoundGroup.SCULK_SENSOR, "sculk_sensor"); - put(BlockSoundGroup.GLOW_LICHEN, "glow_lichen"); - put(BlockSoundGroup.DEEPSLATE, "deepslate"); - put(BlockSoundGroup.DEEPSLATE_BRICKS, "deepslate_bricks"); - put(BlockSoundGroup.DEEPSLATE_TILES, "deepslate_tiles"); - put(BlockSoundGroup.POLISHED_DEEPSLATE, "polished_deepslate"); + put(SoundType.TUFF, "tuff"); + put(SoundType.CALCITE, "calcite"); + put(SoundType.DRIPSTONE_BLOCK, "dripstone"); + put(SoundType.POINTED_DRIPSTONE, "pointed_dripstone"); + put(SoundType.COPPER, "copper"); + put(SoundType.CAVE_VINES, "cave_vine"); + put(SoundType.SPORE_BLOSSOM, "spore_blossom"); + put(SoundType.AZALEA, "azalea"); + put(SoundType.FLOWERING_AZALEA, "flowering_azalea"); + put(SoundType.MOSS_CARPET, "moss_carpet"); + put(SoundType.MOSS, "moss"); + put(SoundType.BIG_DRIPLEAF, "big_dripleaf"); + put(SoundType.SMALL_DRIPLEAF, "small_dripleaf"); + put(SoundType.ROOTED_DIRT, "rooted_dirt"); + put(SoundType.HANGING_ROOTS, "hanging_roots"); + put(SoundType.AZALEA_LEAVES, "azalea_leaves"); + put(SoundType.SCULK_SENSOR, "sculk_sensor"); + put(SoundType.GLOW_LICHEN, "glow_lichen"); + put(SoundType.DEEPSLATE, "deepslate"); + put(SoundType.DEEPSLATE_BRICKS, "deepslate_bricks"); + put(SoundType.DEEPSLATE_TILES, "deepslate_tiles"); + put(SoundType.POLISHED_DEEPSLATE, "polished_deepslate"); }}; - public static final Map mapColourName = new HashMap() {{ - put(MapColor.CLEAR , "air" ); - put(MapColor.PALE_GREEN , "grass" ); - put(MapColor.PALE_YELLOW , "sand" ); - put(MapColor.WHITE_GRAY , "wool" ); - put(MapColor.BRIGHT_RED , "tnt" ); - put(MapColor.PALE_PURPLE , "ice" ); - put(MapColor.IRON_GRAY , "iron" ); - put(MapColor.DARK_GREEN , "foliage" ); - put(MapColor.WHITE , "snow" ); - put(MapColor.LIGHT_BLUE_GRAY , "clay" ); - put(MapColor.DIRT_BROWN , "dirt" ); - put(MapColor.STONE_GRAY , "stone" ); - put(MapColor.WATER_BLUE , "water" ); - put(MapColor.OAK_TAN , "wood" ); - put(MapColor.OFF_WHITE , "quartz" ); - put(MapColor.ORANGE , "adobe" ); - put(MapColor.MAGENTA , "magenta" ); - put(MapColor.LIGHT_BLUE, "light_blue"); - put(MapColor.YELLOW , "yellow" ); - put(MapColor.LIME , "lime" ); - put(MapColor.PINK , "pink" ); - put(MapColor.GRAY , "gray" ); - put(MapColor.LIGHT_GRAY, "light_gray"); - put(MapColor.CYAN , "cyan" ); - put(MapColor.PURPLE , "purple" ); - put(MapColor.BLUE , "blue" ); - put(MapColor.BROWN , "brown" ); - put(MapColor.GREEN , "green" ); - put(MapColor.RED , "red" ); - put(MapColor.BLACK , "black" ); - put(MapColor.GOLD , "gold" ); - put(MapColor.DIAMOND_BLUE , "diamond" ); - put(MapColor.LAPIS_BLUE , "lapis" ); - put(MapColor.EMERALD_GREEN , "emerald" ); - put(MapColor.SPRUCE_BROWN , "obsidian" ); - put(MapColor.DARK_RED , "netherrack"); //TODO fix these - put(MapColor.TERRACOTTA_WHITE , "white_terracotta" ); - put(MapColor.TERRACOTTA_ORANGE , "orange_terracotta" ); - put(MapColor.TERRACOTTA_MAGENTA , "magenta_terracotta" ); - put(MapColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ); - put(MapColor.TERRACOTTA_YELLOW , "yellow_terracotta" ); - put(MapColor.TERRACOTTA_LIME , "lime_terracotta" ); - put(MapColor.TERRACOTTA_PINK , "pink_terracotta" ); - put(MapColor.TERRACOTTA_GRAY , "gray_terracotta" ); - put(MapColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ); - put(MapColor.TERRACOTTA_CYAN , "cyan_terracotta" ); - put(MapColor.TERRACOTTA_PURPLE , "purple_terracotta" ); - put(MapColor.TERRACOTTA_BLUE , "blue_terracotta" ); - put(MapColor.TERRACOTTA_BROWN , "brown_terracotta" ); - put(MapColor.TERRACOTTA_GREEN , "green_terracotta" ); - put(MapColor.TERRACOTTA_RED , "red_terracotta" ); - put(MapColor.TERRACOTTA_BLACK , "black_terracotta" ); - put(MapColor.DULL_RED , "crimson_nylium" ); - put(MapColor.DULL_PINK , "crimson_stem" ); - put(MapColor.DARK_CRIMSON , "crimson_hyphae" ); - put(MapColor.TEAL , "warped_nylium" ); - put(MapColor.DARK_AQUA , "warped_stem" ); - put(MapColor.DARK_DULL_PINK , "warped_hyphae" ); - put(MapColor.BRIGHT_TEAL , "warped_wart" ); - put(MapColor.DEEPSLATE_GRAY , "deepslate" ); - put(MapColor.RAW_IRON_PINK , "raw_iron" ); - put(MapColor.LICHEN_GREEN , "glow_lichen" ); + public static final Map mapColourName = new HashMap() {{ + put(MaterialColor.NONE , "air" ); + put(MaterialColor.GRASS , "grass" ); + put(MaterialColor.SAND , "sand" ); + put(MaterialColor.WOOL , "wool" ); + put(MaterialColor.FIRE , "tnt" ); + put(MaterialColor.ICE , "ice" ); + put(MaterialColor.METAL , "iron" ); + put(MaterialColor.PLANT , "foliage" ); + put(MaterialColor.SNOW , "snow" ); + put(MaterialColor.CLAY , "clay" ); + put(MaterialColor.DIRT , "dirt" ); + put(MaterialColor.STONE , "stone" ); + put(MaterialColor.WATER , "water" ); + put(MaterialColor.WOOD , "wood" ); + put(MaterialColor.QUARTZ , "quartz" ); + put(MaterialColor.COLOR_ORANGE , "adobe" ); + put(MaterialColor.COLOR_MAGENTA , "magenta" ); + put(MaterialColor.COLOR_LIGHT_BLUE, "light_blue"); + put(MaterialColor.COLOR_YELLOW , "yellow" ); + put(MaterialColor.COLOR_LIGHT_GREEN , "lime" ); + put(MaterialColor.COLOR_PINK , "pink" ); + put(MaterialColor.COLOR_GRAY , "gray" ); + put(MaterialColor.COLOR_LIGHT_GRAY, "light_gray"); + put(MaterialColor.COLOR_CYAN , "cyan" ); + put(MaterialColor.COLOR_PURPLE , "purple" ); + put(MaterialColor.COLOR_BLUE , "blue" ); + put(MaterialColor.COLOR_BROWN , "brown" ); + put(MaterialColor.COLOR_GREEN , "green" ); + put(MaterialColor.COLOR_RED , "red" ); + put(MaterialColor.COLOR_BLACK , "black" ); + put(MaterialColor.GOLD , "gold" ); + put(MaterialColor.DIAMOND , "diamond" ); + put(MaterialColor.LAPIS , "lapis" ); + put(MaterialColor.EMERALD , "emerald" ); + put(MaterialColor.PODZOL , "obsidian" ); + put(MaterialColor.NETHER , "netherrack"); //TODO fix these + put(MaterialColor.TERRACOTTA_WHITE , "white_terracotta" ); + put(MaterialColor.TERRACOTTA_ORANGE , "orange_terracotta" ); + put(MaterialColor.TERRACOTTA_MAGENTA , "magenta_terracotta" ); + put(MaterialColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ); + put(MaterialColor.TERRACOTTA_YELLOW , "yellow_terracotta" ); + put(MaterialColor.TERRACOTTA_LIGHT_GREEN , "lime_terracotta" ); + put(MaterialColor.TERRACOTTA_PINK , "pink_terracotta" ); + put(MaterialColor.TERRACOTTA_GRAY , "gray_terracotta" ); + put(MaterialColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ); + put(MaterialColor.TERRACOTTA_CYAN , "cyan_terracotta" ); + put(MaterialColor.TERRACOTTA_PURPLE , "purple_terracotta" ); + put(MaterialColor.TERRACOTTA_BLUE , "blue_terracotta" ); + put(MaterialColor.TERRACOTTA_BROWN , "brown_terracotta" ); + put(MaterialColor.TERRACOTTA_GREEN , "green_terracotta" ); + put(MaterialColor.TERRACOTTA_RED , "red_terracotta" ); + put(MaterialColor.TERRACOTTA_BLACK , "black_terracotta" ); + put(MaterialColor.CRIMSON_NYLIUM , "crimson_nylium" ); + put(MaterialColor.CRIMSON_STEM , "crimson_stem" ); + put(MaterialColor.CRIMSON_HYPHAE , "crimson_hyphae" ); + put(MaterialColor.WARPED_NYLIUM , "warped_nylium" ); + put(MaterialColor.WARPED_STEM , "warped_stem" ); + put(MaterialColor.WARPED_HYPHAE , "warped_hyphae" ); + put(MaterialColor.WARPED_WART_BLOCK , "warped_wart" ); + put(MaterialColor.DEEPSLATE , "deepslate" ); + put(MaterialColor.RAW_IRON , "raw_iron" ); + put(MaterialColor.GLOW_LICHEN , "glow_lichen" ); }}; public static final Map materialName = new HashMap() {{ put(Material.AIR , "air" ); - put(Material.STRUCTURE_VOID , "void" ); + put(Material.STRUCTURAL_AIR , "void" ); put(Material.PORTAL , "portal" ); - put(Material.CARPET , "carpet" ); + put(Material.CLOTH_DECORATION , "carpet" ); put(Material.PLANT , "plant" ); - put(Material.UNDERWATER_PLANT, "water_plant" ); + put(Material.WATER_PLANT, "water_plant" ); put(Material.REPLACEABLE_PLANT, "vegetation" ); - put(Material.NETHER_SHOOTS, "nether_shoots" ); - put(Material.REPLACEABLE_UNDERWATER_PLANT, "sea_grass" ); + put(Material.REPLACEABLE_FIREPROOF_PLANT, "nether_shoots" ); + put(Material.REPLACEABLE_WATER_PLANT, "sea_grass" ); put(Material.WATER , "water" ); put(Material.BUBBLE_COLUMN , "bubble_column"); put(Material.LAVA , "lava" ); - put(Material.SNOW_LAYER , "snow_layer" ); + put(Material.TOP_SNOW , "snow_layer" ); put(Material.FIRE , "fire" ); put(Material.DECORATION , "decoration" ); - put(Material.COBWEB , "cobweb" ); + put(Material.WEB , "cobweb" ); put(Material.SCULK , "sculk" ); - put(Material.REDSTONE_LAMP , "redstone_lamp"); - put(Material.ORGANIC_PRODUCT, "clay" ); - put(Material.SOIL , "dirt" ); - put(Material.SOLID_ORGANIC , "grass" ); - put(Material.DENSE_ICE , "packed_ice" ); - put(Material.AGGREGATE , "sand" ); + put(Material.BUILDABLE_GLASS , "redstone_lamp"); + put(Material.CLAY, "clay" ); + put(Material.DIRT , "dirt" ); + put(Material.GRASS , "grass" ); + put(Material.ICE_SOLID , "packed_ice" ); + put(Material.SAND , "sand" ); put(Material.SPONGE , "sponge" ); - put(Material.SHULKER_BOX , "shulker" ); + put(Material.SHULKER_SHELL , "shulker" ); put(Material.WOOD , "wood" ); put(Material.NETHER_WOOD , "nether_wood" ); put(Material.BAMBOO_SAPLING , "shoots" ); put(Material.BAMBOO , "bamboo" ); put(Material.WOOL , "wool" ); - put(Material.TNT , "tnt" ); + put(Material.EXPLOSIVE , "tnt" ); put(Material.LEAVES , "leaves" ); put(Material.GLASS , "glass" ); put(Material.ICE , "ice" ); put(Material.CACTUS , "cactus" ); put(Material.STONE , "stone" ); put(Material.METAL , "metal" ); - put(Material.SNOW_BLOCK , "snow" ); - put(Material.REPAIR_STATION , "anvil" ); + put(Material.SNOW , "snow" ); + put(Material.HEAVY_METAL , "anvil" ); put(Material.BARRIER , "barrier" ); put(Material.PISTON , "piston" ); - put(Material.MOSS_BLOCK , "moss" ); - put(Material.GOURD , "gourd" ); + put(Material.MOSS , "moss" ); + put(Material.VEGETABLE , "gourd" ); put(Material.EGG , "dragon_egg" ); put(Material.CAKE , "cake" ); put(Material.AMETHYST , "amethyst" ); put(Material.POWDER_SNOW , "powder_snow"); }}; - public static List blockInfo(BlockPos pos, ServerWorld world) + public static List blockInfo(BlockPos pos, ServerLevel world) { BlockState state = world.getBlockState(pos); Material material = state.getMaterial(); Block block = state.getBlock(); String metastring = ""; - for (net.minecraft.state.property.Property iproperty : state.getProperties()) + for (net.minecraft.world.level.block.state.properties.Property iproperty : state.getProperties()) { - metastring += ", "+iproperty.getName() + '='+state.get(iproperty); + metastring += ", "+iproperty.getName() + '='+state.getValue(iproperty); } - List lst = new ArrayList<>(); + List lst = new ArrayList<>(); lst.add(Messenger.s("")); lst.add(Messenger.s("=====================================")); - lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):",Registry.BLOCK.getId(block),metastring, Registry.BLOCK.getRawId(block), metastring ))); + lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):",Registry.BLOCK.getKey(block),metastring, Registry.BLOCK.getId(block), metastring ))); lst.add(Messenger.s(String.format(" - Material: %s", materialName.get(material)))); lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getMapColor(world, pos))))); - lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundGroup(state))))); + lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundType(state))))); lst.add(Messenger.s("")); - lst.add(Messenger.s(String.format(" - Full block: %s", state.isFullCube(world, pos)))); // isFullCube() ))); - lst.add(Messenger.s(String.format(" - Normal cube: %s", state.isSolidBlock(world, pos)))); //isNormalCube()))); isSimpleFullBlock + lst.add(Messenger.s(String.format(" - Full block: %s", state.isCollisionShapeFullBlock(world, pos)))); // isFullCube() ))); + lst.add(Messenger.s(String.format(" - Normal cube: %s", state.isRedstoneConductor(world, pos)))); //isNormalCube()))); isSimpleFullBlock lst.add(Messenger.s(String.format(" - Is liquid: %s", material.isLiquid()))); lst.add(Messenger.s("")); lst.add(Messenger.s(String.format(" - Light in: %d, above: %d", - Math.max(world.getLightLevel(LightType.BLOCK, pos),world.getLightLevel(LightType.SKY, pos)) , - Math.max(world.getLightLevel(LightType.BLOCK, pos.up()),world.getLightLevel(LightType.SKY, pos.up()))))); - lst.add(Messenger.s(String.format(" - Brightness in: %.2f, above: %.2f", world.getBrightness(pos), world.getBrightness(pos.up())))); + Math.max(world.getBrightness(LightLayer.BLOCK, pos),world.getBrightness(LightLayer.SKY, pos)) , + Math.max(world.getBrightness(LightLayer.BLOCK, pos.above()),world.getBrightness(LightLayer.SKY, pos.above()))))); + lst.add(Messenger.s(String.format(" - Brightness in: %.2f, above: %.2f", world.getBrightness(pos), world.getBrightness(pos.above())))); lst.add(Messenger.s(String.format(" - Is opaque: %s", material.isSolid() ))); //lst.add(Messenger.s(String.format(" - Light opacity: %d", state.getOpacity(world,pos)))); - lst.add(Messenger.s(String.format(" - Blocks light: %s", state.getMaterial().blocksLight()))); + lst.add(Messenger.s(String.format(" - Blocks light: %s", state.getMaterial().isSolidBlocking()))); //lst.add(Messenger.s(String.format(" - Emitted light: %d", state.getLightValue()))); //lst.add(Messenger.s(String.format(" - Picks neighbour light value: %s", state.useNeighborBrightness(world, pos)))); lst.add(Messenger.s("")); - lst.add(Messenger.s(String.format(" - Causes suffocation: %s", state.shouldSuffocate(world, pos)))); //canSuffocate - lst.add(Messenger.s(String.format(" - Blocks movement on land: %s", !state.canPathfindThrough(world,pos, NavigationType.LAND)))); - lst.add(Messenger.s(String.format(" - Blocks movement in air: %s", !state.canPathfindThrough(world,pos, NavigationType.AIR)))); - lst.add(Messenger.s(String.format(" - Blocks movement in liquids: %s", !state.canPathfindThrough(world,pos, NavigationType.WATER)))); - lst.add(Messenger.s(String.format(" - Can burn: %s", material.isBurnable()))); + lst.add(Messenger.s(String.format(" - Causes suffocation: %s", state.isSuffocating(world, pos)))); //canSuffocate + lst.add(Messenger.s(String.format(" - Blocks movement on land: %s", !state.isPathfindable(world,pos, PathComputationType.LAND)))); + lst.add(Messenger.s(String.format(" - Blocks movement in air: %s", !state.isPathfindable(world,pos, PathComputationType.AIR)))); + lst.add(Messenger.s(String.format(" - Blocks movement in liquids: %s", !state.isPathfindable(world,pos, PathComputationType.WATER)))); + lst.add(Messenger.s(String.format(" - Can burn: %s", material.isFlammable()))); lst.add(Messenger.s(String.format(" - Requires a tool: %s", !material.isReplaceable()))); //?maybe - lst.add(Messenger.s(String.format(" - Hardness: %.2f", state.getHardness(world, pos)))); - lst.add(Messenger.s(String.format(" - Blast resistance: %.2f", block.getBlastResistance()))); - lst.add(Messenger.s(String.format(" - Ticks randomly: %s", block.hasRandomTicks(state)))); + lst.add(Messenger.s(String.format(" - Hardness: %.2f", state.getDestroySpeed(world, pos)))); + lst.add(Messenger.s(String.format(" - Blast resistance: %.2f", block.getExplosionResistance()))); + lst.add(Messenger.s(String.format(" - Ticks randomly: %s", block.isRandomlyTicking(state)))); lst.add(Messenger.s("")); - lst.add(Messenger.s(String.format(" - Can provide power: %s", state.emitsRedstonePower()))); - lst.add(Messenger.s(String.format(" - Strong power level: %d", world.getReceivedStrongRedstonePower(pos)))); - lst.add(Messenger.s(String.format(" - Redstone power level: %d", world.getReceivedRedstonePower(pos)))); + lst.add(Messenger.s(String.format(" - Can provide power: %s", state.isSignalSource()))); + lst.add(Messenger.s(String.format(" - Strong power level: %d", world.getDirectSignalTo(pos)))); + lst.add(Messenger.s(String.format(" - Redstone power level: %d", world.getBestNeighborSignal(pos)))); lst.add(Messenger.s("")); - lst.add(wander_chances(pos.up(), world)); + lst.add(wander_chances(pos.above(), world)); return lst; } - private static BaseText wander_chances(BlockPos pos, ServerWorld worldIn) + private static BaseComponent wander_chances(BlockPos pos, ServerLevel worldIn) { - PathAwareEntity creature = new ZombifiedPiglinEntity(EntityType.ZOMBIFIED_PIGLIN, worldIn); - creature.initialize(worldIn, worldIn.getLocalDifficulty(pos), SpawnReason.NATURAL, null, null); - creature.refreshPositionAndAngles(pos, 0.0F, 0.0F); - WanderAroundGoal wander = new WanderAroundGoal(creature, 0.8D); + PathfinderMob creature = new ZombifiedPiglin(EntityType.ZOMBIFIED_PIGLIN, worldIn); + creature.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(pos), MobSpawnType.NATURAL, null, null); + creature.moveTo(pos, 0.0F, 0.0F); + RandomStrollGoal wander = new RandomStrollGoal(creature, 0.8D); int success = 0; for (int i=0; i<1000; i++) { - Vec3d vec = NoPenaltyTargeting.find(creature, 10, 7); // TargetFinder.findTarget(creature, 10, 7); + Vec3 vec = DefaultRandomPos.getPos(creature, 10, 7); // TargetFinder.findTarget(creature, 10, 7); if (vec == null) { continue; @@ -297,7 +295,7 @@ public class BlockInfo int i; for (i=1;i<30*20*60; i++) //*60 used to be 5 hours, limited to 30 mins { - if (wander.canStart()) + if (wander.canUse()) { break; } diff --git a/src/main/java/carpet/utils/CarpetProfiler.java b/src/main/java/carpet/utils/CarpetProfiler.java index d5ad5fd6..d7a5132a 100644 --- a/src/main/java/carpet/utils/CarpetProfiler.java +++ b/src/main/java/carpet/utils/CarpetProfiler.java @@ -2,16 +2,16 @@ package carpet.utils; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.World; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; import org.apache.commons.lang3.tuple.Pair; import java.util.Comparator; @@ -22,11 +22,11 @@ import java.util.stream.Collectors; public class CarpetProfiler { private static final Map SECTION_STATS = new HashMap<>(); - private static final Object2LongMap> ENTITY_TIMES = new Object2LongOpenHashMap<>(); - private static final Object2LongMap> ENTITY_COUNT = new Object2LongOpenHashMap<>(); + private static final Object2LongMap> ENTITY_TIMES = new Object2LongOpenHashMap<>(); + private static final Object2LongMap> ENTITY_COUNT = new Object2LongOpenHashMap<>(); - private static ServerCommandSource currentRequester = null; + private static CommandSourceStack currentRequester = null; public static int tick_health_requested = 0; private static int tick_health_elapsed = 0; private static TYPE test_type = TYPE.NONE; //1 for ticks, 2 for entities @@ -50,15 +50,15 @@ public class CarpetProfiler TILEENTITY } - public static record ProfilerToken(TYPE type, Object section, long start, World world) + public static record ProfilerToken(TYPE type, Object section, long start, Level world) { - public ProfilerToken(TYPE type, Object section, World world) + public ProfilerToken(TYPE type, Object section, Level world) { this(type, section, System.nanoTime(), world); } } - public static void prepare_tick_report(ServerCommandSource source, int ticks) + public static void prepare_tick_report(CommandSourceStack source, int ticks) { //maybe add so it only spams the sending player, but honestly - all may want to see it SECTION_STATS.clear(); @@ -74,11 +74,11 @@ public class CarpetProfiler { SECTION_STATS.put(section, 0L); } - for (RegistryKey level : source.getServer().getWorldRegistryKeys()) + for (ResourceKey level : source.getServer().levelKeys()) { for (String section : SECTIONS) { - SECTION_STATS.put(level.getValue() + "." + section, 0L); + SECTION_STATS.put(level.location() + "." + section, 0L); } } @@ -88,7 +88,7 @@ public class CarpetProfiler currentRequester = source; } - public static void prepare_entity_report(ServerCommandSource source, int ticks) + public static void prepare_entity_report(CommandSourceStack source, int ticks) { //maybe add so it only spams the sending player, but honestly - all may want to see it SECTION_STATS.clear(); @@ -102,21 +102,21 @@ public class CarpetProfiler currentRequester = source; } - public static ProfilerToken start_section(World world, String name, TYPE type) + public static ProfilerToken start_section(Level world, String name, TYPE type) { if (tick_health_requested == 0L || test_type != TYPE.GENERAL || current_tick_start == 0) return null; return new ProfilerToken(type, name, world); } - public static ProfilerToken start_entity_section(World world, Entity e, TYPE type) + public static ProfilerToken start_entity_section(Level world, Entity e, TYPE type) { if (tick_health_requested == 0L || test_type != TYPE.ENTITY || current_tick_start == 0) return null; return new ProfilerToken(type, e.getType(), world); } - public static ProfilerToken start_block_entity_section(World world, BlockEntity be, TYPE type) + public static ProfilerToken start_block_entity_section(Level world, BlockEntity be, TYPE type) { if (tick_health_requested == 0L || test_type != TYPE.ENTITY || current_tick_start == 0) return null; @@ -130,10 +130,10 @@ public class CarpetProfiler long end_time = System.nanoTime(); if (tok.type == TYPE.GENERAL) { - World world = tok.world; + Level world = tok.world; String current_section = (world == null) ? (String) tok.section : - String.format("%s.%s%s", world.getRegistryKey().getValue(), tok.section, world.isClient ? " (Client)" : ""); + String.format("%s.%s%s", world.dimension().location(), tok.section, world.isClientSide ? " (Client)" : ""); SECTION_STATS.put(current_section, SECTION_STATS.getOrDefault(current_section, 0L) + end_time - tok.start); } } @@ -143,7 +143,7 @@ public class CarpetProfiler if (tick_health_requested == 0L || test_type != TYPE.ENTITY || current_tick_start == 0 || tok == null) return; long end_time = System.nanoTime(); - Pair section = Pair.of(tok.world, tok.section); + Pair section = Pair.of(tok.world, tok.section); ENTITY_TIMES.put(section, ENTITY_TIMES.getOrDefault(section, 0L) + end_time - tok.start); ENTITY_COUNT.put(section, ENTITY_COUNT.getOrDefault(section, 0L) + 1); } @@ -216,9 +216,9 @@ public class CarpetProfiler } } - for (RegistryKey dim : server.getWorldRegistryKeys()) + for (ResourceKey dim : server.levelKeys()) { - Identifier dimensionId = dim.getValue(); + ResourceLocation dimensionId = dim.location(); boolean hasSomethin = false; for (String section : SECTIONS) { @@ -253,23 +253,23 @@ public class CarpetProfiler Messenger.m(currentRequester, String.format("gi The Rest, whatever that might be: %.3fms", divider * rest)); } - private static String sectionName(Pair section) + private static String sectionName(Pair section) { - Identifier id; + ResourceLocation id; if (section.getValue() instanceof EntityType) { - id = Registry.ENTITY_TYPE.getId((EntityType) section.getValue()); + id = Registry.ENTITY_TYPE.getKey((EntityType) section.getValue()); } else { - id = Registry.BLOCK_ENTITY_TYPE.getId((BlockEntityType) section.getValue()); + id = Registry.BLOCK_ENTITY_TYPE.getKey((BlockEntityType) section.getValue()); } String name = "minecraft".equals(id.getNamespace())?id.getPath():id.toString(); - if (section.getKey().isClient) + if (section.getKey().isClientSide) { name += " (client)"; } - Identifier dimkey = section.getKey().getRegistryKey().getValue(); + ResourceLocation dimkey = section.getKey().dimension().location(); String dim = "minecraft".equals(dimkey.getNamespace())?dimkey.getPath():dimkey.toString(); return name+" in "+dim; } @@ -286,11 +286,11 @@ public class CarpetProfiler SECTION_STATS.remove("tick"); Messenger.m(currentRequester, "wb Top 10 counts:"); int total = 0; - for (Object2LongMap.Entry> sectionEntry : ENTITY_COUNT.object2LongEntrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList())) + for (Object2LongMap.Entry> sectionEntry : ENTITY_COUNT.object2LongEntrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList())) { if (++total > 10) break; - Pair section = sectionEntry.getKey(); - boolean cli = section.getKey().isClient; + Pair section = sectionEntry.getKey(); + boolean cli = section.getKey().isClientSide; Messenger.m(currentRequester, String.format( "%s - %s: ", cli?"gi":"w", sectionName(section)), @@ -300,11 +300,11 @@ public class CarpetProfiler } Messenger.m(currentRequester, "wb Top 10 CPU hogs:"); total = 0; - for (Object2LongMap.Entry> sectionEntry : ENTITY_TIMES.object2LongEntrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList())) + for (Object2LongMap.Entry> sectionEntry : ENTITY_TIMES.object2LongEntrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList())) { if (++total > 10) break; - Pair section = sectionEntry.getKey(); - boolean cli = section.getKey().isClient; + Pair section = sectionEntry.getKey(); + boolean cli = section.getKey().isClientSide; Messenger.m(currentRequester, String.format( "%s - %s: ", cli?"gi":"w", sectionName(section)), diff --git a/src/main/java/carpet/utils/DistanceCalculator.java b/src/main/java/carpet/utils/DistanceCalculator.java index f7b97bdc..9e11597e 100644 --- a/src/main/java/carpet/utils/DistanceCalculator.java +++ b/src/main/java/carpet/utils/DistanceCalculator.java @@ -1,32 +1,31 @@ package carpet.utils; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.text.BaseText; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.Vec3; public class DistanceCalculator { - public static final HashMap START_POINT_STORAGE = new HashMap<>(); + public static final HashMap START_POINT_STORAGE = new HashMap<>(); - public static boolean hasStartingPoint(ServerCommandSource source) + public static boolean hasStartingPoint(CommandSourceStack source) { - return START_POINT_STORAGE.containsKey(source.getName()); + return START_POINT_STORAGE.containsKey(source.getTextName()); } - public static List findDistanceBetweenTwoPoints(Vec3d pos1, Vec3d pos2) + public static List findDistanceBetweenTwoPoints(Vec3 pos1, Vec3 pos2) { - double dx = MathHelper.abs((float)pos1.x-(float)pos2.x); - double dy = MathHelper.abs((float)pos1.y-(float)pos2.y); - double dz = MathHelper.abs((float)pos1.z-(float)pos2.z); + double dx = Mth.abs((float)pos1.x-(float)pos2.x); + double dy = Mth.abs((float)pos1.y-(float)pos2.y); + double dz = Mth.abs((float)pos1.z-(float)pos2.z); double manhattan = dx+dy+dz; double spherical = Math.sqrt(dx*dx + dy*dy + dz*dz); double cylindrical = Math.sqrt(dx*dx + dz*dz); - List res = new ArrayList<>(); + List res = new ArrayList<>(); res.add(Messenger.c("w Distance between ", Messenger.tp("c",pos1),"w and ", Messenger.tp("c",pos2),"w :")); @@ -36,29 +35,29 @@ public class DistanceCalculator return res; } - public static int distance(ServerCommandSource source, Vec3d pos1, Vec3d pos2) + public static int distance(CommandSourceStack source, Vec3 pos1, Vec3 pos2) { Messenger.send(source, findDistanceBetweenTwoPoints(pos1, pos2)); return 1; } - public static int setStart(ServerCommandSource source, Vec3d pos) + public static int setStart(CommandSourceStack source, Vec3 pos) { - START_POINT_STORAGE.put(source.getName(), pos); + START_POINT_STORAGE.put(source.getTextName(), pos); Messenger.m(source,"gi Initial point set to: ", Messenger.tp("g",pos)); return 1; } - public static int setEnd(ServerCommandSource source, Vec3d pos) + public static int setEnd(CommandSourceStack source, Vec3 pos) { if ( !hasStartingPoint(source) ) { - START_POINT_STORAGE.put(source.getName(), pos); - Messenger.m(source,"gi There was no initial point for "+source.getName()); + START_POINT_STORAGE.put(source.getTextName(), pos); + Messenger.m(source,"gi There was no initial point for "+source.getTextName()); Messenger.m(source,"gi Initial point set to: ", Messenger.tp("g",pos)); return 0; } - Messenger.send(source, findDistanceBetweenTwoPoints( START_POINT_STORAGE.get(source.getName()), pos)); + Messenger.send(source, findDistanceBetweenTwoPoints( START_POINT_STORAGE.get(source.getTextName()), pos)); return 1; } } diff --git a/src/main/java/carpet/utils/Messenger.java b/src/main/java/carpet/utils/Messenger.java index 0fcfc050..a216d96f 100644 --- a/src/main/java/carpet/utils/Messenger.java +++ b/src/main/java/carpet/utils/Messenger.java @@ -1,20 +1,20 @@ package carpet.utils; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.text.BaseText; -import net.minecraft.text.ClickEvent; -import net.minecraft.text.HoverEvent; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Style; -import net.minecraft.text.TextColor; -import net.minecraft.util.Util; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.Util; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.TextColor; +import net.minecraft.network.chat.TextComponent; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -34,30 +34,30 @@ public class Messenger public enum CarpetFormatting { ITALIC ('i', (s, f) -> s.withItalic(true)), - STRIKE ('s', (s, f) -> s.withFormatting(Formatting.STRIKETHROUGH)), - UNDERLINE ('u', (s, f) -> s.withFormatting(Formatting.UNDERLINE)), + STRIKE ('s', (s, f) -> s.applyFormat(ChatFormatting.STRIKETHROUGH)), + UNDERLINE ('u', (s, f) -> s.applyFormat(ChatFormatting.UNDERLINE)), BOLD ('b', (s, f) -> s.withBold(true)), - OBFUSCATE ('o', (s, f) -> s.withFormatting(Formatting.OBFUSCATED)), + OBFUSCATE ('o', (s, f) -> s.applyFormat(ChatFormatting.OBFUSCATED)), - WHITE ('w', (s, f) -> s.withColor(Formatting.WHITE)), - YELLOW ('y', (s, f) -> s.withColor(Formatting.YELLOW)), - LIGHT_PURPLE('m', (s, f) -> s.withColor(Formatting.LIGHT_PURPLE)), // magenta - RED ('r', (s, f) -> s.withColor(Formatting.RED)), - AQUA ('c', (s, f) -> s.withColor(Formatting.AQUA)), // cyan - GREEN ('l', (s, f) -> s.withColor(Formatting.GREEN)), // lime - BLUE ('t', (s, f) -> s.withColor(Formatting.BLUE)), // light blue, teal - DARK_GRAY ('f', (s, f) -> s.withColor(Formatting.DARK_GRAY)), - GRAY ('g', (s, f) -> s.withColor(Formatting.GRAY)), - GOLD ('d', (s, f) -> s.withColor(Formatting.GOLD)), - DARK_PURPLE ('p', (s, f) -> s.withColor(Formatting.DARK_PURPLE)), // purple - DARK_RED ('n', (s, f) -> s.withColor(Formatting.DARK_RED)), // brown - DARK_AQUA ('q', (s, f) -> s.withColor(Formatting.DARK_AQUA)), - DARK_GREEN ('e', (s, f) -> s.withColor(Formatting.DARK_GREEN)), - DARK_BLUE ('v', (s, f) -> s.withColor(Formatting.DARK_BLUE)), // navy - BLACK ('k', (s, f) -> s.withColor(Formatting.BLACK)), + WHITE ('w', (s, f) -> s.withColor(ChatFormatting.WHITE)), + YELLOW ('y', (s, f) -> s.withColor(ChatFormatting.YELLOW)), + LIGHT_PURPLE('m', (s, f) -> s.withColor(ChatFormatting.LIGHT_PURPLE)), // magenta + RED ('r', (s, f) -> s.withColor(ChatFormatting.RED)), + AQUA ('c', (s, f) -> s.withColor(ChatFormatting.AQUA)), // cyan + GREEN ('l', (s, f) -> s.withColor(ChatFormatting.GREEN)), // lime + BLUE ('t', (s, f) -> s.withColor(ChatFormatting.BLUE)), // light blue, teal + DARK_GRAY ('f', (s, f) -> s.withColor(ChatFormatting.DARK_GRAY)), + GRAY ('g', (s, f) -> s.withColor(ChatFormatting.GRAY)), + GOLD ('d', (s, f) -> s.withColor(ChatFormatting.GOLD)), + DARK_PURPLE ('p', (s, f) -> s.withColor(ChatFormatting.DARK_PURPLE)), // purple + DARK_RED ('n', (s, f) -> s.withColor(ChatFormatting.DARK_RED)), // brown + DARK_AQUA ('q', (s, f) -> s.withColor(ChatFormatting.DARK_AQUA)), + DARK_GREEN ('e', (s, f) -> s.withColor(ChatFormatting.DARK_GREEN)), + DARK_BLUE ('v', (s, f) -> s.withColor(ChatFormatting.DARK_BLUE)), // navy + BLACK ('k', (s, f) -> s.withColor(ChatFormatting.BLACK)), COLOR ('#', (s, f) -> { - TextColor color = TextColor.parse("#"+f); + TextColor color = TextColor.parseColor("#"+f); return color == null ? s : s.withColor(color); }, s -> { Matcher m = colorExtract.matcher(s); @@ -88,7 +88,7 @@ public class Messenger public static Style parseStyle(String style) { - Style myStyle= Style.EMPTY.withColor(Formatting.WHITE); + Style myStyle= Style.EMPTY.withColor(ChatFormatting.WHITE); for (CarpetFormatting cf: CarpetFormatting.values()) myStyle = cf.apply(style, myStyle); return myStyle; } @@ -101,7 +101,7 @@ public class Messenger if (actual > reference) color = "m"; return color; } - public static String creatureTypeColor(SpawnGroup type) + public static String creatureTypeColor(MobCategory type) { return switch (type) { @@ -114,11 +114,11 @@ public class Messenger }; } - private static BaseText getChatComponentFromDesc(String message, BaseText previousMessage) + private static BaseComponent getChatComponentFromDesc(String message, BaseComponent previousMessage) { if (message.equalsIgnoreCase("")) { - return new LiteralText(""); + return new TextComponent(""); } if (Character.isWhitespace(message.charAt(0))) { @@ -133,12 +133,12 @@ public class Messenger str = message.substring(limit+1); } if (previousMessage == null) { - BaseText text = new LiteralText(str); + BaseComponent text = new TextComponent(str); text.setStyle(parseStyle(desc)); return text; } Style previousStyle = previousMessage.getStyle(); - BaseText ret = previousMessage; + BaseComponent ret = previousMessage; previousMessage.setStyle(switch (desc.charAt(0)) { case '?' -> previousStyle.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, message.substring(1))); case '!' -> previousStyle.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, message.substring(1))); @@ -146,31 +146,31 @@ public class Messenger case '@' -> previousStyle.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, message.substring(1))); case '&' -> previousStyle.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, message.substring(1))); default -> { // Create a new component - ret = new LiteralText(str); + ret = new TextComponent(str); ret.setStyle(parseStyle(desc)); yield previousStyle; // no op for the previous style } }); return ret; } - public static BaseText tp(String desc, Vec3d pos) { return tp(desc, pos.x, pos.y, pos.z); } - public static BaseText tp(String desc, BlockPos pos) { return tp(desc, pos.getX(), pos.getY(), pos.getZ()); } - public static BaseText tp(String desc, double x, double y, double z) { return tp(desc, (float)x, (float)y, (float)z);} - public static BaseText tp(String desc, float x, float y, float z) + public static BaseComponent tp(String desc, Vec3 pos) { return tp(desc, pos.x, pos.y, pos.z); } + public static BaseComponent tp(String desc, BlockPos pos) { return tp(desc, pos.getX(), pos.getY(), pos.getZ()); } + public static BaseComponent tp(String desc, double x, double y, double z) { return tp(desc, (float)x, (float)y, (float)z);} + public static BaseComponent tp(String desc, float x, float y, float z) { return getCoordsTextComponent(desc, x, y, z, false); } - public static BaseText tp(String desc, int x, int y, int z) + public static BaseComponent tp(String desc, int x, int y, int z) { return getCoordsTextComponent(desc, (float)x, (float)y, (float)z, true); } /// to be continued - public static BaseText dbl(String style, double double_value) + public static BaseComponent dbl(String style, double double_value) { return c(String.format("%s %.1f",style,double_value),String.format("^w %f",double_value)); } - public static BaseText dbls(String style, double ... doubles) + public static BaseComponent dbls(String style, double ... doubles) { StringBuilder str = new StringBuilder(style + " [ "); String prefix = ""; @@ -182,7 +182,7 @@ public class Messenger str.append(" ]"); return c(str.toString()); } - public static BaseText dblf(String style, double ... doubles) + public static BaseComponent dblf(String style, double ... doubles) { StringBuilder str = new StringBuilder(style + " [ "); String prefix = ""; @@ -194,7 +194,7 @@ public class Messenger str.append(" ]"); return c(str.toString()); } - public static BaseText dblt(String style, double ... doubles) + public static BaseComponent dblt(String style, double ... doubles) { List components = new ArrayList<>(); components.add(style+" [ "); @@ -212,7 +212,7 @@ public class Messenger return c(components.toArray(new Object[0])); } - private static BaseText getCoordsTextComponent(String style, float x, float y, float z, boolean isInt) + private static BaseComponent getCoordsTextComponent(String style, float x, float y, float z, boolean isInt) { String text; String command; @@ -230,33 +230,33 @@ public class Messenger } //message source - public static void m(ServerCommandSource source, Object ... fields) + public static void m(CommandSourceStack source, Object ... fields) { if (source != null) - source.sendFeedback(Messenger.c(fields),source.getServer() != null && source.getServer().getWorld(World.OVERWORLD) != null); //OW + source.sendSuccess(Messenger.c(fields),source.getServer() != null && source.getServer().getLevel(Level.OVERWORLD) != null); //OW } - public static void m(PlayerEntity player, Object ... fields) + public static void m(Player player, Object ... fields) { - player.sendSystemMessage(Messenger.c(fields), Util.NIL_UUID); + player.sendMessage(Messenger.c(fields), Util.NIL_UUID); } /* composes single line, multicomponent message, and returns as one chat messagge */ - public static BaseText c(Object ... fields) + public static BaseComponent c(Object ... fields) { - BaseText message = new LiteralText(""); - BaseText previousComponent = null; + BaseComponent message = new TextComponent(""); + BaseComponent previousComponent = null; for (Object o: fields) { - if (o instanceof BaseText) + if (o instanceof BaseComponent) { - message.append((BaseText)o); - previousComponent = (BaseText)o; + message.append((BaseComponent)o); + previousComponent = (BaseComponent)o; continue; } String txt = o.toString(); - BaseText comp = getChatComponentFromDesc(txt, previousComponent); + BaseComponent comp = getChatComponentFromDesc(txt, previousComponent); if (comp != previousComponent) message.append(comp); previousComponent = comp; } @@ -265,13 +265,13 @@ public class Messenger //simple text - public static BaseText s(String text) + public static BaseComponent s(String text) { return s(text,""); } - public static BaseText s(String text, String style) + public static BaseComponent s(String text, String style) { - BaseText message = new LiteralText(text); + BaseComponent message = new TextComponent(text); message.setStyle(parseStyle(style)); return message; } @@ -279,13 +279,13 @@ public class Messenger - public static void send(PlayerEntity player, Collection lines) + public static void send(Player player, Collection lines) { - lines.forEach(message -> player.sendSystemMessage(message, Util.NIL_UUID)); + lines.forEach(message -> player.sendMessage(message, Util.NIL_UUID)); } - public static void send(ServerCommandSource source, Collection lines) + public static void send(CommandSourceStack source, Collection lines) { - lines.stream().forEachOrdered((s) -> source.sendFeedback(s, false)); + lines.stream().forEachOrdered((s) -> source.sendSuccess(s, false)); } @@ -293,21 +293,21 @@ public class Messenger { if (server == null) LOG.error("Message not delivered: "+message); - server.sendSystemMessage(new LiteralText(message), Util.NIL_UUID); - BaseText txt = c("gi "+message); - for (PlayerEntity entityplayer : server.getPlayerManager().getPlayerList()) + server.sendMessage(new TextComponent(message), Util.NIL_UUID); + BaseComponent txt = c("gi "+message); + for (Player entityplayer : server.getPlayerList().getPlayers()) { - entityplayer.sendSystemMessage(txt, Util.NIL_UUID); + entityplayer.sendMessage(txt, Util.NIL_UUID); } } - public static void print_server_message(MinecraftServer server, BaseText message) + public static void print_server_message(MinecraftServer server, BaseComponent message) { if (server == null) LOG.error("Message not delivered: "+message.getString()); - server.sendSystemMessage(message, Util.NIL_UUID); - for (PlayerEntity entityplayer : server.getPlayerManager().getPlayerList()) + server.sendMessage(message, Util.NIL_UUID); + for (Player entityplayer : server.getPlayerList().getPlayers()) { - entityplayer.sendSystemMessage(message, Util.NIL_UUID); + entityplayer.sendMessage(message, Util.NIL_UUID); } } } diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index eb5b58f6..9a94f180 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -2,23 +2,19 @@ package carpet.utils; import carpet.CarpetServer; import com.google.common.collect.Sets; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.effect.StatusEffects; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.tag.FluidTags; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.Registry; - import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; public class MobAI { @@ -31,7 +27,7 @@ public class MobAI public static boolean isTracking(Entity e, TrackingType type) { - if (e.getEntityWorld().isClient()) + if (e.getCommandSenderWorld().isClientSide()) return false; Set currentTrackers = aiTrackers.get(e.getType()); if (currentTrackers == null) @@ -42,9 +38,9 @@ public class MobAI public static void clearTracking(EntityType etype) { aiTrackers.remove(etype); - for(ServerWorld world : CarpetServer.minecraft_server.getWorlds() ) + for(ServerLevel world : CarpetServer.minecraft_server.getAllLevels() ) { - for (Entity e: world.getEntitiesByType(etype, Entity::hasCustomName)) + for (Entity e: world.getEntities(etype, Entity::hasCustomName)) { e.setCustomNameVisible(false); e.setCustomName(null); @@ -65,7 +61,7 @@ public class MobAI { types.addAll(type.types); } - return types.stream().map(t -> Registry.ENTITY_TYPE.getId(t).getPath()).collect(Collectors.toList()); + return types.stream().map(t -> Registry.ENTITY_TYPE.getKey(t).getPath()).collect(Collectors.toList()); } public static List availableFor(EntityType entityType) @@ -105,19 +101,19 @@ public class MobAI */ public static void genericJump(Entity e) { - if (!e.isOnGround() && !e.isInsideWaterOrBubbleColumn() && !e.isInLava()) return; - float m = e.world.getBlockState(e.getBlockPos()).getBlock().getJumpVelocityMultiplier(); - float g = e.world.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpVelocityMultiplier(); + if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava()) return; + float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); + float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); float jumpVelocityMultiplier = (double) m == 1.0D ? g : m; float jumpStrength = (0.42F * jumpVelocityMultiplier); - Vec3d vec3d = e.getVelocity(); - e.setVelocity(vec3d.x, jumpStrength, vec3d.z); + Vec3 vec3d = e.getDeltaMovement(); + e.setDeltaMovement(vec3d.x, jumpStrength, vec3d.z); if (e.isSprinting()) { - float u = e.getYaw() * 0.017453292F; // yaw - e.setVelocity(e.getVelocity().add((-MathHelper.sin(g) * 0.2F), 0.0D, (MathHelper.cos(u) * 0.2F))); + float u = e.getYRot() * 0.017453292F; // yaw + e.setDeltaMovement(e.getDeltaMovement().add((-Mth.sin(g) * 0.2F), 0.0D, (Mth.cos(u) * 0.2F))); } - e.velocityDirty = true; + e.hasImpulse = true; } } diff --git a/src/main/java/carpet/utils/PerimeterDiagnostics.java b/src/main/java/carpet/utils/PerimeterDiagnostics.java index 15c8f9d7..79a1a029 100644 --- a/src/main/java/carpet/utils/PerimeterDiagnostics.java +++ b/src/main/java/carpet/utils/PerimeterDiagnostics.java @@ -1,26 +1,24 @@ package carpet.utils; -import net.minecraft.block.Block; -import net.minecraft.block.Blocks; -import net.minecraft.block.Material; -import net.minecraft.block.BlockState; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.entity.SpawnRestriction; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.mob.WaterCreatureEntity; -import net.minecraft.entity.mob.AmbientEntity; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.mob.Monster; -import net.minecraft.entity.passive.PassiveEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.SpawnHelper; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.SpawnSettings; - import java.util.ArrayList; import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SpawnPlacements; +import net.minecraft.world.entity.ambient.AmbientCreature; +import net.minecraft.world.entity.animal.WaterAnimal; +import net.minecraft.world.entity.monster.Enemy; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; public class PerimeterDiagnostics { @@ -35,11 +33,11 @@ public class PerimeterDiagnostics samples = new ArrayList<>(); } } - private SpawnSettings.SpawnEntry sle; - private ServerWorld worldServer; - private SpawnGroup ctype; - private MobEntity el; - private PerimeterDiagnostics(ServerWorld server, SpawnGroup ctype, MobEntity el) + private MobSpawnSettings.SpawnerData sle; + private ServerLevel worldServer; + private MobCategory ctype; + private Mob el; + private PerimeterDiagnostics(ServerLevel server, MobCategory ctype, Mob el) { this.sle = null; this.worldServer = server; @@ -47,7 +45,7 @@ public class PerimeterDiagnostics this.el = el; } - public static Result countSpots(ServerWorld worldserver, BlockPos epos, MobEntity el) + public static Result countSpots(ServerLevel worldserver, BlockPos epos, Mob el) { BlockPos pos; //List samples = new ArrayList(); @@ -62,35 +60,35 @@ public class PerimeterDiagnostics //int specific_spawns = 0; boolean add_water = false; boolean add_ground = false; - SpawnGroup ctype = null; + MobCategory ctype = null; if (el != null) { - if (el instanceof WaterCreatureEntity) + if (el instanceof WaterAnimal) { add_water = true; - ctype = SpawnGroup.WATER_CREATURE; + ctype = MobCategory.WATER_CREATURE; } - else if (el instanceof PassiveEntity) + else if (el instanceof AgeableMob) { add_ground = true; - ctype = SpawnGroup.CREATURE; + ctype = MobCategory.CREATURE; } - else if (el instanceof Monster) + else if (el instanceof Enemy) { add_ground = true; - ctype = SpawnGroup.MONSTER; + ctype = MobCategory.MONSTER; } - else if (el instanceof AmbientEntity) + else if (el instanceof AmbientCreature) { - ctype = SpawnGroup.AMBIENT; + ctype = MobCategory.AMBIENT; } } PerimeterDiagnostics diagnostic = new PerimeterDiagnostics(worldserver,ctype,el); EntityType type = EntityType.ZOMBIE; if (el != null) type = el.getType(); - int minY = worldserver.getBottomY(); - int maxY = worldserver.getTopY(); + int minY = worldserver.getMinBuildHeight(); + int maxY = worldserver.getMaxBuildHeight(); for (int x = -128; x <= 128; ++x) { for (int z = -128; z <= 128; ++z) @@ -113,10 +111,10 @@ public class PerimeterDiagnostics pos = new BlockPos(eX+x, y, eZ+z); BlockState iblockstate = worldserver.getBlockState(pos); - BlockState iblockstate_down = worldserver.getBlockState(pos.down()); - BlockState iblockstate_up = worldserver.getBlockState(pos.up()); + BlockState iblockstate_down = worldserver.getBlockState(pos.below()); + BlockState iblockstate_up = worldserver.getBlockState(pos.above()); - if ( iblockstate.getMaterial() == Material.WATER && iblockstate_down.getMaterial() == Material.WATER && !iblockstate_up.isSolidBlock(worldserver, pos)) // isSimpleFUllBLock + if ( iblockstate.getMaterial() == Material.WATER && iblockstate_down.getMaterial() == Material.WATER && !iblockstate_up.isRedstoneConductor(worldserver, pos)) // isSimpleFUllBLock { result.liquid++; if (add_water && diagnostic.check_entity_spawn(pos)) @@ -130,11 +128,11 @@ public class PerimeterDiagnostics } else { - if (iblockstate_down.isSolidBlock(worldserver, pos)) // isSimpleFUllBLock + if (iblockstate_down.isRedstoneConductor(worldserver, pos)) // isSimpleFUllBLock { Block block = iblockstate_down.getBlock(); boolean flag = block != Blocks.BEDROCK && block != Blocks.BARRIER; - if( flag && SpawnHelper.isClearForSpawn(worldserver, pos, iblockstate, iblockstate.getFluidState(), type) && SpawnHelper.isClearForSpawn(worldserver, pos.up(), iblockstate_up, iblockstate_up.getFluidState(), type)) + if( flag && NaturalSpawner.isValidEmptySpawnBlock(worldserver, pos, iblockstate, iblockstate.getFluidState(), type) && NaturalSpawner.isValidEmptySpawnBlock(worldserver, pos.above(), iblockstate_up, iblockstate_up.getFluidState(), type)) { result.ground ++; if (add_ground && diagnostic.check_entity_spawn(pos)) @@ -161,10 +159,10 @@ public class PerimeterDiagnostics private boolean check_entity_spawn(BlockPos pos) { - if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries().contains(sle)) + if (sle == null || !worldServer.getChunkSource().getGenerator().getMobsAt(worldServer.getBiome(pos), worldServer.structureFeatureManager(), ctype, pos).unwrap().contains(sle)) { sle = null; - for (SpawnSettings.SpawnEntry sle: worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries()) + for (MobSpawnSettings.SpawnerData sle: worldServer.getChunkSource().getGenerator().getMobsAt(worldServer.getBiome(pos), worldServer.structureFeatureManager(), ctype, pos).unwrap()) { if (el.getType() == sle.type) { @@ -172,20 +170,20 @@ public class PerimeterDiagnostics break; } } - if (sle == null || !worldServer.getChunkManager().getChunkGenerator().getEntitySpawnList(worldServer.getBiome(pos), worldServer.getStructureAccessor(), ctype, pos).getEntries().contains(sle)) + if (sle == null || !worldServer.getChunkSource().getGenerator().getMobsAt(worldServer.getBiome(pos), worldServer.structureFeatureManager(), ctype, pos).unwrap().contains(sle)) { return false; } } - SpawnRestriction.Location spt = SpawnRestriction.getLocation(sle.type); + SpawnPlacements.Type spt = SpawnPlacements.getPlacementType(sle.type); - if (SpawnHelper.canSpawn(spt, worldServer, pos, sle.type)) + if (NaturalSpawner.isSpawnPositionOk(spt, worldServer, pos, sle.type)) { - el.refreshPositionAndAngles((float)pos.getX() + 0.5F, (float)pos.getY(), (float)pos.getZ()+0.5F, 0.0F, 0.0F); - return el.canSpawn(worldServer) && el.canSpawn(worldServer, SpawnReason.NATURAL) && - SpawnRestriction.canSpawn(el.getType(),(ServerWorld)el.getEntityWorld(), SpawnReason.NATURAL, el.getBlockPos(), el.getEntityWorld().random) && - worldServer.isSpaceEmpty(el); // check collision rules once they stop fiddling with them after 1.14.1 + el.moveTo((float)pos.getX() + 0.5F, (float)pos.getY(), (float)pos.getZ()+0.5F, 0.0F, 0.0F); + return el.checkSpawnObstruction(worldServer) && el.checkSpawnRules(worldServer, MobSpawnType.NATURAL) && + SpawnPlacements.checkSpawnRules(el.getType(),(ServerLevel)el.getCommandSenderWorld(), MobSpawnType.NATURAL, el.blockPosition(), el.getCommandSenderWorld().random) && + worldServer.noCollision(el); // check collision rules once they stop fiddling with them after 1.14.1 } return false; } diff --git a/src/main/java/carpet/utils/SpawnChunks.java b/src/main/java/carpet/utils/SpawnChunks.java index f2e8f117..5c905d17 100644 --- a/src/main/java/carpet/utils/SpawnChunks.java +++ b/src/main/java/carpet/utils/SpawnChunks.java @@ -2,15 +2,15 @@ package carpet.utils; import carpet.fakes.ChunkTicketManagerInterface; import carpet.fakes.ServerChunkManagerInterface; -import net.minecraft.server.world.ChunkTicketManager; -import net.minecraft.server.world.ServerChunkManager; -import net.minecraft.util.math.ChunkPos; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.world.level.ChunkPos; public class SpawnChunks { - public static void changeSpawnChunks(ServerChunkManager chunkManager, ChunkPos pos, int size) + public static void changeSpawnChunks(ServerChunkCache chunkManager, ChunkPos pos, int size) { - ChunkTicketManager ticketManager = ((ServerChunkManagerInterface)chunkManager).getCMTicketManager(); + DistanceManager ticketManager = ((ServerChunkManagerInterface)chunkManager).getCMTicketManager(); ((ChunkTicketManagerInterface)ticketManager).changeSpawnChunks(pos, size); } } diff --git a/src/main/java/carpet/utils/SpawnReporter.java b/src/main/java/carpet/utils/SpawnReporter.java index 18efc24a..914fc528 100644 --- a/src/main/java/carpet/utils/SpawnReporter.java +++ b/src/main/java/carpet/utils/SpawnReporter.java @@ -4,35 +4,34 @@ import carpet.CarpetSettings; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.entity.Entity; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.SpawnRestriction; -import net.minecraft.entity.SpawnReason; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.passive.OcelotEntity; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.tag.BlockTags; -import net.minecraft.text.BaseText; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.DyeColor; -import net.minecraft.util.TypeFilter; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.registry.RegistryKey; -import net.minecraft.world.Heightmap; -import net.minecraft.world.SpawnHelper; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.biome.SpawnSettings; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.gen.StructureAccessor; -import net.minecraft.world.gen.chunk.ChunkGenerator; -import net.minecraft.world.gen.feature.NetherFortressFeature; -import net.minecraft.world.gen.feature.StructureFeature; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SpawnPlacements; +import net.minecraft.world.entity.animal.Ocelot; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.StructureFeatureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.feature.NetherFortressFeature; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; @@ -50,31 +49,31 @@ public class SpawnReporter public static boolean mock_spawns = false; public static Long track_spawns = 0L; - public static final HashMap, Integer> chunkCounts = new HashMap<>(); + public static final HashMap, Integer> chunkCounts = new HashMap<>(); - public static final HashMap, SpawnGroup>, Object2LongMap> spawn_stats = new HashMap<>(); + public static final HashMap, MobCategory>, Object2LongMap> spawn_stats = new HashMap<>(); public static double mobcap_exponent = 0.0D; - public static final HashMap, SpawnGroup>, Long> spawn_attempts = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> overall_spawn_ticks = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> spawn_ticks_full = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> spawn_ticks_fail = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> spawn_ticks_succ = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> spawn_ticks_spawns = new HashMap<>(); - public static final HashMap, SpawnGroup>, Long> spawn_cap_count = new HashMap<>(); - public static final HashMap, SpawnGroup>, EvictingQueue>> spawned_mobs = new HashMap<>(); - public static final HashMap spawn_tries = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_attempts = new HashMap<>(); + public static final HashMap, MobCategory>, Long> overall_spawn_ticks = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_ticks_full = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_ticks_fail = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_ticks_succ = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_ticks_spawns = new HashMap<>(); + public static final HashMap, MobCategory>, Long> spawn_cap_count = new HashMap<>(); + public static final HashMap, MobCategory>, EvictingQueue>> spawned_mobs = new HashMap<>(); + public static final HashMap spawn_tries = new HashMap<>(); public static BlockPos lower_spawning_limit = null; public static BlockPos upper_spawning_limit = null; // in case game gets each thread for each world - these need to belong to workd. - public static HashMap local_spawns = null; // per world - public static HashSet first_chunk_marker = null; + public static HashMap local_spawns = null; // per world + public static HashSet first_chunk_marker = null; static { reset_spawn_stats(null, true); } - public static void registerSpawn(MobEntity mob, SpawnGroup cat, BlockPos pos) + public static void registerSpawn(Mob mob, MobCategory cat, BlockPos pos) { if (lower_spawning_limit != null) { @@ -86,13 +85,13 @@ public class SpawnReporter return; } } - Pair, SpawnGroup> key = Pair.of(mob.world.getRegistryKey(), cat); + Pair, MobCategory> key = Pair.of(mob.level.dimension(), cat); long count = spawn_stats.get(key).getOrDefault(mob.getType(), 0L); spawn_stats.get(key).put(mob.getType(), count + 1); spawned_mobs.get(key).put(Pair.of(mob.getType(), pos)); if (!local_spawns.containsKey(cat)) { - CarpetSettings.LOG.error("Rogue spawn detected for category "+cat.getName()+" for mob "+mob.getType().getName().getString()+". If you see this message let carpet peeps know about it on github issues."); + CarpetSettings.LOG.error("Rogue spawn detected for category "+cat.getName()+" for mob "+mob.getType().getDescription().getString()+". If you see this message let carpet peeps know about it on github issues."); local_spawns.put(cat, 0L); } local_spawns.put(cat, local_spawns.get(cat)+1); @@ -104,15 +103,15 @@ public class SpawnReporter return MAGIC_NUMBER / (Math.pow(2.0,(SpawnReporter.mobcap_exponent/4))); }*/ - public static List printMobcapsForDimension(ServerWorld world, boolean multiline) + public static List printMobcapsForDimension(ServerLevel world, boolean multiline) { - RegistryKey dim = world.getRegistryKey(); - String name = dim.getValue().getPath(); - List lst = new ArrayList<>(); + ResourceKey dim = world.dimension(); + String name = dim.location().getPath(); + List lst = new ArrayList<>(); if (multiline) lst.add(Messenger.s(String.format("Mobcaps for %s:",name))); - SpawnHelper.Info lastSpawner = world.getChunkManager().getSpawnInfo(); - Object2IntMap dimCounts = lastSpawner.getGroupToCount(); + NaturalSpawner.SpawnState lastSpawner = world.getChunkSource().getLastSpawnState(); + Object2IntMap dimCounts = lastSpawner.getMobCategoryCounts(); int chunkcount = chunkCounts.getOrDefault(dim, -1); if (dimCounts == null || chunkcount < 0) { @@ -121,10 +120,10 @@ public class SpawnReporter } List shortCodes = new ArrayList<>(); - for (SpawnGroup enumcreaturetype : SpawnGroup.values()) + for (MobCategory enumcreaturetype : MobCategory.values()) { int cur = dimCounts.getOrDefault(enumcreaturetype, -1); - int max = (int)(chunkcount * ((double)enumcreaturetype.getCapacity() / MAGIC_NUMBER)); // from ServerChunkManager.CHUNKS_ELIGIBLE_FOR_SPAWNING + int max = (int)(chunkcount * ((double)enumcreaturetype.getMaxInstancesPerChunk() / MAGIC_NUMBER)); // from ServerChunkManager.CHUNKS_ELIGIBLE_FOR_SPAWNING String color = Messenger.heatmap_color(cur, max); String mobColor = Messenger.creatureTypeColor(enumcreaturetype); if (multiline) @@ -159,9 +158,9 @@ public class SpawnReporter return lst; } - public static List recent_spawns(World world, SpawnGroup creature_type) + public static List recent_spawns(Level world, MobCategory creature_type) { - List lst = new ArrayList<>(); + List lst = new ArrayList<>(); if ((track_spawns == 0L)) { lst.add(Messenger.s("Spawn tracking not started")); @@ -170,12 +169,12 @@ public class SpawnReporter String type_code = creature_type.getName(); lst.add(Messenger.s(String.format("Recent %s spawns:",type_code))); - for (Pair pair : spawned_mobs.get(Pair.of(world.getRegistryKey(), creature_type)).keySet()) // getDImTYpe + for (Pair pair : spawned_mobs.get(Pair.of(world.dimension(), creature_type)).keySet()) // getDImTYpe { lst.add( Messenger.c( "w - ", Messenger.tp("wb",pair.getRight()), - String.format("w : %s", pair.getLeft().getName().getString()) + String.format("w : %s", pair.getLeft().getDescription().getString()) )); } @@ -187,9 +186,9 @@ public class SpawnReporter } - public static List show_mobcaps(BlockPos pos, ServerWorld worldIn) + public static List show_mobcaps(BlockPos pos, ServerLevel worldIn) { - DyeColor under = WoolTool.getWoolColorAtPosition(worldIn, pos.down()); + DyeColor under = WoolTool.getWoolColorAtPosition(worldIn, pos.below()); if (under == null) { if (track_spawns > 0L) @@ -201,7 +200,7 @@ public class SpawnReporter return printMobcapsForDimension(worldIn, true ); } } - SpawnGroup creature_type = get_type_code_from_wool_code(under); + MobCategory creature_type = get_type_code_from_wool_code(under); if (creature_type != null) { if (track_spawns > 0L) @@ -226,52 +225,52 @@ public class SpawnReporter } - public static SpawnGroup get_type_code_from_wool_code(DyeColor color) + public static MobCategory get_type_code_from_wool_code(DyeColor color) { switch (color) { case RED: - return SpawnGroup.MONSTER; + return MobCategory.MONSTER; case GREEN: - return SpawnGroup.CREATURE; + return MobCategory.CREATURE; case BLUE: - return SpawnGroup.WATER_CREATURE; + return MobCategory.WATER_CREATURE; case BROWN: - return SpawnGroup.AMBIENT; + return MobCategory.AMBIENT; case CYAN: - return SpawnGroup.WATER_AMBIENT; + return MobCategory.WATER_AMBIENT; default: return null; } } - public static SpawnGroup get_creature_type_from_code(String type_code) + public static MobCategory get_creature_type_from_code(String type_code) { if ("hostile".equalsIgnoreCase(type_code)) { - return SpawnGroup.MONSTER; + return MobCategory.MONSTER; } else if ("passive".equalsIgnoreCase(type_code)) { - return SpawnGroup.CREATURE; + return MobCategory.CREATURE; } else if ("water".equalsIgnoreCase(type_code)) { - return SpawnGroup.WATER_CREATURE; + return MobCategory.WATER_CREATURE; } else if ("fish".equalsIgnoreCase(type_code)) { - return SpawnGroup.WATER_AMBIENT; + return MobCategory.WATER_AMBIENT; } else if ("ambient".equalsIgnoreCase(type_code)) { - return SpawnGroup.AMBIENT; + return MobCategory.AMBIENT; } return null; } - public static String get_type_string(SpawnGroup type) + public static String get_type_string(MobCategory type) { return String.format("%s", type); } @@ -281,22 +280,22 @@ public class SpawnReporter return get_type_string(get_creature_type_from_code(str)); } - public static List printEntitiesByType(SpawnGroup cat, World worldIn, boolean all) //Class entityType) + public static List printEntitiesByType(MobCategory cat, Level worldIn, boolean all) //Class entityType) { - List lst = new ArrayList<>(); + List lst = new ArrayList<>(); lst.add( Messenger.s(String.format("Loaded entities for %s class:", get_type_string(cat)))); - for (Entity entity : ((ServerWorld)worldIn).getEntitiesByType(TypeFilter.instanceOf(Entity.class), (e) -> e.getType().getSpawnGroup()==cat)) + for (Entity entity : ((ServerLevel)worldIn).getEntities(EntityTypeTest.forClass(Entity.class), (e) -> e.getType().getCategory()==cat)) { - boolean persistent = entity instanceof MobEntity && ( ((MobEntity) entity).isPersistent() || ((MobEntity) entity).cannotDespawn()); + boolean persistent = entity instanceof Mob && ( ((Mob) entity).isPersistenceRequired() || ((Mob) entity).requiresCustomPersistence()); if (!all && persistent) continue; EntityType type = entity.getType(); - BlockPos pos = entity.getBlockPos(); + BlockPos pos = entity.blockPosition(); lst.add( Messenger.c( "w - ", Messenger.tp(persistent?"gb":"wb",pos), - String.format(persistent?"g : %s":"w : %s", type.getName().getString()) + String.format(persistent?"g : %s":"w : %s", type.getDescription().getString()) )); } @@ -321,15 +320,15 @@ public class SpawnReporter spawn_stats.clear(); spawned_mobs.clear(); - for (SpawnGroup enumcreaturetype : SpawnGroup.values()) + for (MobCategory enumcreaturetype : MobCategory.values()) { if (full) { spawn_tries.put(enumcreaturetype, 1); } - if (server != null) for (RegistryKey dim : server.getWorldRegistryKeys()) + if (server != null) for (ResourceKey dim : server.levelKeys()) { - Pair, SpawnGroup> key = Pair.of(dim, enumcreaturetype); + Pair, MobCategory> key = Pair.of(dim, enumcreaturetype); overall_spawn_ticks.put(key, 0L); spawn_attempts.put(key, 0L); spawn_ticks_full.put(key, 0L); @@ -344,16 +343,16 @@ public class SpawnReporter track_spawns = 0L; } - private static String getWorldCode(RegistryKey world) + private static String getWorldCode(ResourceKey world) { - if (world == World.OVERWORLD) return ""; - return "("+world.getValue().getPath().toUpperCase(Locale.ROOT).replace("THE_","").charAt(0)+")"; + if (world == Level.OVERWORLD) return ""; + return "("+world.location().getPath().toUpperCase(Locale.ROOT).replace("THE_","").charAt(0)+")"; } - public static List tracking_report(World worldIn) + public static List tracking_report(Level worldIn) { - List report = new ArrayList<>(); + List report = new ArrayList<>(); if (track_spawns == 0L) { report.add(Messenger.c( @@ -362,20 +361,20 @@ public class SpawnReporter "w ' to enable")); return report; } - long duration = (long) worldIn.getServer().getTicks() - track_spawns; + long duration = (long) worldIn.getServer().getTickCount() - track_spawns; report.add(Messenger.c("bw --------------------")); String simulated = mock_spawns?"[SIMULATED] ":""; String location = (lower_spawning_limit != null)?String.format("[in (%d, %d, %d)x(%d, %d, %d)]", lower_spawning_limit.getX(),lower_spawning_limit.getY(),lower_spawning_limit.getZ(), upper_spawning_limit.getX(),upper_spawning_limit.getY(),upper_spawning_limit.getZ() ):""; report.add(Messenger.s(String.format("%sSpawn statistics %s: for %.1f min", simulated, location, (duration/72000.0)*60))); - for (SpawnGroup enumcreaturetype : SpawnGroup.values()) + for (MobCategory enumcreaturetype : MobCategory.values()) { //String type_code = String.format("%s", enumcreaturetype); boolean there_are_mobs_to_list = false; - for (RegistryKey dim : worldIn.getServer().getWorldRegistryKeys()) //String world_code: new String[] {"", " (N)", " (E)"}) + for (ResourceKey dim : worldIn.getServer().levelKeys()) //String world_code: new String[] {"", " (N)", " (E)"}) { - Pair, SpawnGroup> code = Pair.of(dim, enumcreaturetype); + Pair, MobCategory> code = Pair.of(dim, enumcreaturetype); if (spawn_ticks_spawns.get(code) > 0L) { there_are_mobs_to_list = true; @@ -392,7 +391,7 @@ public class SpawnReporter for (EntityType type: spawn_stats.get(code).keySet()) { report.add(Messenger.s(String.format(" - %s: %d spawns, %d per hour", - type.getName().getString(), + type.getDescription().getString(), spawn_stats.get(code).getLong(type), (72000 * spawn_stats.get(code).getLong(type)/duration )))); } @@ -406,20 +405,20 @@ public class SpawnReporter public static void killEntity(LivingEntity entity) { - if (entity.hasVehicle()) + if (entity.isPassenger()) { entity.getVehicle().discard(); } - if (entity.hasPassengers()) + if (entity.isVehicle()) { - for (Entity e: entity.getPassengerList()) + for (Entity e: entity.getPassengers()) { e.discard(); } } - if (entity instanceof OcelotEntity) + if (entity instanceof Ocelot) { - for (Entity e: entity.getEntityWorld().getOtherEntities(entity, entity.getBoundingBox())) + for (Entity e: entity.getCommandSenderWorld().getEntities(entity, entity.getBoundingBox())) { e.discard(); } @@ -428,39 +427,39 @@ public class SpawnReporter } // yeeted from SpawnHelper - temporary fix - private static List getSpawnEntries(ServerWorld world, StructureAccessor structureAccessor, ChunkGenerator chunkGenerator, SpawnGroup spawnGroup, BlockPos pos, @Nullable Biome biome) { - return SpawnHelper.shouldUseNetherFortressSpawns(pos, world, spawnGroup, structureAccessor) ? NetherFortressFeature.MONSTER_SPAWNS.getEntries() : chunkGenerator.getEntitySpawnList(biome != null ? biome : world.getBiome(pos), structureAccessor, spawnGroup, pos).getEntries(); + private static List getSpawnEntries(ServerLevel world, StructureFeatureManager structureAccessor, ChunkGenerator chunkGenerator, MobCategory spawnGroup, BlockPos pos, @Nullable Biome biome) { + return NaturalSpawner.isInNetherFortressBounds(pos, world, spawnGroup, structureAccessor) ? NetherFortressFeature.FORTRESS_ENEMIES.unwrap() : chunkGenerator.getMobsAt(biome != null ? biome : world.getBiome(pos), structureAccessor, spawnGroup, pos).unwrap(); } - public static List report(BlockPos pos, ServerWorld worldIn) + public static List report(BlockPos pos, ServerLevel worldIn) { - List rep = new ArrayList<>(); + List rep = new ArrayList<>(); int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); - Chunk chunk = worldIn.getChunk(pos); - int lc = chunk.sampleHeightmap(Heightmap.Type.WORLD_SURFACE, x, z) + 1; - String where = String.format((y >= lc) ? "%d blocks above it." : "%d blocks below it.", MathHelper.abs(y-lc)); + ChunkAccess chunk = worldIn.getChunk(pos); + int lc = chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z) + 1; + String where = String.format((y >= lc) ? "%d blocks above it." : "%d blocks below it.", Mth.abs(y-lc)); if (y == lc) where = "right at it."; rep.add(Messenger.s(String.format("Maximum spawn Y value for (%+d, %+d) is %d. You are "+where, x, z, lc ))); rep.add(Messenger.s("Spawns:")); - for (SpawnGroup enumcreaturetype : SpawnGroup.values()) + for (MobCategory enumcreaturetype : MobCategory.values()) { String type_code = String.format("%s", enumcreaturetype).substring(0, 3); - List lst = getSpawnEntries(worldIn, worldIn.getStructureAccessor(), worldIn.getChunkManager().getChunkGenerator(), enumcreaturetype, pos, worldIn.getBiome(pos) );// ((ChunkGenerator)worldIn.getChunkManager().getChunkGenerator()).getEntitySpawnList(, worldIn.getStructureAccessor(), enumcreaturetype, pos); + List lst = getSpawnEntries(worldIn, worldIn.structureFeatureManager(), worldIn.getChunkSource().getGenerator(), enumcreaturetype, pos, worldIn.getBiome(pos) );// ((ChunkGenerator)worldIn.getChunkManager().getChunkGenerator()).getEntitySpawnList(, worldIn.getStructureAccessor(), enumcreaturetype, pos); if (lst != null && !lst.isEmpty()) { - for (SpawnSettings.SpawnEntry spawnEntry : lst) + for (MobSpawnSettings.SpawnerData spawnEntry : lst) { - if (SpawnRestriction.getLocation(spawnEntry.type)==null) + if (SpawnPlacements.getPlacementType(spawnEntry.type)==null) continue; // vanilla bug - boolean canspawn = SpawnHelper.canSpawn(SpawnRestriction.getLocation(spawnEntry.type), worldIn, pos, spawnEntry.type); + boolean canspawn = NaturalSpawner.isSpawnPositionOk(SpawnPlacements.getPlacementType(spawnEntry.type), worldIn, pos, spawnEntry.type); int will_spawn = -1; boolean fits; boolean fits1; - MobEntity mob; + Mob mob; try { - mob = (MobEntity) spawnEntry.type.create(worldIn); + mob = (Mob) spawnEntry.type.create(worldIn); } catch (Exception exception) { @@ -478,32 +477,32 @@ public class SpawnReporter { float f = (float)x + 0.5F; float f1 = (float)z + 0.5F; - mob.refreshPositionAndAngles((double)f, (double)y, (double)f1, worldIn.random.nextFloat() * 360.0F, 0.0F); - fits1 = worldIn.isSpaceEmpty(mob); + mob.moveTo((double)f, (double)y, (double)f1, worldIn.random.nextFloat() * 360.0F, 0.0F); + fits1 = worldIn.noCollision(mob); EntityType etype = mob.getType(); for (int i = 0; i < 20; ++i) { if ( - SpawnRestriction.canSpawn(etype,worldIn, SpawnReason.NATURAL, pos, worldIn.random) && - SpawnHelper.canSpawn(SpawnRestriction.getLocation(etype), worldIn, pos, etype) && - mob.canSpawn(worldIn, SpawnReason.NATURAL) + SpawnPlacements.checkSpawnRules(etype,worldIn, MobSpawnType.NATURAL, pos, worldIn.random) && + NaturalSpawner.isSpawnPositionOk(SpawnPlacements.getPlacementType(etype), worldIn, pos, etype) && + mob.checkSpawnRules(worldIn, MobSpawnType.NATURAL) // && mob.canSpawn(worldIn) // entity collisions // mostly - except ocelots ) { if (etype == EntityType.OCELOT) { - BlockState blockState = worldIn.getBlockState(pos.down()); - if ((pos.getY() < worldIn.getSeaLevel()) || !(blockState.isOf(Blocks.GRASS_BLOCK) || blockState.isIn(BlockTags.LEAVES))) { + BlockState blockState = worldIn.getBlockState(pos.below()); + if ((pos.getY() < worldIn.getSeaLevel()) || !(blockState.is(Blocks.GRASS_BLOCK) || blockState.is(BlockTags.LEAVES))) { continue; } } will_spawn += 1; } } - mob.initialize(worldIn, worldIn.getLocalDifficulty(mob.getBlockPos()), SpawnReason.NATURAL, null, null); + mob.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.NATURAL, null, null); // the code invokes onInitialSpawn after getCanSpawHere - fits = fits1 && worldIn.isSpaceEmpty(mob); + fits = fits1 && worldIn.noCollision(mob); if (fits) { fits_true = true; @@ -517,7 +516,7 @@ public class SpawnReporter try { - mob = (MobEntity) spawnEntry.type.create(worldIn); + mob = (Mob) spawnEntry.type.create(worldIn); } catch (Exception exception) { @@ -527,14 +526,14 @@ public class SpawnReporter } } - String creature_name = mob.getType().getName().getString(); - String pack_size = String.format("%d", mob.getLimitPerChunk());//String.format("%d-%d", animal.minGroupCount, animal.maxGroupCount); - int weight = spawnEntry.getWeight().getValue(); + String creature_name = mob.getType().getDescription().getString(); + String pack_size = String.format("%d", mob.getMaxSpawnClusterSize());//String.format("%d-%d", animal.minGroupCount, animal.maxGroupCount); + int weight = spawnEntry.getWeight().asInt(); if (canspawn) { String c = (fits_true && will_spawn>0)?"e":"gi"; rep.add(Messenger.c( - String.format("%s %s: %s (%d:%d-%d/%d), can: ",c,type_code,creature_name,weight,spawnEntry.minGroupSize, spawnEntry.maxGroupSize, mob.getLimitPerChunk()), + String.format("%s %s: %s (%d:%d-%d/%d), can: ",c,type_code,creature_name,weight,spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), "l YES", c+" , fit: ", ((fits_true && fits_false)?"y YES and NO":(fits_true?"l YES":"r NO")), @@ -544,7 +543,7 @@ public class SpawnReporter } else { - rep.add(Messenger.c(String.format("gi %s: %s (%d:%d-%d/%d), can: ",type_code,creature_name,weight,spawnEntry.minGroupSize, spawnEntry.maxGroupSize, mob.getLimitPerChunk()), "n NO")); + rep.add(Messenger.c(String.format("gi %s: %s (%d:%d-%d/%d), can: ",type_code,creature_name,weight,spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), "n NO")); } killEntity(mob); } diff --git a/src/main/java/carpet/utils/Translations.java b/src/main/java/carpet/utils/Translations.java index b27be4b1..b1ac8b62 100644 --- a/src/main/java/carpet/utils/Translations.java +++ b/src/main/java/carpet/utils/Translations.java @@ -6,7 +6,6 @@ import carpet.CarpetSettings; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import net.minecraft.server.command.ServerCommandSource; import org.apache.commons.io.IOUtils; import java.io.IOException; @@ -14,6 +13,7 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import net.minecraft.commands.CommandSourceStack; public class Translations { @@ -55,7 +55,7 @@ public class Translations } - public static void updateLanguage(ServerCommandSource source) + public static void updateLanguage(CommandSourceStack source) { if (CarpetSettings.language.equalsIgnoreCase("none")) { diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index 52669d90..17963e9e 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -2,21 +2,20 @@ package carpet.utils; import carpet.CarpetSettings; import carpet.helpers.HopperCounter; -import net.minecraft.block.Material; -import net.minecraft.block.MapColor; -import net.minecraft.block.BlockState; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.DyeColor; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.text.BaseText; -import net.minecraft.world.World; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.BaseComponent; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.material.MaterialColor; +import net.minecraft.world.phys.Vec3; /** * A series of utility functions and variables for dealing predominantly with hopper counters and determining which counter @@ -28,36 +27,36 @@ public class WoolTool * A map of the {@link MaterialColor} to the {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition} * to get the colour of wool at a position. */ - private static final HashMap Material2Dye = new HashMap<>(); + private static final HashMap Material2Dye = new HashMap<>(); /** * A map of all the wool colours to their respective colours in the {@link Messenger#m} format so the name of the counter * gets printed in colour. */ - public static final HashMap Material2DyeName = new HashMap(){{ - put(MapColor.WHITE, "w "); - put(MapColor.ORANGE, "#F9801D "); - put(MapColor.MAGENTA, "m "); - put(MapColor.LIGHT_BLUE, "t "); - put(MapColor.YELLOW, "y "); - put(MapColor.LIME, "l "); - put(MapColor.PINK, "#FFACCB "); - put(MapColor.GRAY, "f "); - put(MapColor.LIGHT_GRAY, "g "); - put(MapColor.CYAN, "c "); - put(MapColor.PURPLE, "p "); - put(MapColor.BLUE, "v "); - put(MapColor.BROWN, "#835432 "); - put(MapColor.GREEN, "e "); - put(MapColor.RED, "r "); - put(MapColor.BLACK, "k "); + public static final HashMap Material2DyeName = new HashMap(){{ + put(MaterialColor.SNOW, "w "); + put(MaterialColor.COLOR_ORANGE, "#F9801D "); + put(MaterialColor.COLOR_MAGENTA, "m "); + put(MaterialColor.COLOR_LIGHT_BLUE, "t "); + put(MaterialColor.COLOR_YELLOW, "y "); + put(MaterialColor.COLOR_LIGHT_GREEN, "l "); + put(MaterialColor.COLOR_PINK, "#FFACCB "); + put(MaterialColor.COLOR_GRAY, "f "); + put(MaterialColor.COLOR_LIGHT_GRAY, "g "); + put(MaterialColor.COLOR_CYAN, "c "); + put(MaterialColor.COLOR_PURPLE, "p "); + put(MaterialColor.COLOR_BLUE, "v "); + put(MaterialColor.COLOR_BROWN, "#835432 "); + put(MaterialColor.COLOR_GREEN, "e "); + put(MaterialColor.COLOR_RED, "r "); + put(MaterialColor.COLOR_BLACK, "k "); }}; static { for (DyeColor color: DyeColor.values()) { - Material2Dye.put(color.getMapColor(),color); + Material2Dye.put(color.getMaterialColor(),color); } } @@ -68,7 +67,7 @@ public class WoolTool *
  • Green - Prints the contents of the counter of the colour of wool underneath the carpet
  • * */ - public static void carpetPlacedAction(DyeColor color, PlayerEntity placer, BlockPos pos, ServerWorld worldIn) + public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos pos, ServerLevel worldIn) { if (!CarpetSettings.carpets) { @@ -88,23 +87,23 @@ public class WoolTool case BROWN: if (!"false".equals(CarpetSettings.commandDistance)) { - ServerCommandSource source = placer.getCommandSource(); - if (!DistanceCalculator.hasStartingPoint(source) || placer.isSneaking()) { - DistanceCalculator.setStart(source, Vec3d.of(pos) ); // zero padded pos + CommandSourceStack source = placer.createCommandSourceStack(); + if (!DistanceCalculator.hasStartingPoint(source) || placer.isShiftKeyDown()) { + DistanceCalculator.setStart(source, Vec3.atLowerCornerOf(pos) ); // zero padded pos } else { - DistanceCalculator.setEnd(source, Vec3d.of(pos)); + DistanceCalculator.setEnd(source, Vec3.atLowerCornerOf(pos)); } } break; case GRAY: if (!"false".equals(CarpetSettings.commandInfo)) - Messenger.send(placer, BlockInfo.blockInfo(pos.down(), worldIn)); + Messenger.send(placer, BlockInfo.blockInfo(pos.below(), worldIn)); break; case GREEN: if (CarpetSettings.hopperCounters) { - DyeColor under = getWoolColorAtPosition(worldIn, pos.down()); + DyeColor under = getWoolColorAtPosition(worldIn, pos.below()); if (under == null) return; HopperCounter counter = HopperCounter.getCounter(under.toString()); if (counter != null) @@ -114,12 +113,12 @@ public class WoolTool case RED: if (CarpetSettings.hopperCounters) { - DyeColor under = getWoolColorAtPosition(worldIn, pos.down()); + DyeColor under = getWoolColorAtPosition(worldIn, pos.below()); if (under == null) return; HopperCounter counter = HopperCounter.getCounter(under.toString()); if (counter == null) return; counter.reset(placer.getServer()); - List res = new ArrayList<>(); + List res = new ArrayList<>(); res.add(Messenger.s(String.format("%s counter reset",under.toString()))); Messenger.send(placer, res); } @@ -130,10 +129,10 @@ public class WoolTool /** * Gets the colour of wool at the position, for hoppers to be able to decide whether to add their items to the global counter. */ - public static DyeColor getWoolColorAtPosition(World worldIn, BlockPos pos) + public static DyeColor getWoolColorAtPosition(Level worldIn, BlockPos pos) { BlockState state = worldIn.getBlockState(pos); - if (state.getMaterial() != Material.WOOL || !state.isSolidBlock(worldIn, pos)) //isSimpleFullBlock + if (state.getMaterial() != Material.WOOL || !state.isRedstoneConductor(worldIn, pos)) //isSimpleFullBlock return null; return Material2Dye.get(state.getMapColor(worldIn, pos)); } diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener index fb8f780d..066a820a 100644 --- a/src/main/resources/carpet.accesswidener +++ b/src/main/resources/carpet.accesswidener @@ -1,7 +1,7 @@ accessWidener v1 named -accessible class net/minecraft/server/world/ThreadedAnvilChunkStorage$TicketManager -accessible class net/minecraft/server/world/ServerLightingProvider$Stage -accessible class net/minecraft/recipe/Ingredient$Entry -accessible class net/minecraft/world/chunk/light/BlockLightStorage$Data -accessible class net/minecraft/world/gen/NoiseColumnSampler$CaveScaler +accessible class net/minecraft/server/level/ChunkMap$DistanceManager +accessible class net/minecraft/server/level/ThreadedLevelLightEngine$TaskType +accessible class net/minecraft/world/item/crafting/Ingredient$Value +accessible class net/minecraft/world/level/lighting/BlockLightSectionStorage$BlockDataLayerStorageMap +accessible class net/minecraft/world/level/levelgen/NoiseSampler$QuantizedSpaghettiRarity diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 69ec16f8..cbe9a232 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -208,10 +208,10 @@ "CaveScalerMixin_scarpetMixin", "BlockEntity_movableBEMixin", - "PistonBlock_movableTEMixin", - "PistonBlockEntity_movableTEMixin", - "World_movableTEMixin", - "WorldChunk_movableTEMixin", + "PistonBlock_movableBEMixin", + "PistonBlockEntity_movableBEMixin", + "World_movableBEMixin", + "WorldChunk_movableBEMixin", "PistonHandler_customStickyMixin", "PlayerEntity_creativeNoClipMixin", "PistonBlockEntity_playerHandlingMixin", @@ -232,7 +232,7 @@ "WorldRenderer_pausedShakeMixin", "InGameHudMixin", "PlayerListHudMixin", - "PistonBlockEntityRenderer_movableTEMixin", + "PistonBlockEntityRenderer_movableBEMixin", "StructureBlockBlockEntityRenderer_mixin", "ClientPlayerEntity_clientCommandMixin", "WorldRenderer_fogOffMixin",