diff --git a/.editorconfig b/.editorconfig index ac7a0202900..41dfea33622 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,4 +10,7 @@ max_line_length = 120 tab_width = 4 [*mixins*.json] -indent_size = 4 \ No newline at end of file +indent_size = 4 + +[*.yaml] +indent_size = 2 \ No newline at end of file diff --git a/.github/workflows/common-run-build.yaml b/.github/workflows/common-run-build.yaml index 027975557b0..c3dbfe08a8d 100644 --- a/.github/workflows/common-run-build.yaml +++ b/.github/workflows/common-run-build.yaml @@ -11,15 +11,30 @@ jobs: # Only run on PRs if the source branch is on someone else's repo if: "${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}" runs-on: ubuntu-22.04 + strategy: + matrix: + project: + - vanilla + - forge + - neoforge + include: + - project: vanilla + gradleProject: SpongeVanilla + - project: forge + gradleProject: SpongeForge + - project: neoforge + gradleProject: SpongeNeo steps: - name: setup id: setup uses: SpongePowered/.github/.github/actions/setup-java-env@master + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" with: runtime_version: 21 publishing_branch_regex: 'api-\d+' - name: setup / cache minecraft dependencies uses: "actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9" # v4.0.2 + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" with: path: | ${{ github.workspace}}/buildSrc/.gradle/ @@ -28,15 +43,18 @@ jobs: restore-keys: | ${{ runner.os }}-minecraft-${{ env.CACHE_REV }}- - name: setup / environment + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" run: | echo "GIT_COMMIT=${GITHUB_SHA}" >> $GITHUB_ENV echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV echo "BUILD_NUMBER=${GITHUB_RUN_NUMBER}" >> $GITHUB_ENV - name: build with Gradle - run: ./gradlew -Pprojects=vanilla,forge,neoforge,testplugins build --stacktrace + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" + run: ./gradlew -Pprojects=${{ matrix.project }},testplugins build --stacktrace env: CI_SYSTEM: Github Actions - name: Archive artifacts for build + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" uses: "actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3" # v4.3.1 with: name: Sponge Jars @@ -46,22 +64,14 @@ jobs: ${{ github.workspace }}/vanilla/build/libs/*.jar ${{ github.workspace }}/forge/build/libs/*.jar ${{ github.workspace }}/neoforge/build/libs/*.jar - - name: SpongeVanilla Production Jar + - name: ${{ matrix.gradleProject }} Production Jar + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" uses: "actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3" # v4.3.1 with: - name: SpongeVanilla Production Jar - path: "${{ github.workspace }}/vanilla/build/libs/*-universal.jar" - - name: SpongeForge Production Jar - uses: "actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3" # v4.3.1 - with: - name: SpongeForge Production Jar - path: "${{ github.workspace }}/forge/build/libs/*-universal.jar" - - name: SpongeNeo Production Jar - uses: "actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3" # v4.3.1 - with: - name: SpongeNeo Production Jar - path: "${{ github.workspace }}/neoforge/build/libs/*-universal.jar" + name: ${{ matrix.gradleProject }} Production Jar + path: "${{ github.workspace }}/${{ matrix.project }}/build/libs/*-universal.jar" - name: SpongeVanilla libraries + if: "matrix.project == 'vanilla'" uses: "actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3" # v4.3.1 with: name: SpongeVanilla installer libraries diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 1ddb706d534..82311bfe60c 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -5,7 +5,9 @@ name: Build and Deploy on: push: - branches: [ 'api-*' ] + branches: + - 'api-*' + - 'update/*' tags-ignore: [ '**' ] env: @@ -22,13 +24,30 @@ jobs: publish: needs: integrationTest runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + project: + - vanilla + - forge + - neoforge + include: + - project: vanilla + gradleProject: SpongeVanilla + - project: forge + gradleProject: SpongeForge + - project: neoforge + gradleProject: SpongeNeo steps: - name: setup + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" id: setup uses: SpongePowered/.github/.github/actions/setup-java-env@master with: runtime_version: 21 + publishing_branch_regex: '' - name: setup / minecraft cache + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" uses: "actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9" # v4.0.2 with: path: | @@ -39,12 +58,14 @@ jobs: ${{ runner.os }}-minecraft-${{ env.CACHE_REV }}- # We don't need to run tests again, so we just publish - name: setup / workspace + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" run: | echo "GIT_COMMIT=${GITHUB_SHA}" >> $GITHUB_ENV echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV echo "BUILD_NUMBER=${GITHUB_RUN_NUMBER}" >> $GITHUB_ENV - name: Publish to Sponge Maven & GitHub Packages - run: ./gradlew -s -Pprojects=vanilla,forge,neoforge :publish :SpongeVanilla:publish :SpongeForge:publish :SpongeNeo:publish + if: "!startsWith(github.ref, 'refs/heads/update/') || matrix.project == 'vanilla'" + run: ./gradlew -s -Pprojects=vanilla,${{ matrix.project }} :${{ matrix.gradleProject }}:publish env: CI_SYSTEM: Github Actions GITHUB_USERNAME: "${{ github.actor }}" diff --git a/.gitignore b/.gitignore index 7d364aaea03..309c753be9f 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist lib out run +run_snap /target *.com *.class diff --git a/SpongeAPI b/SpongeAPI index 9eec8a5e6e3..30a5fb5795e 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit 9eec8a5e6e3f64fc5a373bdb8d468e132261e67d +Subproject commit 30a5fb5795e45a1738830c0a400094c5a71de542 diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertiesGenerator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertiesGenerator.java index 202e77ae676..fbcf5ea6048 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertiesGenerator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertiesGenerator.java @@ -32,6 +32,7 @@ import net.minecraft.core.FrontAndTop; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.CreakingHeartBlock; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerState; import net.minecraft.world.level.block.entity.vault.VaultState; import net.minecraft.world.level.block.state.BlockState; @@ -131,6 +132,7 @@ static PropertyType ofProperty(final Property prop) { vanillaEnumTypeMapping.put(StructureMode.class, BlockStatePropertiesGenerator.inDataTypePkg("StructureMode")); vanillaEnumTypeMapping.put(PistonType.class, BlockStatePropertiesGenerator.inDataTypePkg("PistonType")); vanillaEnumTypeMapping.put(BambooLeaves.class, BlockStatePropertiesGenerator.inDataTypePkg("BambooLeavesType")); + vanillaEnumTypeMapping.put(CreakingHeartBlock.CreakingHeartState.class, BlockStatePropertiesGenerator.inDataTypePkg("CreakingHeart")); vanillaEnumTypeMapping.put(WallSide.class, BlockStatePropertiesGenerator.inDataTypePkg("WallConnectionState")); vanillaEnumTypeMapping.put(RailShape.class, BlockStatePropertiesGenerator.inDataTypePkg("RailDirection")); vanillaEnumTypeMapping.put(AttachFace.class, BlockStatePropertiesGenerator.inDataTypePkg("AttachmentSurface")); diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertyKeysGenerator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertyKeysGenerator.java index d00816a08ce..8e269ac5864 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertyKeysGenerator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/BlockStatePropertyKeysGenerator.java @@ -33,6 +33,7 @@ import com.squareup.javapoet.TypeVariableName; import net.minecraft.core.Direction; import net.minecraft.core.FrontAndTop; +import net.minecraft.world.level.block.CreakingHeartBlock; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerState; import net.minecraft.world.level.block.entity.vault.VaultState; import net.minecraft.world.level.block.state.BlockState; @@ -129,6 +130,7 @@ static BlockStatePropertyKeysGenerator.PropertyType ofProperty(final Property vanillaEnumTypeMapping.put(StructureMode.class, BlockStatePropertyKeysGenerator.inDataTypePkg("StructureMode")); vanillaEnumTypeMapping.put(PistonType.class, BlockStatePropertyKeysGenerator.inDataTypePkg("PistonType")); vanillaEnumTypeMapping.put(BambooLeaves.class, BlockStatePropertyKeysGenerator.inDataTypePkg("BambooLeavesType")); + vanillaEnumTypeMapping.put(CreakingHeartBlock.CreakingHeartState.class, BlockStatePropertyKeysGenerator.inDataTypePkg("CreakingHeart")); vanillaEnumTypeMapping.put(WallSide.class, BlockStatePropertyKeysGenerator.inDataTypePkg("WallConnectionState")); vanillaEnumTypeMapping.put(RailShape.class, BlockStatePropertyKeysGenerator.inDataTypePkg("RailDirection")); vanillaEnumTypeMapping.put(AttachFace.class, BlockStatePropertyKeysGenerator.inDataTypePkg("AttachmentSurface")); diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/EnumEntriesValidator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/EnumEntriesValidator.java index 27618ec8527..78acf6a1f41 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/EnumEntriesValidator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/EnumEntriesValidator.java @@ -136,7 +136,11 @@ public void generate(final Context ctx) { // Sort field entries and add them back to the class processedFields.sort(Comparator.comparing(field -> field.getVariable(0).getNameAsString())); - primaryTypeDeclaration.getMembers().addAll(lastNonFieldIndex, processedFields); + var indextoAddAt = lastNonFieldIndex; + if (indextoAddAt == -1) { + indextoAddAt = 0; + } + primaryTypeDeclaration.getMembers().addAll(indextoAddAt, processedFields); if (!added.isEmpty()) { Logger.info("Added {} entries to {} that will require manual action to implement: {}", added.size(), this.targetClassSimpleName, added); diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java index 2b19277298e..fa239231a98 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java @@ -33,19 +33,19 @@ import net.minecraft.Util; import net.minecraft.advancements.AdvancementType; import net.minecraft.commands.Commands.CommandSelection; +import net.minecraft.core.HolderLookup; import net.minecraft.core.LayeredRegistryAccess; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.Registries; import net.minecraft.resources.RegistryDataLoader; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.Bootstrap; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.RegistryLayer; -import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.*; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.server.packs.resources.CloseableResourceManager; import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; import net.minecraft.world.Difficulty; import net.minecraft.world.damagesource.DamageEffects; import net.minecraft.world.damagesource.DamageScaling; @@ -62,14 +62,14 @@ import net.minecraft.world.entity.animal.horse.Markings; import net.minecraft.world.entity.animal.horse.Variant; import net.minecraft.world.entity.monster.SpellcasterIllager; -import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.Rarity; -import net.minecraft.world.item.Tiers; import net.minecraft.world.item.component.FireworkExplosion; +import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.block.CreakingHeartBlock; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerState; import net.minecraft.world.level.block.state.properties.BambooLeaves; import net.minecraft.world.level.block.state.properties.DripstoneThickness; @@ -91,6 +91,7 @@ import java.util.concurrent.ExecutionException; import java.util.function.BiConsumer; import java.util.stream.Collectors; +import java.util.stream.Stream; /** * A generator that will output source code containing constants used in Minecraft: Java Edition. @@ -161,24 +162,25 @@ private static Pair loadVanill // We don't currently try to load any datapacks here final var packRepository = ServerPacksSource.createVanillaTrustedRepository(); MinecraftServer.configurePackRepository(packRepository, WorldDataConfiguration.DEFAULT, /* safeMode = */ false, true); - final CloseableResourceManager resourceManager = new MultiPackResourceManager(PackType.SERVER_DATA, packRepository.openAllSelected()); + final CloseableResourceManager rm = new MultiPackResourceManager(PackType.SERVER_DATA, packRepository.openAllSelected()); // WorldLoader.load final LayeredRegistryAccess staticRegistries = RegistryLayer.createRegistryAccess(); - final LayeredRegistryAccess withWorldgen = staticRegistries.replaceFrom( - RegistryLayer.WORLDGEN, - RegistryDataLoader.load(resourceManager, staticRegistries.getAccessForLoading(RegistryLayer.WORLDGEN), RegistryDataLoader.WORLDGEN_REGISTRIES) - ); - final LayeredRegistryAccess withDimensions = withWorldgen.replaceFrom( - RegistryLayer.DIMENSIONS, - RegistryDataLoader.load(resourceManager, staticRegistries.getAccessForLoading(RegistryLayer.DIMENSIONS), RegistryDataLoader.DIMENSION_REGISTRIES) - ); - + List> pendingTags = TagLoader.loadTagsForExistingRegistries(rm, staticRegistries.getLayer(RegistryLayer.STATIC)); + final var wga = staticRegistries.getAccessForLoading(RegistryLayer.WORLDGEN); + List> tl = TagLoader.buildUpdatedLookups(wga, pendingTags); + RegistryAccess.Frozen wgr = RegistryDataLoader.load(rm, tl, RegistryDataLoader.WORLDGEN_REGISTRIES); + List> cl = Stream.concat(tl.stream(), wgr.listRegistries()).toList(); + final LayeredRegistryAccess withWorldGen = staticRegistries.replaceFrom(RegistryLayer.WORLDGEN, wgr); + RegistryAccess.Frozen da = RegistryDataLoader.load(rm, cl, RegistryDataLoader.DIMENSION_REGISTRIES); + final LayeredRegistryAccess withDimensions = withWorldGen.replaceFrom(RegistryLayer.DIMENSIONS, da); + TagLoader.loadTagsForExistingRegistries(rm, withDimensions.getLayer(RegistryLayer.WORLDGEN)); final RegistryAccess.Frozen compositeRegistries = withDimensions.getAccessForLoading(RegistryLayer.RELOADABLE); final var resourcesFuture = ReloadableServerResources.loadResources( - resourceManager, + rm, withDimensions, + pendingTags, packRepository.getRequestedFeatureFlags(), CommandSelection.ALL, 2, // functionPermissionLevel @@ -186,10 +188,10 @@ private static Pair loadVanill Runnable::run // applyExecutor ).whenComplete((result, ex) -> { if (ex != null) { - resourceManager.close(); + rm.close(); } }).thenApply(resources -> { - resources.updateRegistryTags(); + resources.updateStaticRegistryTags(); return resources; }); @@ -216,7 +218,7 @@ private static List generators(final Context context) { // Prepare a set of generators // We are starting out by just generating Vanilla registry-backed catalogs // Enum-backed (automatically-named) catalogs can be added later as necessary - return List.of( + return List.of( new MapEntriesValidator<>( "world.gamerule", "GameRules", @@ -246,18 +248,11 @@ private static List generators(final Context context) { "sponge" ), new EnumEntriesValidator<>( - "data.type", - "BoatTypes", - Boat.Type.class, - "getSerializedName", - "sponge" - ), - new RegistryEntriesGenerator<>( - "data.type", - "ArmorMaterials", - "ARMOR_MATERIAL", - context.relativeClass("data.type", "ArmorMaterial"), - Registries.ARMOR_MATERIAL + "data.type", + "CreakingHearts", + CreakingHeartBlock.CreakingHeartState.class, + "getSerializedName", + "sponge" ), new RegistryEntriesGenerator<>( "map.decoration", @@ -318,14 +313,14 @@ private static List generators(final Context context) { new EnumEntriesValidator<>( "data.type", "MooshroomTypes", - MushroomCow.MushroomType.class, + MushroomCow.Variant.class, "getSerializedName", "sponge" ), new EnumEntriesValidator<>( "data.type", "FoxTypes", - Fox.Type.class, + Fox.Variant.class, "getSerializedName", "sponge" ), @@ -378,6 +373,13 @@ private static List generators(final Context context) { "getSerializedName", "sponge" ), + new EnumEntriesValidator<>( + "world.explosion", + "ExplosionBlockInteractions", + Explosion.BlockInteraction.class, + "name", + "sponge" + ), new RegistryEntriesGenerator<>( "data.type", "ArtTypes", @@ -789,13 +791,14 @@ private static List generators(final Context context) { "getSerializedName", "sponge" ), - new EnumEntriesValidator<>( - "data.type", - "ItemTiers", - Tiers.class, - "name", - "sponge" - ), +// TODO - Figure out this change since ToolMaterials aren't registered, nor an enum anymore. - Snapshot 24w34a +// new EnumEntriesValidator<>( +// "data.type", +// "ItemTiers", +// ToolMaterial.class, +// "name", +// "sponge" +// ), new EnumEntriesValidator<>( "entity.display", "BillboardTypes", diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesGenerator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesGenerator.java index 769325db35d..753594ccfeb 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesGenerator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesGenerator.java @@ -24,10 +24,13 @@ */ package org.spongepowered.vanilla.generator; +import com.squareup.javapoet.AnnotationSpec; +import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; @@ -35,6 +38,7 @@ import net.minecraft.world.flag.FeatureElement; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.flag.FeatureFlags; +import org.jetbrains.annotations.ApiStatus; import java.io.IOException; import java.util.Comparator; @@ -121,9 +125,9 @@ public void generate(final Context ctx) throws IOException { clazz.addAnnotation(Types.suppressWarnings("unused")); final RegistryScope scopeType; - Registry registry = (Registry) BuiltInRegistries.REGISTRY.get(this.registry.location()); + Registry registry = (Registry) BuiltInRegistries.REGISTRY.get(this.registry.location()).map(Holder.Reference::value).orElse(null); if (registry == null) { - registry = ctx.registries().registry(this.registry).orElse(null); + registry = ctx.registries().lookup(this.registry).orElse(null); if (registry == null) { throw new IllegalArgumentException("Unknown registry " + this.registry); } @@ -160,12 +164,12 @@ private FieldSpec makeField(final String ownType, final TypeName fieldType, fina if (!featureFlagSet.isSubsetOf(FeatureFlags.VANILLA_SET)) { final var flags = FeatureFlags.REGISTRY.toNames(featureFlagSet).stream().map(rl -> rl.getNamespace().equals("minecraft") ? rl.getPath() : rl.getNamespace() + ":" + rl.getPath()).toArray(); // Use this when new feature flags are introduced -// if (featureFlagSet.contains(FeatureFlags.UPDATE_1_20)) { -// var annotation = AnnotationSpec.builder(ClassName.get("org.spongepowered.api.util.annotation", "Experimental")) -// .addMember("value", "$S", flags).build(); -// builder.addAnnotation(annotation).build(); -// builder.addAnnotation(ApiStatus.Experimental.class).build(); -// } + if (featureFlagSet.contains(FeatureFlags.WINTER_DROP)) { + var annotation = AnnotationSpec.builder(ClassName.get("org.spongepowered.api.util.annotation", "Experimental")) + .addMember("value", "$S", flags).build(); + builder.addAnnotation(annotation).build(); + builder.addAnnotation(ApiStatus.Experimental.class).build(); + } } diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesValidator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesValidator.java index 5fed02e72aa..8adf3830a3f 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesValidator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/RegistryEntriesValidator.java @@ -96,12 +96,10 @@ public void generate(final Context ctx) { final var primaryTypeDeclaration = compilationUnit.getPrimaryType() .orElseThrow(() -> new IllegalStateException("Could not find primary type for registry type " + this.targetClassSimpleName)); - Registry registry = ctx.registries().registry(this.registry).orElse(null); + Registry registry = ctx.registries().lookup(this.registry).orElse(null); if (registry == null) { - registry = (Registry) BuiltInRegistries.REGISTRY.get(this.registry.location()); - if (registry == null) { - throw new IllegalArgumentException("Unknown registry " + this.registry); - } + registry = (Registry) BuiltInRegistries.REGISTRY.get(this.registry.location()) + .orElseThrow(() -> new IllegalArgumentException("Unknown registry " + this.registry)); } primaryTypeDeclaration.setJavadocComment(new Javadoc(JavadocDescription.parseText(Generator.GENERATED_FILE_JAVADOCS))); @@ -130,7 +128,7 @@ public void generate(final Context ctx) { final Set allKeys = new HashSet<>(registry.keySet()); allKeys.addAll(this.extraEntries); for (final ResourceLocation key : allKeys) { - if (!this.filter.test(registry.get(key))) { + if (!this.filter.test(registry.getValue(key))) { continue; } diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/TagGenerator.java b/generator/src/main/java/org/spongepowered/vanilla/generator/TagGenerator.java index 87955f21e49..68d9d95b4ed 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/TagGenerator.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/TagGenerator.java @@ -29,6 +29,7 @@ import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; +import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; @@ -93,8 +94,9 @@ public void generate(final Context ctx) throws IOException { ).build(); - ctx.registries().registryOrThrow(this.taggedRegistry).getTagNames() - .map(TagKey::location) + ctx.registries().lookupOrThrow(this.taggedRegistry).getTags() + .>map(HolderSet.Named::key) + .map(TagKey::location) .sorted(Comparator.naturalOrder()) .map(v -> this.makeField(this.targetClassSimpleName, fieldType, factoryMethod, v)) .forEachOrdered(clazz::addField); diff --git a/gradle.properties b/gradle.properties index db84133290e..650da30265c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json superClassChanges=common.superclasschange -minecraftVersion=1.21.1 +minecraftVersion=1.21.2-rc2 recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 1d25c3d10e6..131ded4b65f 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -225,6 +225,11 @@ + + + + + @@ -245,6 +250,11 @@ + + + + + @@ -255,6 +265,11 @@ + + + + + @@ -280,6 +295,11 @@ + + + + + @@ -295,6 +315,14 @@ + + + + + + + + @@ -314,6 +342,14 @@ + + + + + + + + @@ -322,6 +358,14 @@ + + + + + + + + @@ -446,6 +490,14 @@ + + + + + + + + @@ -1130,6 +1182,14 @@ + + + + + + + + @@ -1152,6 +1212,14 @@ + + + + + + + + @@ -1209,6 +1277,23 @@ + + + + + + + + + + + + + + + + + @@ -1231,6 +1316,22 @@ + + + + + + + + + + + + + + + + @@ -1250,6 +1351,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -3373,6 +3506,22 @@ + + + + + + + + + + + + + + + + diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/EntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/EntityAccessor.java index 538bfb02607..8a3171168a1 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/EntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/EntityAccessor.java @@ -87,8 +87,6 @@ public interface EntityAccessor { @Invoker("getFireImmuneTicks") int invoker$getFireImmuneTicks(); - @Invoker("getPermissionLevel") int invoker$getPermissionLevel(); - @Invoker("unsetRemoved") void invoker$unsetRemoved(); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/ai/targeting/TargetingConditionsAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/ai/targeting/TargetingConditionsAccessor.java index e975fb1e014..7301d5c9c4c 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/ai/targeting/TargetingConditionsAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/ai/targeting/TargetingConditionsAccessor.java @@ -24,16 +24,14 @@ */ package org.spongepowered.common.accessor.world.entity.ai.targeting; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -import java.util.function.Predicate; @Mixin(TargetingConditions.class) public interface TargetingConditionsAccessor { - @Accessor("selector") Predicate accessor$selector(); + @Accessor("selector") TargetingConditions.Selector accessor$selector(); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/SheepAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/SheepAccessor.java index f876ba9205c..9bbc8d32fb5 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/SheepAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/SheepAccessor.java @@ -26,14 +26,10 @@ import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.world.entity.animal.Sheep; -import net.minecraft.world.item.DyeColor; -import net.minecraft.world.level.ItemLike; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.common.UntransformedAccessorError; -import java.util.Map; - @Mixin(Sheep.class) public interface SheepAccessor { @@ -41,8 +37,4 @@ public interface SheepAccessor { throw new UntransformedAccessorError(); } - @Accessor("ITEM_BY_DYE") static Map accessor$ITEM_BY_DYE() { - throw new UntransformedAccessorError(); - } - } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ArmorStandAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ArmorStandAccessor.java index f7793b8ce90..a44016eaaa9 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ArmorStandAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ArmorStandAccessor.java @@ -50,10 +50,6 @@ public interface ArmorStandAccessor { @Invoker("setSmall") void invoker$setSmall(final boolean small); - @Invoker("setShowArms") void invoker$setShowArms(final boolean showArms); - - @Invoker("setNoBasePlate") void invoker$setNoBasePlate(final boolean noBasePlate); - @Invoker("setMarker") void invoker$setMarker(final boolean marker); @Invoker("hasPhysics") boolean invoker$hasPhysics(); diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ItemFrameAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ItemFrameAccessor.java index f633ffb127a..d6cb0289c74 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ItemFrameAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/decoration/ItemFrameAccessor.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.accessor.world.entity.decoration; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.decoration.ItemFrame; import org.spongepowered.asm.mixin.Mixin; @@ -32,6 +33,6 @@ @Mixin(ItemFrame.class) public interface ItemFrameAccessor { - @Invoker("dropItem") void invoker$dropItem(final Entity entity, final boolean drop); + @Invoker("dropItem") void invoker$dropItem(final ServerLevel level, final Entity entity, final boolean drop); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/block/entity/JukeboxMixin_ItemStackLike.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/monster/creaking/CreakingTransientAccessor.java similarity index 75% rename from src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/block/entity/JukeboxMixin_ItemStackLike.java rename to src/accessors/java/org/spongepowered/common/accessor/world/entity/monster/creaking/CreakingTransientAccessor.java index 23bbd9d7eca..a3a80e54d1a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/block/entity/JukeboxMixin_ItemStackLike.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/monster/creaking/CreakingTransientAccessor.java @@ -22,16 +22,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.itemstacklike.block.entity; +package org.spongepowered.common.accessor.world.entity.monster.creaking; -import org.spongepowered.api.block.entity.Jukebox; -import org.spongepowered.api.item.inventory.ItemStack; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.monster.creaking.CreakingTransient; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(value = Jukebox.class, remap = false) -public interface JukeboxMixin_ItemStackLike { +@Mixin(CreakingTransient.class) +public interface CreakingTransientAccessor { + + @Accessor("homePos") BlockPos accessor$homePos(); + + @Accessor("homePos") void accessor$setHomePos(BlockPos pos); - default void insert(ItemStack disc) { - ((Jukebox) this).insert(disc); - } } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/player/PlayerAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/player/PlayerAccessor.java index 9a12ace2ef0..1a91a66d7ad 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/player/PlayerAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/player/PlayerAccessor.java @@ -29,6 +29,7 @@ import net.minecraft.world.entity.player.Player; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedAccessorError; @Mixin(Player.class) @@ -57,6 +58,7 @@ public interface PlayerAccessor { @Accessor("DATA_SHOULDER_RIGHT") static EntityDataAccessor accessor$DATA_SHOULDER_RIGHT() { throw new UntransformedAccessorError(); } + @Invoker("getPermissionLevel") int invoker$getPermissionLevel(); @Accessor("sleepCounter") void accessor$sleepCounter(final int sleepCounter); diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/BoatAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/AbstractBoatAccessor.java similarity index 88% rename from src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/BoatAccessor.java rename to src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/AbstractBoatAccessor.java index 13c13fa8e5f..36f4de0698a 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/BoatAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/vehicle/AbstractBoatAccessor.java @@ -24,13 +24,13 @@ */ package org.spongepowered.common.accessor.world.entity.vehicle; -import net.minecraft.world.entity.vehicle.Boat; +import net.minecraft.world.entity.vehicle.AbstractBoat; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(Boat.class) -public interface BoatAccessor { +@Mixin(AbstractBoat.class) +public interface AbstractBoatAccessor { - @Accessor("status") Boat.Status accessor$status(); + @Accessor("status") AbstractBoat.Status accessor$status(); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/food/FoodDataAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/food/FoodDataAccessor.java index d01f6e281c3..4d7892de036 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/food/FoodDataAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/food/FoodDataAccessor.java @@ -37,4 +37,6 @@ public interface FoodDataAccessor { @Accessor("exhaustionLevel") void accessor$exhaustionLevel(final float exhaustionLevel); + @Accessor("exhaustionLevel") float accessor$exhaustionLevel(); + } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/inventory/CraftingMenuAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/inventory/AbstractCraftingMenuAccessor.java similarity index 91% rename from src/accessors/java/org/spongepowered/common/accessor/world/inventory/CraftingMenuAccessor.java rename to src/accessors/java/org/spongepowered/common/accessor/world/inventory/AbstractCraftingMenuAccessor.java index dce50afccdf..354247b48d5 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/inventory/CraftingMenuAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/inventory/AbstractCraftingMenuAccessor.java @@ -24,13 +24,13 @@ */ package org.spongepowered.common.accessor.world.inventory; +import net.minecraft.world.inventory.AbstractCraftingMenu; import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.CraftingMenu; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(CraftingMenu.class) -public interface CraftingMenuAccessor { +@Mixin(AbstractCraftingMenu.class) +public interface AbstractCraftingMenuAccessor { @Accessor("craftSlots") CraftingContainer accessor$craftSlots(); diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/RecipeMapAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/RecipeMapAccessor.java new file mode 100644 index 00000000000..f7ed452f1de --- /dev/null +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/RecipeMapAccessor.java @@ -0,0 +1,41 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.accessor.world.item.crafting; + +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeMap; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.Map; + +@Mixin(RecipeMap.class) +public interface RecipeMapAccessor { + + @Accessor("byKey") + Map>, RecipeHolder> accessor$byKey(); +} diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/MushroomCow_MushroomTypeAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/ShapelessRecipeAccessor.java similarity index 79% rename from src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/MushroomCow_MushroomTypeAccessor.java rename to src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/ShapelessRecipeAccessor.java index 0bcfb85fffd..b0343958027 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/MushroomCow_MushroomTypeAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/crafting/ShapelessRecipeAccessor.java @@ -22,15 +22,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.accessor.world.entity.animal; +package org.spongepowered.common.accessor.world.item.crafting; -import net.minecraft.world.entity.animal.MushroomCow; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.ShapelessRecipe; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(MushroomCow.MushroomType.class) -public interface MushroomCow_MushroomTypeAccessor { - - @Accessor("type") String accessor$type(); +import java.util.List; +@Mixin(ShapelessRecipe.class) +public interface ShapelessRecipeAccessor { + @Accessor("ingredients") List accessor$ingredients(); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/NaturalSpawner_SpawnStateAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/NaturalSpawner_SpawnStateAccessor.java index 7aa47292f9d..9b12a614bd1 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/NaturalSpawner_SpawnStateAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/NaturalSpawner_SpawnStateAccessor.java @@ -24,22 +24,15 @@ */ package org.spongepowered.common.accessor.world.level; -import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.NaturalSpawner; -import net.minecraft.world.level.chunk.ChunkAccess; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(NaturalSpawner.SpawnState.class) public interface NaturalSpawner_SpawnStateAccessor { - @Invoker("canSpawn") boolean invoker$canSpawn(EntityType p_234969_1_, BlockPos p_234969_2_, ChunkAccess p_234969_3_); - @Invoker("afterSpawn") void invoker$afterSpawn(Mob p_234970_1_, ChunkAccess p_234970_2_); - - @Invoker("canSpawnForCategory") boolean invoker$canSpawnForCategory(MobCategory category, final ChunkPos pos); + @Invoker("canSpawnForCategoryLocal") boolean invoker$canSpawnForCategoryLocal(MobCategory category, final ChunkPos pos); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/ExplosionAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/ServerExplosionAccessor.java similarity index 85% rename from src/accessors/java/org/spongepowered/common/accessor/world/level/ExplosionAccessor.java rename to src/accessors/java/org/spongepowered/common/accessor/world/level/ServerExplosionAccessor.java index 6f3e7f1f733..68550648525 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/ExplosionAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/ServerExplosionAccessor.java @@ -24,23 +24,18 @@ */ package org.spongepowered.common.accessor.world.level; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Explosion; -import net.minecraft.world.level.Level; +import net.minecraft.world.level.ServerExplosion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(Explosion.class) -public interface ExplosionAccessor { +@Mixin(ServerExplosion.class) +public interface ServerExplosionAccessor { @Accessor("blockInteraction") Explosion.BlockInteraction accessor$blockInteraction(); - @Accessor("level") Level accessor$level(); - - @Accessor("x") double accessor$x(); - - @Accessor("y") double accessor$y(); - - @Accessor("z") double accessor$z(); + @Accessor("level") ServerLevel accessor$level(); @Accessor("radius") float accessor$radius(); diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/biome/BiomeAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/biome/BiomeAccessor.java index 80b9378b46b..bfaea3db80f 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/biome/BiomeAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/biome/BiomeAccessor.java @@ -24,13 +24,17 @@ */ package org.spongepowered.common.accessor.world.level.biome; +import net.minecraft.core.BlockPos; import net.minecraft.world.level.biome.Biome; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(Biome.class) public interface BiomeAccessor { @Accessor("climateSettings") Biome.ClimateSettings accessor$climateSettings(); + @Invoker("getTemperature") float shadow$getTemperature(BlockPos pos, int seaLevel); + } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/trialspawner/TrialSpawnerAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/trialspawner/TrialSpawnerAccessor.java index 2b34f3284d2..82c6ff5adfa 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/trialspawner/TrialSpawnerAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/trialspawner/TrialSpawnerAccessor.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.accessor.world.level.block.entity.trialspawner; +import net.minecraft.core.Holder; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawner; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerConfig; import org.spongepowered.asm.mixin.Mixin; @@ -33,6 +34,6 @@ @Mixin(TrialSpawner.class) public interface TrialSpawnerAccessor { - @Mutable @Accessor("normalConfig") void accessor$normalConfig(TrialSpawnerConfig normalConfig); - @Mutable @Accessor("ominousConfig") void accessor$ominousConfig(TrialSpawnerConfig ominousConfig); + @Mutable @Accessor("normalConfig") void accessor$normalConfig(Holder normalConfig); + @Mutable @Accessor("ominousConfig") void accessor$ominousConfig(Holder ominousConfig); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/StateHolderAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/StateHolderAccessor.java index 8e1e4e05408..7e1331995f3 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/StateHolderAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/StateHolderAccessor.java @@ -29,12 +29,12 @@ import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedInvokerError; -import java.util.Collection; +import java.util.List; @Mixin(StateHolder.class) public interface StateHolderAccessor { - @Invoker("findNextInCollection") static T invoker$findNextInCollection(final Collection collection, final T element) { + @Invoker("findNextInCollection") static T invoker$findNextInCollection(final List $$0, final T $$1) { throw new UntransformedInvokerError(); } } diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 8d5b7b9e8a6..12b09545f3f 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -1,214 +1,215 @@ { - "required": true, - "parent": "mixins.sponge.parent.json", - "package": "org.spongepowered.common.accessor", - "client": [ - "client.KeyMappingAccessor", - "client.multiplayer.ClientLevelAccessor", - "world.level.entity.TransientEntitySectionManagerAccessor" - ], - "mixins": [ - "ChatFormattingAccessor", - "advancements.CriteriaTriggersAccessor", - "advancements.critereon.MinMaxBounds_DoublesAccessor", - "advancements.critereon.MinMaxBounds_IntsAccessor", - "commands.CommandSourceStackAccessor", - "commands.arguments.DimensionArgumentAccessor", - "commands.arguments.OperationArgumentAccessor", - "commands.arguments.selector.EntitySelectorParserAccessor", - "commands.arguments.selector.options.EntitySelectorOptions_OptionAccessor", - "commands.arguments.selector.options.EntitySelectorOptionsAccessor", - "core.MappedRegistryAccessor", - "entity.passive.AbstractChestedHorseEntityAccessor", - "network.ConnectionAccessor", - "network.chat.HoverEvent_ItemStackInfoAccessor", - "network.chat.StyleAccessor", - "network.protocol.game.ClientboundAddEntityPacketAccessor", - "network.protocol.game.ClientboundPlayerInfoUpdatePacketAccessor", - "network.protocol.game.ServerboundInteractPacket_InteractionActionAccessor", - "network.protocol.game.ServerboundInteractPacket_InteractionAtLocationActionAccessor", - "network.protocol.game.ServerboundInteractPacketAccessor", - "network.protocol.game.ServerboundMovePlayerPacketAccessor", - "network.protocol.game.ServerboundMoveVehiclePacketAccessor", - "network.protocol.handshake.ClientIntentionPacketAccessor", - "resources.ResourceKeyAccessor", - "server.MinecraftServerAccessor", - "server.level.ChunkMap_TrackedEntityAccessor", - "server.level.ChunkMapAccessor", - "server.level.ServerChunkCacheAccessor", - "server.level.ServerLevelAccessor", - "server.level.ServerPlayer_ContainerListenerAccessor", - "server.level.ServerPlayerAccessor", - "server.level.ServerPlayerGameModeAccessor", - "server.level.TicketAccessor", - "server.level.TicketTypeAccessor", - "server.network.ServerCommonPacketListenerImplAccessor", - "server.network.ServerGamePacketListenerImplAccessor", - "server.network.ServerLoginPacketListenerImplAccessor", - "server.players.GameProfileCache_GameProfileInfoAccessor", - "server.players.IpBanListAccessor", - "server.players.PlayerListAccessor", - "server.players.StoredUserEntryAccessor", - "server.players.StoredUserListAccessor", - "server.rcon.thread.RconClientAccessor", - "sounds.SoundEventAccessor", - "stats.StatsCounterAccessor", - "util.datafix.schemas.V100Accessor", - "world.CompoundContainerAccessor", - "world.damagesource.CombatTrackerAccessor", - "world.entity.AgableMobAccessor", - "world.entity.AreaEffectCloudAccessor", - "world.entity.Display_BlockDisplayAccessor", - "world.entity.Display_ItemDisplayAccessor", - "world.entity.Display_TextDisplayAccessor", - "world.entity.DisplayAccessor", - "world.entity.EntityAccessor", - "world.entity.EntityTypeAccessor", - "world.entity.ExperienceOrbAccessor", - "world.entity.LightningBoltAccessor", - "world.entity.LivingEntityAccessor", - "world.entity.MobAccessor", - "world.entity.PortalProcessorAccessor", - "world.entity.ai.targeting.TargetingConditionsAccessor", - "world.entity.animal.AnimalAccessor", - "world.entity.animal.CatAccessor", - "world.entity.animal.FoxAccessor", - "world.entity.animal.MushroomCow_MushroomTypeAccessor", - "world.entity.animal.OcelotAccessor", - "world.entity.animal.PandaAccessor", - "world.entity.animal.PigAccessor", - "world.entity.animal.PufferfishAccessor", - "world.entity.animal.SheepAccessor", - "world.entity.animal.TropicalFishAccessor", - "world.entity.animal.TurtleAccessor", - "world.entity.animal.WolfAccessor", - "world.entity.animal.horse.HorseAccessor", - "world.entity.animal.horse.LlamaAccessor", - "world.entity.animal.horse.TraderLlamaAccessor", - "world.entity.boss.enderdragon.phases.EnderDragonPhaseAccessor", - "world.entity.boss.wither.WitherBossAccessor", - "world.entity.decoration.ArmorStandAccessor", - "world.entity.decoration.HangingEntityAccessor", - "world.entity.decoration.ItemFrameAccessor", - "world.entity.item.FallingBlockEntityAccessor", - "world.entity.item.PrimedTntAccessor", - "world.entity.monster.BlazeAccessor", - "world.entity.monster.CreeperAccessor", - "world.entity.monster.EnderManAccessor", - "world.entity.monster.EndermiteAccessor", - "world.entity.monster.EvokerAccessor", - "world.entity.monster.GuardianAccessor", - "world.entity.monster.PatrollingMonsterAccessor", - "world.entity.monster.PhantomAccessor", - "world.entity.monster.PillagerAccessor", - "world.entity.monster.RavagerAccessor", - "world.entity.monster.SlimeAccessor", - "world.entity.monster.SpellcasterIllagerAccessor", - "world.entity.monster.VexAccessor", - "world.entity.monster.VindicatorAccessor", - "world.entity.monster.ZombifiedPiglinAccessor", - "world.entity.npc.AbstractVillagerAccessor", - "world.entity.player.AbilitiesAccessor", - "world.entity.player.PlayerAccessor", - "world.entity.projectile.ArrowAccessor", - "world.entity.projectile.EyeOfEnderAccessor", - "world.entity.projectile.FireworkRocketEntityAccessor", - "world.entity.projectile.FishingHookAccessor", - "world.entity.projectile.ProjectileAccessor", - "world.entity.projectile.ShulkerBulletAccessor", - "world.entity.raid.RaidAccessor", - "world.entity.raid.RaiderAccessor", - "world.entity.raid.RaidsAccessor", - "world.entity.vehicle.BoatAccessor", - "world.entity.vehicle.MinecartFurnaceAccessor", - "world.food.FoodDataAccessor", - "world.inventory.AbstractContainerMenuAccessor", - "world.inventory.AbstractFurnaceMenuAccessor", - "world.inventory.BeaconMenuAccessor", - "world.inventory.BrewingStandMenuAccessor", - "world.inventory.CraftingMenuAccessor", - "world.inventory.DispenserMenuAccessor", - "world.inventory.HopperMenuAccessor", - "world.inventory.HorseInventoryMenuAccessor", - "world.inventory.ItemCombinerMenuAccessor", - "world.inventory.MerchantMenuAccessor", - "world.inventory.ResultSlotAccessor", - "world.inventory.SlotAccessor", - "world.inventory.SmithingMenuAccessor", - "world.inventory.StonecutterMenuAccessor", - "world.item.AdventureModePredicateAccessor", - "world.item.ItemCooldowns_CooldownInstanceAccessor", - "world.item.component.CustomDataAccessor", - "world.item.enchantment.ItemEnchantmentsAccessor", - "world.item.trading.MerchantOfferAccessor", - "world.level.BaseCommandBlockAccessor", - "world.level.BaseSpawnerAccessor", - "world.level.ExplosionAccessor", - "world.level.GameRules_ValueAccessor", - "world.level.GameRulesAccessor", - "world.level.LevelAccessor", - "world.level.LevelSettingsAccessor", - "world.level.NaturalSpawner_SpawnStateAccessor", - "world.level.NaturalSpawnerAccessor", - "world.level.biome.Biome_ClimateSettingsAccessor", - "world.level.biome.BiomeAccessor", - "world.level.biome.MobSpawnSettingsAccessor", - "world.level.biome.MultiNoiseBiomeSourceAccessor", - "world.level.biome.OverworldBiomeBuilderAccessor", - "world.level.biome.TheEndBiomeSourceAccessor", - "world.level.block.AbstractSkullBlockAccessor", - "world.level.block.BaseFireBlockAccessor", - "world.level.block.BedBlockAccessor", - "world.level.block.CrafterBlockAccessor", - "world.level.block.CropBlockAccessor", - "world.level.block.DispenserBlockAccessor", - "world.level.block.EnderChestBlockAccessor", - "world.level.block.StemBlockAccessor", - "world.level.block.entity.AbstractFurnaceBlockEntityAccessor", - "world.level.block.entity.BaseContainerBlockEntityAccessor", - "world.level.block.entity.BeaconBlockEntityAccessor", - "world.level.block.entity.BlockEntityAccessor", - "world.level.block.entity.BrewingStandBlockEntityAccessor", - "world.level.block.entity.ConduitBlockEntityAccessor", - "world.level.block.entity.CrafterBlockEntityAccessor", - "world.level.block.entity.EnchantingTableBlockEntityAccessor", - "world.level.block.entity.HopperBlockEntityAccessor", - "world.level.block.entity.LecternBlockEntity_Accessor", - "world.level.block.entity.SkullBlockEntityAccessor", - "world.level.block.entity.SpawnerBlockEntityAccessor", - "world.level.block.entity.StructureBlockEntityAccessor", - "world.level.block.entity.TheEndGatewayBlockEntityAccessor", - "world.level.block.entity.trialspawner.TrialSpawnerAccessor", - "world.level.block.entity.trialspawner.TrialSpawnerDataAccessor", - "world.level.block.piston.PistonBaseBlockAccessor", - "world.level.block.state.BlockBehaviour_PropertiesAccessor", - "world.level.block.state.BlockBehaviourAccessor", - "world.level.block.state.StateHolderAccessor", - "world.level.border.WorldBorder_SettingsAccessor", - "world.level.border.WorldBorderAccessor", - "world.level.chunk.ChunkAccessAccessor", - "world.level.chunk.LevelChunk$BoundTickingBlockEntityAccessor", - "world.level.chunk.LevelChunk$RebindableTickingBlockEntityWrapperAccessor", - "world.level.chunk.LevelChunkAccessor", - "world.level.chunk.storage.ChunkStorageAccessor", - "world.level.chunk.storage.IOWorker$PendingStoreAccessor", - "world.level.chunk.storage.RegionFileAccessor", - "world.level.chunk.storage.SimpleRegionStorageAccessor", - "world.level.dimension.DimensionTypeAccessor", - "world.level.dimension.end.EndDragonFightAccessor", - "world.level.entity.EntityTickListAccessor", - "world.level.entity.PersistentEntitySectionManagerAccessor", - "world.level.levelgen.NoiseSettingsAccessor", - "world.level.levelgen.flat.FlatLevelGeneratorSettingsAccessor", - "world.level.levelgen.structure.pools.StructureTemplatePoolAccessor", - "world.level.saveddata.maps.MapItemSavedDataAccessor", - "world.level.storage.LevelStorageSource_LevelStorageAccessAccessor", - "world.level.storage.PlayerDataStorageAccessor", - "world.phys.AABBAccessor", - "world.scores.PlayerTeamAccessor", - "world.scores.ScoreboardAccessor" - ], - "server": [ - "server.dedicated.DedicatedServerAccessor" + "required": true, + "parent": "mixins.sponge.parent.json", + "package": "org.spongepowered.common.accessor", + "client": [ + "client.KeyMappingAccessor", + "client.multiplayer.ClientLevelAccessor", + "world.level.entity.TransientEntitySectionManagerAccessor" + ], + "mixins": [ + "ChatFormattingAccessor", + "advancements.CriteriaTriggersAccessor", + "advancements.critereon.MinMaxBounds_DoublesAccessor", + "advancements.critereon.MinMaxBounds_IntsAccessor", + "commands.CommandSourceStackAccessor", + "commands.arguments.DimensionArgumentAccessor", + "commands.arguments.OperationArgumentAccessor", + "commands.arguments.selector.EntitySelectorParserAccessor", + "commands.arguments.selector.options.EntitySelectorOptions_OptionAccessor", + "commands.arguments.selector.options.EntitySelectorOptionsAccessor", + "core.MappedRegistryAccessor", + "entity.passive.AbstractChestedHorseEntityAccessor", + "network.ConnectionAccessor", + "network.chat.HoverEvent_ItemStackInfoAccessor", + "network.chat.StyleAccessor", + "network.protocol.game.ClientboundAddEntityPacketAccessor", + "network.protocol.game.ClientboundPlayerInfoUpdatePacketAccessor", + "network.protocol.game.ServerboundInteractPacket_InteractionActionAccessor", + "network.protocol.game.ServerboundInteractPacket_InteractionAtLocationActionAccessor", + "network.protocol.game.ServerboundInteractPacketAccessor", + "network.protocol.game.ServerboundMovePlayerPacketAccessor", + "network.protocol.game.ServerboundMoveVehiclePacketAccessor", + "network.protocol.handshake.ClientIntentionPacketAccessor", + "resources.ResourceKeyAccessor", + "server.MinecraftServerAccessor", + "server.level.ChunkMap_TrackedEntityAccessor", + "server.level.ChunkMapAccessor", + "server.level.ServerChunkCacheAccessor", + "server.level.ServerLevelAccessor", + "server.level.ServerPlayer_ContainerListenerAccessor", + "server.level.ServerPlayerAccessor", + "server.level.ServerPlayerGameModeAccessor", + "server.level.TicketAccessor", + "server.level.TicketTypeAccessor", + "server.network.ServerCommonPacketListenerImplAccessor", + "server.network.ServerGamePacketListenerImplAccessor", + "server.network.ServerLoginPacketListenerImplAccessor", + "server.players.GameProfileCache_GameProfileInfoAccessor", + "server.players.IpBanListAccessor", + "server.players.PlayerListAccessor", + "server.players.StoredUserEntryAccessor", + "server.players.StoredUserListAccessor", + "server.rcon.thread.RconClientAccessor", + "sounds.SoundEventAccessor", + "stats.StatsCounterAccessor", + "util.datafix.schemas.V100Accessor", + "world.CompoundContainerAccessor", + "world.damagesource.CombatTrackerAccessor", + "world.entity.AgableMobAccessor", + "world.entity.AreaEffectCloudAccessor", + "world.entity.Display_BlockDisplayAccessor", + "world.entity.Display_ItemDisplayAccessor", + "world.entity.Display_TextDisplayAccessor", + "world.entity.DisplayAccessor", + "world.entity.EntityAccessor", + "world.entity.EntityTypeAccessor", + "world.entity.ExperienceOrbAccessor", + "world.entity.LightningBoltAccessor", + "world.entity.LivingEntityAccessor", + "world.entity.MobAccessor", + "world.entity.PortalProcessorAccessor", + "world.entity.ai.targeting.TargetingConditionsAccessor", + "world.entity.animal.AnimalAccessor", + "world.entity.animal.CatAccessor", + "world.entity.animal.FoxAccessor", + "world.entity.animal.OcelotAccessor", + "world.entity.animal.PandaAccessor", + "world.entity.animal.PigAccessor", + "world.entity.animal.PufferfishAccessor", + "world.entity.animal.SheepAccessor", + "world.entity.animal.TropicalFishAccessor", + "world.entity.animal.TurtleAccessor", + "world.entity.animal.WolfAccessor", + "world.entity.animal.horse.HorseAccessor", + "world.entity.animal.horse.LlamaAccessor", + "world.entity.animal.horse.TraderLlamaAccessor", + "world.entity.boss.enderdragon.phases.EnderDragonPhaseAccessor", + "world.entity.boss.wither.WitherBossAccessor", + "world.entity.decoration.ArmorStandAccessor", + "world.entity.decoration.HangingEntityAccessor", + "world.entity.decoration.ItemFrameAccessor", + "world.entity.item.FallingBlockEntityAccessor", + "world.entity.item.PrimedTntAccessor", + "world.entity.monster.BlazeAccessor", + "world.entity.monster.CreeperAccessor", + "world.entity.monster.EnderManAccessor", + "world.entity.monster.EndermiteAccessor", + "world.entity.monster.EvokerAccessor", + "world.entity.monster.GuardianAccessor", + "world.entity.monster.PatrollingMonsterAccessor", + "world.entity.monster.PhantomAccessor", + "world.entity.monster.PillagerAccessor", + "world.entity.monster.RavagerAccessor", + "world.entity.monster.SlimeAccessor", + "world.entity.monster.SpellcasterIllagerAccessor", + "world.entity.monster.VexAccessor", + "world.entity.monster.VindicatorAccessor", + "world.entity.monster.ZombifiedPiglinAccessor", + "world.entity.monster.creaking.CreakingTransientAccessor", + "world.entity.npc.AbstractVillagerAccessor", + "world.entity.player.AbilitiesAccessor", + "world.entity.player.PlayerAccessor", + "world.entity.projectile.ArrowAccessor", + "world.entity.projectile.EyeOfEnderAccessor", + "world.entity.projectile.FireworkRocketEntityAccessor", + "world.entity.projectile.FishingHookAccessor", + "world.entity.projectile.ProjectileAccessor", + "world.entity.projectile.ShulkerBulletAccessor", + "world.entity.raid.RaidAccessor", + "world.entity.raid.RaiderAccessor", + "world.entity.raid.RaidsAccessor", + "world.entity.vehicle.AbstractBoatAccessor", + "world.entity.vehicle.MinecartFurnaceAccessor", + "world.food.FoodDataAccessor", + "world.inventory.AbstractContainerMenuAccessor", + "world.inventory.AbstractCraftingMenuAccessor", + "world.inventory.AbstractFurnaceMenuAccessor", + "world.inventory.BeaconMenuAccessor", + "world.inventory.BrewingStandMenuAccessor", + "world.inventory.DispenserMenuAccessor", + "world.inventory.HopperMenuAccessor", + "world.inventory.HorseInventoryMenuAccessor", + "world.inventory.ItemCombinerMenuAccessor", + "world.inventory.MerchantMenuAccessor", + "world.inventory.ResultSlotAccessor", + "world.inventory.SlotAccessor", + "world.inventory.SmithingMenuAccessor", + "world.item.AdventureModePredicateAccessor", + "world.item.ItemCooldowns_CooldownInstanceAccessor", + "world.item.component.CustomDataAccessor", + "world.item.crafting.RecipeMapAccessor", + "world.item.crafting.ShapelessRecipeAccessor", + "world.item.enchantment.ItemEnchantmentsAccessor", + "world.item.trading.MerchantOfferAccessor", + "world.level.BaseCommandBlockAccessor", + "world.level.BaseSpawnerAccessor", + "world.level.GameRules_ValueAccessor", + "world.level.GameRulesAccessor", + "world.level.LevelAccessor", + "world.level.LevelSettingsAccessor", + "world.level.NaturalSpawner_SpawnStateAccessor", + "world.level.NaturalSpawnerAccessor", + "world.level.ServerExplosionAccessor", + "world.level.biome.Biome_ClimateSettingsAccessor", + "world.level.biome.BiomeAccessor", + "world.level.biome.MobSpawnSettingsAccessor", + "world.level.biome.MultiNoiseBiomeSourceAccessor", + "world.level.biome.OverworldBiomeBuilderAccessor", + "world.level.biome.TheEndBiomeSourceAccessor", + "world.level.block.AbstractSkullBlockAccessor", + "world.level.block.BaseFireBlockAccessor", + "world.level.block.BedBlockAccessor", + "world.level.block.CrafterBlockAccessor", + "world.level.block.CropBlockAccessor", + "world.level.block.DispenserBlockAccessor", + "world.level.block.EnderChestBlockAccessor", + "world.level.block.StemBlockAccessor", + "world.level.block.entity.AbstractFurnaceBlockEntityAccessor", + "world.level.block.entity.BaseContainerBlockEntityAccessor", + "world.level.block.entity.BeaconBlockEntityAccessor", + "world.level.block.entity.BlockEntityAccessor", + "world.level.block.entity.BrewingStandBlockEntityAccessor", + "world.level.block.entity.ConduitBlockEntityAccessor", + "world.level.block.entity.CrafterBlockEntityAccessor", + "world.level.block.entity.EnchantingTableBlockEntityAccessor", + "world.level.block.entity.HopperBlockEntityAccessor", + "world.level.block.entity.LecternBlockEntity_Accessor", + "world.level.block.entity.SkullBlockEntityAccessor", + "world.level.block.entity.SpawnerBlockEntityAccessor", + "world.level.block.entity.StructureBlockEntityAccessor", + "world.level.block.entity.TheEndGatewayBlockEntityAccessor", + "world.level.block.entity.trialspawner.TrialSpawnerAccessor", + "world.level.block.entity.trialspawner.TrialSpawnerDataAccessor", + "world.level.block.piston.PistonBaseBlockAccessor", + "world.level.block.state.BlockBehaviour_PropertiesAccessor", + "world.level.block.state.BlockBehaviourAccessor", + "world.level.block.state.StateHolderAccessor", + "world.level.border.WorldBorder_SettingsAccessor", + "world.level.border.WorldBorderAccessor", + "world.level.chunk.ChunkAccessAccessor", + "world.level.chunk.LevelChunk$BoundTickingBlockEntityAccessor", + "world.level.chunk.LevelChunk$RebindableTickingBlockEntityWrapperAccessor", + "world.level.chunk.LevelChunkAccessor", + "world.level.chunk.storage.ChunkStorageAccessor", + "world.level.chunk.storage.IOWorker$PendingStoreAccessor", + "world.level.chunk.storage.RegionFileAccessor", + "world.level.chunk.storage.SimpleRegionStorageAccessor", + "world.level.dimension.DimensionTypeAccessor", + "world.level.dimension.end.EndDragonFightAccessor", + "world.level.entity.EntityTickListAccessor", + "world.level.entity.PersistentEntitySectionManagerAccessor", + "world.level.levelgen.NoiseSettingsAccessor", + "world.level.levelgen.flat.FlatLevelGeneratorSettingsAccessor", + "world.level.levelgen.structure.pools.StructureTemplatePoolAccessor", + "world.level.saveddata.maps.MapItemSavedDataAccessor", + "world.level.storage.LevelStorageSource_LevelStorageAccessAccessor", + "world.level.storage.PlayerDataStorageAccessor", + "world.phys.AABBAccessor", + "world.scores.PlayerTeamAccessor", + "world.scores.ScoreboardAccessor" + ], + "server": [ + "server.dedicated.DedicatedServerAccessor" ] } diff --git a/src/main/java/org/spongepowered/common/SpongeCommon.java b/src/main/java/org/spongepowered/common/SpongeCommon.java index 2789b1c36bc..7238fe6e054 100644 --- a/src/main/java/org/spongepowered/common/SpongeCommon.java +++ b/src/main/java/org/spongepowered/common/SpongeCommon.java @@ -101,7 +101,7 @@ public static RegistryAccess.Frozen vanillaRegistryAccess() { } public static Registry vanillaRegistry(ResourceKey> key) { - return SpongeCommon.vanillaRegistryAccess().registryOrThrow(key); + return SpongeCommon.vanillaRegistryAccess().lookupOrThrow(key); } public static ServerScheduler serverScheduler() { diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java index ef073687f61..afd8a7a3f8c 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java @@ -61,6 +61,7 @@ import net.kyori.adventure.util.Codec; import net.kyori.adventure.util.TriState; import net.minecraft.ChatFormatting; +import net.minecraft.commands.arguments.selector.SelectorPattern; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; @@ -264,7 +265,7 @@ private static MutableComponent asVanillaMutable0(final Component component) { return net.minecraft.network.chat.Component.score($this.name(), $this.objective()); } if (component instanceof final SelectorComponent $this) { - return net.minecraft.network.chat.Component.selector($this.pattern(), SpongeAdventure.asVanillaOpt($this.separator())); + return net.minecraft.network.chat.Component.selector(SelectorPattern.parse($this.pattern()).getOrThrow(), SpongeAdventure.asVanillaOpt($this.separator())); } if (component instanceof NBTComponent) { if (component instanceof final BlockNBTComponent $this) { @@ -320,11 +321,11 @@ public static Component asAdventure(final net.minecraft.network.chat.Component c return Component.keybind().keybind(kc.getName()); } if (contents instanceof final ScoreContents sc) { - return Component.score().name(sc.getName()).objective(sc.getObjective()); + return Component.score().name(sc.name().mapLeft(SelectorPattern::pattern).orThrow()).objective(sc.objective()); } if (contents instanceof final SelectorContents sc) { - return Component.selector().pattern(sc.getPattern()) - .separator(SpongeAdventure.asAdventure(sc.getSeparator())); + return Component.selector().pattern(sc.selector().pattern()) + .separator(SpongeAdventure.asAdventure(sc.separator())); } if (contents instanceof final NbtContents nc) { NBTComponentBuilder nbtBuilder; @@ -547,7 +548,7 @@ public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEv return new net.minecraft.network.chat.HoverEvent( Action.SHOW_ENTITY, new net.minecraft.network.chat.HoverEvent.EntityTooltipInfo( - entityTypeRegistry.get(SpongeAdventure.asVanilla(value.type())), + entityTypeRegistry.getValue(SpongeAdventure.asVanilla(value.type())), value.id(), SpongeAdventure.asVanillaNullable(value.name()) ) @@ -558,7 +559,7 @@ public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEv return new net.minecraft.network.chat.HoverEvent( Action.SHOW_ITEM, HoverEvent_ItemStackInfoAccessor.invoker$new( - Holder.direct(itemRegistry.get(SpongeAdventure.asVanilla(value.item()))), + Holder.direct(itemRegistry.getValue(SpongeAdventure.asVanilla(value.item()))), value.count(), SpongeAdventure.asVanilla(value.dataComponents()) ) @@ -730,12 +731,11 @@ public static DataComponentPatch asVanilla(final Map co return DataComponentPatch.EMPTY; } final DataComponentPatch.Builder builder = DataComponentPatch.builder(); - componentMap.forEach((key, value) -> { - final DataComponentType type = BuiltInRegistries.DATA_COMPONENT_TYPE.get(SpongeAdventure.asVanilla(key)); - if (type != null && value instanceof SpongeDataComponentValue dcv) { - builder.set(type, dcv.value.orElse(null)); + componentMap.forEach((key, value) -> BuiltInRegistries.DATA_COMPONENT_TYPE.getOptional(SpongeAdventure.asVanilla(key)).ifPresent(type -> { + if (value instanceof SpongeDataComponentValue dcv) { + builder.set((DataComponentType) type, dcv.value.orElse(null)); } - }); + })); return builder.build(); } diff --git a/src/main/java/org/spongepowered/common/block/BlockStateSerializerDeserializer.java b/src/main/java/org/spongepowered/common/block/BlockStateSerializerDeserializer.java index 90903c5dad1..8e7d9204630 100644 --- a/src/main/java/org/spongepowered/common/block/BlockStateSerializerDeserializer.java +++ b/src/main/java/org/spongepowered/common/block/BlockStateSerializerDeserializer.java @@ -43,7 +43,7 @@ public static String serialize(final BlockState state) { public static Optional deserialize(final String string) { final String state = Objects.requireNonNull(string, "Id cannot be null!").toLowerCase(Locale.ENGLISH); try { - final BlockStateParser.BlockResult result = BlockStateParser.parseForBlock(SpongeCommon.vanillaRegistry(Registries.BLOCK).asLookup(), state, true); + final BlockStateParser.BlockResult result = BlockStateParser.parseForBlock(SpongeCommon.vanillaRegistry(Registries.BLOCK), state, true); return Optional.of((BlockState) result.blockState()); } catch (final CommandSyntaxException e) { return Optional.empty(); diff --git a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java index 0b0c48012fe..5fd5dee4143 100644 --- a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java +++ b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java @@ -275,7 +275,7 @@ public Optional createArchetype() { return Optional.of(SpongeBlockEntityArchetypeBuilder.pooled() .state(this.state()) - .blockEntity((BlockEntityType) SpongeCommon.vanillaRegistry(Registries.BLOCK_ENTITY_TYPE).get(ResourceLocation.tryParse(blockEntityId))) + .blockEntity((BlockEntityType) SpongeCommon.vanillaRegistry(Registries.BLOCK_ENTITY_TYPE).getOptional(ResourceLocation.tryParse(blockEntityId)).orElse(null)) .blockEntityData(NBTTranslator.INSTANCE.translate(compound)) .build()); } diff --git a/src/main/java/org/spongepowered/common/bridge/block/BlockBridge.java b/src/main/java/org/spongepowered/common/bridge/block/BlockBridge.java index 28100f5f238..abe2566bcf0 100644 --- a/src/main/java/org/spongepowered/common/bridge/block/BlockBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/block/BlockBridge.java @@ -27,14 +27,8 @@ import net.minecraft.world.level.block.Block; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.data.DataManipulator.Immutable; -import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; -import org.spongepowered.api.event.CauseStackManager; -import org.spongepowered.common.bridge.server.level.ServerLevelBridge; -import java.util.List; -import java.util.Optional; -import java.util.function.BiConsumer; /** * A quasi interface to mix into every possible {@link Block} such that their @@ -52,66 +46,8 @@ * they already know the type they need to focus on.

*/ public interface BlockBridge { - - /** - * Gets all the {@link Immutable}s for the provided - * {@link BlockState}. - * - * @param blockState The block state being passed in - * @return The list of immutable manipulators - */ - List bridge$getManipulators(BlockState blockState); - - /** - * A simple check whether the class is supported by the block or not. - * - * @param immutable The immutable class - * @return True if the data possibly represented by an instance of the class is supported - */ - boolean bridge$supports(Class immutable); - - /** - * Instead of delegating to a block processor, we can delegate to the block - * to retrieve the correct {@link BlockState} if supported. Considering - * block processors would require to know of the blocks themselves, it is - * easier to use the block to understand what data is being offered, - * and the current block state being used. Since all of the data is already - * relatively kept in the block state instance, it is therefor very well - * possible to cycle according to the block instance. - * - * @param blockState The block state to use as a base - * @param key The key to the data - * @param value The value - * @param The type of value, for type checking - * @return The blockstate with the new value, if available and compatible - */ - Optional bridge$getStateWithValue(BlockState blockState, Key> key, E value); - - /** - * Again, another delegate method directly to the block, usually not all - * required, but it does help if the block does support the manipulator - * in the first place. Considering that most manipulators are single - * data typed, it is discernible for the block to easily check what - * data is being offered and therefor validate whether the data is - * allowed for the specific block state. The block state passed in - * is not changed, but rather used as a blueprint so to speak due to - * the various pre-set data that the block state may contain, such as - * red stone power levels, plant types, etc. etc. etc. - * - * @param blockState The block state to base off of - * @param manipulator The manipulator being offered - * @return The block state with the requested data, if available - */ - Optional bridge$getStateWithData(BlockState blockState, Immutable manipulator); - // Normal API methods - boolean bridge$isVanilla(); - - boolean bridge$hasCollideLogic(); - - boolean bridge$hasCollideWithStateLogic(); - /** * Used only for Forge's dummy air block that is acting as a surrogate block for missing * mod blocks. Usually when a block is simply marked for replacement when a mod is re-introduced. @@ -122,8 +58,4 @@ public interface BlockBridge { return false; } - default BiConsumer bridge$getTickFrameModifier() { - return (frame, world) -> { - }; - } } diff --git a/src/main/java/org/spongepowered/common/bridge/explosives/ExplosiveBridge.java b/src/main/java/org/spongepowered/common/bridge/explosives/ExplosiveBridge.java index c53341e74bb..34aac1a2009 100644 --- a/src/main/java/org/spongepowered/common/bridge/explosives/ExplosiveBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/explosives/ExplosiveBridge.java @@ -31,7 +31,10 @@ public interface ExplosiveBridge { - Optional bridge$getExplosionRadius(); + Optional bridge$getExplosionRadius(); + + void bridge$setExplosionRadius(@Nullable Float radius); + + default void bridge$cancelExplosion() {} - void bridge$setExplosionRadius(@Nullable Integer radius); } diff --git a/src/main/java/org/spongepowered/common/bridge/server/level/ServerLevelBridge.java b/src/main/java/org/spongepowered/common/bridge/server/level/ServerLevelBridge.java index 62ae2c00c00..58a2fd55563 100644 --- a/src/main/java/org/spongepowered/common/bridge/server/level/ServerLevelBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/server/level/ServerLevelBridge.java @@ -24,8 +24,10 @@ */ package org.spongepowered.common.bridge.server.level; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; import net.minecraft.server.bossevents.CustomBossEvents; import net.minecraft.server.level.progress.ChunkProgressListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.world.explosion.Explosion; @@ -42,6 +44,9 @@ public interface ServerLevelBridge { void bridge$triggerExplosion(Explosion explosion); + void bridge$handleExplosionPacket(final ServerGamePacketListenerImpl instance, Explosion apiExplosion, + final ClientboundExplodePacket packet); + void bridge$setManualSave(boolean state); BlockSnapshot bridge$createSnapshot(int x, int y, int z); diff --git a/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java b/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java index ac2c724af1a..89fa19c7ce8 100644 --- a/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java @@ -92,8 +92,18 @@ public interface ServerPlayerBridge extends ServerPlayerEntityHealthScaleBridge default void bridge$sendChangeDimension(final Holder dimensionType, final ResourceKey key, final long hashedSeed, final GameType gameType, final GameType previousGameType, final boolean isDebug, final boolean isFlat, final byte dataToKeepMask) { - ((ServerPlayer) this).connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo(dimensionType, key, hashedSeed, gameType, previousGameType, isDebug, - isFlat, ((ServerPlayer) this).getLastDeathLocation(), ((ServerPlayer) this).getPortalCooldown()), dataToKeepMask)); + ((ServerPlayer) this).connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo( + dimensionType, + key, + hashedSeed, + gameType, + previousGameType, + isDebug, + isFlat, + ((ServerPlayer) this).getLastDeathLocation(), + ((ServerPlayer) this).getPortalCooldown(), + ((ServerPlayer) this).serverLevel().getSeaLevel() + ), dataToKeepMask)); } boolean bridge$kick(final Component message); diff --git a/src/main/java/org/spongepowered/common/bridge/world/TrackedWorldBridge.java b/src/main/java/org/spongepowered/common/bridge/world/TrackedWorldBridge.java index fbc9060b94c..740a8eed68c 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/TrackedWorldBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/TrackedWorldBridge.java @@ -34,17 +34,14 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.world.BlockChangeFlag; -import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.server.level.ServerLevelBridge; import org.spongepowered.common.bridge.world.level.LevelBridge; import org.spongepowered.common.bridge.world.level.block.state.BlockStateBridge; -import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; import org.spongepowered.common.event.tracking.context.transaction.pipeline.WorldPipeline; import java.util.Optional; -import java.util.function.Function; /** * A specialized {@link LevelBridge} or {@link ServerLevelBridge} @@ -55,9 +52,6 @@ public interface TrackedWorldBridge { boolean bridge$forceSpawnEntity(Entity entity); - net.minecraft.world.level.Explosion tracker$triggerInternalExplosion(Explosion explosion, Function> contextCreator); - Optional bridge$startBlockChange(BlockPos pos, BlockState state, int rawFlags); /** diff --git a/src/main/java/org/spongepowered/common/bridge/world/entity/EntityBridge.java b/src/main/java/org/spongepowered/common/bridge/world/entity/EntityBridge.java index a8b41003978..038bd18db65 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/entity/EntityBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/entity/EntityBridge.java @@ -26,7 +26,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.event.cause.entity.DismountType; import org.spongepowered.api.event.entity.ChangeEntityWorldEvent; @@ -70,7 +70,7 @@ public interface EntityBridge { boolean bridge$dismountRidingEntity(DismountType type); - Entity bridge$changeDimension(DimensionTransition transition); + Entity bridge$changeDimension(TeleportTransition transition); ChangeEntityWorldEvent.Reposition bridge$fireRepositionEvent(org.spongepowered.api.world.server.ServerWorld originalDestinationWorld, org.spongepowered.api.world.server.ServerWorld targetWorld, diff --git a/src/main/java/org/spongepowered/common/bridge/world/entity/boss/enderdragon/EndCrystalBridge.java b/src/main/java/org/spongepowered/common/bridge/world/entity/boss/enderdragon/EndCrystalBridge.java index 931c19522f0..9f58f8701eb 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/entity/boss/enderdragon/EndCrystalBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/entity/boss/enderdragon/EndCrystalBridge.java @@ -25,13 +25,10 @@ package org.spongepowered.common.bridge.world.entity.boss.enderdragon; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; public interface EndCrystalBridge { - @Nullable Explosion bridge$throwExplosionEventAndExplode(Level world, @Nullable Entity nil, double x, - double y, double z, boolean smoking, @Nullable DamageSource source); + void bridge$wrappedExplode(double x, + double y, double z, @Nullable DamageSource source, final DamageSource causeSource); } diff --git a/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/LargeFireballBridge.java b/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/LargeFireballBridge.java index 95d1f438633..b2282c0c20d 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/LargeFireballBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/LargeFireballBridge.java @@ -24,13 +24,9 @@ */ package org.spongepowered.common.bridge.world.entity.projectile; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion; import net.minecraft.world.level.Level; -import org.checkerframework.checker.nullness.qual.Nullable; public interface LargeFireballBridge { - @Nullable Explosion bridge$throwExplosionEventAndExplode(Level worldObj, @Nullable Entity nil, - double x, double y, double z, float strength, boolean flaming, Level.ExplosionInteraction mode); + void bridge$wrappedExplode(double x, double y, double z, float strength, boolean flaming, Level.ExplosionInteraction mode); } diff --git a/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/WitherSkullBridge.java b/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/WitherSkullBridge.java index 8e87c427a77..78301e468b1 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/WitherSkullBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/entity/projectile/WitherSkullBridge.java @@ -24,13 +24,10 @@ */ package org.spongepowered.common.bridge.world.entity.projectile; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion; import net.minecraft.world.level.Level; -import org.checkerframework.checker.nullness.qual.Nullable; public interface WitherSkullBridge { - @Nullable Explosion bridge$throwExplosionEventAndExplosde(net.minecraft.world.level.Level worldObj, Entity self, double x, + void bridge$wrappedExplode(double x, double y, double z, float strength, boolean flaming, Level.ExplosionInteraction mode); } diff --git a/src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/BoatBridge.java b/src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/AbstractBoatBridge.java similarity index 97% rename from src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/BoatBridge.java rename to src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/AbstractBoatBridge.java index d39353485f8..a7318718bab 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/BoatBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/entity/vehicle/AbstractBoatBridge.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.bridge.world.entity.vehicle; -public interface BoatBridge { +public interface AbstractBoatBridge { double bridge$getMaxSpeed(); diff --git a/src/main/java/org/spongepowered/common/bridge/world/level/block/entity/CampfireBlockEntityBridge.java b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/CookingRecipeBridge.java similarity index 80% rename from src/main/java/org/spongepowered/common/bridge/world/level/block/entity/CampfireBlockEntityBridge.java rename to src/main/java/org/spongepowered/common/bridge/world/item/crafting/CookingRecipeBridge.java index 39c1a505ab7..61229a08638 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/level/block/entity/CampfireBlockEntityBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/CookingRecipeBridge.java @@ -22,12 +22,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.bridge.world.level.block.entity; +package org.spongepowered.common.bridge.world.item.crafting; -import net.minecraft.world.item.crafting.CampfireCookingRecipe; -import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.Ingredient; -public interface CampfireBlockEntityBridge { +public interface CookingRecipeBridge extends RecipeResultBridge { + + Ingredient bridge$ingredient(); - void bridge$placeRecipe(RecipeHolder recipe); } diff --git a/src/main/java/org/spongepowered/common/bridge/world/item/crafting/SmithingRecipeBridge.java b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/SmithingRecipeBridge.java index 1d63566f01b..43b0a377e4e 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/item/crafting/SmithingRecipeBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/SmithingRecipeBridge.java @@ -26,10 +26,12 @@ import net.minecraft.world.item.crafting.Ingredient; +import java.util.Optional; + public interface SmithingRecipeBridge extends RecipeResultBridge { - Ingredient bridge$template(); - Ingredient bridge$base(); - Ingredient bridge$addition(); + Optional bridge$template(); + Optional bridge$base(); + Optional bridge$addition(); } diff --git a/src/main/java/org/spongepowered/common/bridge/world/level/ExplosionBridge.java b/src/main/java/org/spongepowered/common/bridge/world/level/ExplosionBridge.java index 68f67ee2665..a83c1171fa5 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/level/ExplosionBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/level/ExplosionBridge.java @@ -24,11 +24,10 @@ */ package org.spongepowered.common.bridge.world.level; + public interface ExplosionBridge { - boolean bridge$getShouldDamageBlocks(); - void bridge$setShouldBreakBlocks(boolean shouldBreakBlocks); boolean bridge$getShouldPlaySmoke(); diff --git a/src/main/java/org/spongepowered/common/bridge/world/level/block/TrackableBlockBridge.java b/src/main/java/org/spongepowered/common/bridge/world/level/block/TrackableBlockBridge.java index 8c8a4418464..719aaf81726 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/level/block/TrackableBlockBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/level/block/TrackableBlockBridge.java @@ -26,8 +26,6 @@ public interface TrackableBlockBridge { - boolean bridge$overridesNeighborNotificationLogic(); - boolean bridge$hasEntityInsideLogic(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/SidedSlotMixin_ItemStackLike.java b/src/main/java/org/spongepowered/common/bridge/world/level/chunk/storage/SerializableChunkDataBridge.java similarity index 60% rename from src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/SidedSlotMixin_ItemStackLike.java rename to src/main/java/org/spongepowered/common/bridge/world/level/chunk/storage/SerializableChunkDataBridge.java index 4a411b0d7f8..815da991b19 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/SidedSlotMixin_ItemStackLike.java +++ b/src/main/java/org/spongepowered/common/bridge/world/level/chunk/storage/SerializableChunkDataBridge.java @@ -22,25 +22,29 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.slot; +package org.spongepowered.common.bridge.world.level.chunk.storage; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.slot.SidedSlot; -import org.spongepowered.api.util.Direction; -import org.spongepowered.asm.mixin.Mixin; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.api.world.SerializationBehavior; -@Mixin(value = SidedSlot.class, remap = false) -public interface SidedSlotMixin_ItemStackLike { +public interface SerializableChunkDataBridge { - default boolean canAccept(ItemStack stack, Direction from) { - return ((SidedSlot) this).canAccept(stack, from); - } + void bridge$setTrackerData(LevelChunk chunkAccess); - default boolean offer(ItemStack stack, Direction from) { - return ((SidedSlot) this).offer(stack, from); - } + void bridge$writeTrackerData(CompoundTag level); - default boolean canGet(ItemStack stack, Direction from) { - return ((SidedSlot) this).canGet(stack, from); - } + void bridge$parseTrackerData(CompoundTag tag); + + void bridge$writeDataHolderData(CompoundTag level); + + void bridge$setDataHolderData(LevelChunk levelChunk); + + void bridge$parseDataHolderData(CompoundTag tag); + + void bridge$readTrackerDataFrom(LevelChunk levelChunk); + + void bridge$readDataHolderDataFrom(LevelChunk levelChunk); + + void bridge$setSerializationBehavior(SerializationBehavior serializationBehavior); } diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java index cbd0fae9ef6..cdbbb388550 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.data.provider.block.entity; -import net.minecraft.world.LockCode; import org.spongepowered.api.data.Keys; import org.spongepowered.common.accessor.world.level.block.entity.BaseContainerBlockEntityAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; @@ -38,9 +37,9 @@ private LockableData() { public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(BaseContainerBlockEntityAccessor.class) - .create(Keys.LOCK_TOKEN) - .get(h -> h.accessor$lockKey().key()) - .set((h, v) -> h.accessor$lockKey(v.isEmpty() ? LockCode.NO_LOCK : new LockCode(v))); + .create(Keys.LOCK_TOKEN);// TODO - Implement Item Predicates +// .get(h -> h.accessor$lockKey().key()) +// .set((h, v) -> h.accessor$lockKey(v.isEmpty() ? LockCode.NO_LOCK : new LockCode(v))); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/TrialSpawnerDataProvider.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/TrialSpawnerDataProvider.java index 2c8195bd761..1c383d849e4 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/TrialSpawnerDataProvider.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/TrialSpawnerDataProvider.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.data.provider.block.entity; +import net.minecraft.core.Holder; import net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerConfig; import org.spongepowered.api.data.Keys; @@ -68,8 +69,8 @@ public static void register(final DataProviderRegistrator registrator) { final var newOminiousConfig = new TrialSpawnerConfig(v.intValue(), ominousConfig.totalMobs(), ominousConfig.simultaneousMobs(), ominousConfig.totalMobsAddedPerPlayer(), ominousConfig.simultaneousMobsAddedPerPlayer(), ominousConfig.ticksBetweenSpawn(), ominousConfig.spawnPotentialsDefinition(), ominousConfig.lootTablesToEject(), ominousConfig.itemsToDropWhenOminous()); final var accessor = (TrialSpawnerAccessor) (Object) h.getTrialSpawner(); - accessor.accessor$normalConfig(newNormalConfig); - accessor.accessor$ominousConfig(newOminiousConfig); + accessor.accessor$normalConfig(Holder.direct(newNormalConfig)); + accessor.accessor$ominousConfig(Holder.direct(newOminiousConfig)); }) // TODO totalMobs // TODO simultaneousMobs @@ -91,8 +92,8 @@ public static void register(final DataProviderRegistrator registrator) { final var newOminiousConfig = new TrialSpawnerConfig(ominousConfig.spawnRange(), ominousConfig.totalMobs(), ominousConfig.simultaneousMobs(), ominousConfig.totalMobsAddedPerPlayer(), ominousConfig.simultaneousMobsAddedPerPlayer(), ominousConfig.ticksBetweenSpawn(), spawnPotentials, ominousConfig.lootTablesToEject(), ominousConfig.itemsToDropWhenOminous()); final var accessor = (TrialSpawnerAccessor) (Object) h.getTrialSpawner(); - accessor.accessor$normalConfig(newNormalConfig); - accessor.accessor$ominousConfig(newOminiousConfig); + accessor.accessor$normalConfig(Holder.direct(newNormalConfig)); + accessor.accessor$ominousConfig(Holder.direct(newOminiousConfig)); }); // TODO lootTablesToEject // TODO itemsToDropWhenOminous diff --git a/src/main/java/org/spongepowered/common/data/provider/block/location/ServerLocationData.java b/src/main/java/org/spongepowered/common/data/provider/block/location/ServerLocationData.java index ec9e9c2ae55..2f3915a3afd 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/location/ServerLocationData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/location/ServerLocationData.java @@ -34,6 +34,7 @@ import org.spongepowered.api.block.entity.NameableBlockEntity; import org.spongepowered.api.data.Keys; import org.spongepowered.api.world.server.ServerLocation; +import org.spongepowered.common.accessor.world.level.biome.BiomeAccessor; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.CustomNameableBridge; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; @@ -66,7 +67,7 @@ public static void register(final DataProviderRegistrator registrator) { final Level world = (Level) h.world(); final BlockPos pos = VecHelper.toBlockPos(h); final Biome biome = world.getBiome(pos).unwrap().right().get(); - return (double) biome.getTemperature(pos); + return (double) ((BiomeAccessor) (Object) biome).shadow$getTemperature(pos, world.getSeaLevel()); }) .create(Keys.SKY_LIGHT) .get(h -> { @@ -79,7 +80,7 @@ public static void register(final DataProviderRegistrator registrator) { final BlockState block = (BlockState) h.block(); final Level world = (Level) h.world(); final BlockPos pos = VecHelper.toBlockPos(h.position()); - return block.isSolidRender(world, pos); + return block.isSolidRender(); }) .create(Keys.IS_INDIRECTLY_POWERED) .get(h -> { diff --git a/src/main/java/org/spongepowered/common/data/provider/block/state/WoolData.java b/src/main/java/org/spongepowered/common/data/provider/block/state/WoolData.java index b0f500b4ea4..a1965961b20 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/state/WoolData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/state/WoolData.java @@ -24,10 +24,10 @@ */ package org.spongepowered.common.data.provider.block.state; +import net.minecraft.data.loot.packs.LootData; import net.minecraft.world.level.block.Block; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.DyeColor; -import org.spongepowered.common.accessor.world.entity.animal.SheepAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.DyeColorUtil; @@ -42,7 +42,7 @@ public static void register(final DataProviderRegistrator registrator) { .asImmutable(Block.class) .create(Keys.DYE_COLOR) .get(h -> (DyeColor) (Object) DyeColorUtil.COLOR_BY_WOOL.get(h)) - .supports(h -> SheepAccessor.accessor$ITEM_BY_DYE().containsValue(h)); + .supports(LootData.WOOL_ITEM_BY_DYE::containsValue); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java index a62aab53c6a..95ec7d9b635 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java @@ -50,7 +50,7 @@ public static void register(final DataProviderRegistrator registrator) { .get(h -> Color.ofRgb(((AreaEffectCloudAccessor) h).accessor$potionContents().getColor())) .set((h, v) -> { var contents = ((AreaEffectCloudAccessor) h).accessor$potionContents(); - h.setPotionContents(new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects())); + h.setPotionContents(new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects(), contents.customName())); }) .create(Keys.DURATION) .get(x -> new SpongeTicks(x.getDuration())) @@ -97,7 +97,7 @@ public static void register(final DataProviderRegistrator registrator) { .get(h -> PotionEffectUtil.copyAsPotionEffects(Streams.stream(h.accessor$potionContents().getAllEffects()).toList())) .set((h, v) -> { final PotionContents contents = h.accessor$potionContents(); - ((AreaEffectCloud) h).setPotionContents(new PotionContents(contents.potion(), contents.customColor(), PotionEffectUtil.copyAsEffectInstances(v))); + ((AreaEffectCloud) h).setPotionContents(new PotionContents(contents.potion(), contents.customColor(), PotionEffectUtil.copyAsEffectInstances(v), contents.customName())); }) .create(Keys.REAPPLICATION_DELAY) .get(h -> new SpongeTicks(h.accessor$reapplicationDelay())) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ArmorStandData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ArmorStandData.java index 2398a2d8aa3..03356948e4d 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ArmorStandData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ArmorStandData.java @@ -78,11 +78,11 @@ public static void register(final DataProviderRegistrator registrator) { .get(h -> VecHelper.toVector3d(h.getBodyPose())) .set((h, v) -> h.setBodyPose(VecHelper.toRotation(v))) .create(Keys.HAS_ARMS) - .get(ArmorStand::isShowArms) - .set((h, v) -> ((ArmorStandAccessor) h).invoker$setShowArms(v)) + .get(ArmorStand::showArms) + .set(ArmorStand::setShowArms) .create(Keys.HAS_BASE_PLATE) - .get(h -> !h.isNoBasePlate()) - .set((h, v) -> ((ArmorStandAccessor) h).invoker$setNoBasePlate(!v)) + .get(h -> !h.showBasePlate()) + .set((h, v) -> h.setNoBasePlate(!v)) .create(Keys.HAS_MARKER) .get(ArmorStand::isMarker) .set((h, v) -> { diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java index b2f6a9a0769..d10b56dbd69 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java @@ -56,7 +56,7 @@ public static void register(final DataProviderRegistrator registrator) { .set((h, v) -> { final PotionContents previousContents = ((ArrowAccessor) h).invoker$getPotionContents(); final List list = v.stream().map(effect -> ArrowData.clone((MobEffectInstance) effect)).toList(); - ((ArrowAccessor) h).invoker$setPotionContents(new PotionContents(previousContents.potion(), previousContents.customColor(), list)); + ((ArrowAccessor) h).invoker$setPotionContents(new PotionContents(previousContents.potion(), previousContents.customColor(), list, previousContents.customName())); }); } // @formatter:on diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/BoatData.java b/src/main/java/org/spongepowered/common/data/provider/entity/BoatData.java index 8fd0878b0fb..f5146dd7d27 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/BoatData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/BoatData.java @@ -24,13 +24,13 @@ */ package org.spongepowered.common.data.provider.entity; +import net.minecraft.world.entity.vehicle.AbstractBoat; import net.minecraft.world.entity.vehicle.Boat; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.persistence.DataContentUpdater; -import org.spongepowered.api.data.type.BoatType; -import org.spongepowered.common.accessor.world.entity.vehicle.BoatAccessor; -import org.spongepowered.common.bridge.world.entity.vehicle.BoatBridge; +import org.spongepowered.common.accessor.world.entity.vehicle.AbstractBoatAccessor; +import org.spongepowered.common.bridge.world.entity.vehicle.AbstractBoatBridge; import org.spongepowered.common.data.ByteToBooleanContentUpdater; import org.spongepowered.common.data.SpongeDataManager; import org.spongepowered.common.data.provider.DataProviderRegistrator; @@ -46,32 +46,29 @@ private BoatData() { // @formatter:off public static void register(final DataProviderRegistrator registrator) { registrator - .asMutable(Boat.class) - .create(Keys.BOAT_TYPE) - .get(h -> ((BoatType) (Object) h.getVariant())) - .set((h, v) -> h.setVariant((Boat.Type) (Object) v)) - .asMutable(BoatAccessor.class) + .asMutable(AbstractBoat.class) + .asMutable(AbstractBoatAccessor.class) .create(Keys.IS_IN_WATER) .get(h -> h.accessor$status() == Boat.Status.IN_WATER) - .asMutable(BoatBridge.class) + .asMutable(AbstractBoatBridge.class) .create(Keys.CAN_MOVE_ON_LAND) - .get(BoatBridge::bridge$getMoveOnLand) - .set(BoatBridge::bridge$setMoveOnLand) - .asMutable(BoatBridge.class) + .get(AbstractBoatBridge::bridge$getMoveOnLand) + .set(AbstractBoatBridge::bridge$setMoveOnLand) + .asMutable(AbstractBoatBridge.class) .create(Keys.OCCUPIED_DECELERATION) - .get(BoatBridge::bridge$getOccupiedDecelerationSpeed) - .set(BoatBridge::bridge$setOccupiedDecelerationSpeed) - .asMutable(BoatBridge.class) + .get(AbstractBoatBridge::bridge$getOccupiedDecelerationSpeed) + .set(AbstractBoatBridge::bridge$setOccupiedDecelerationSpeed) + .asMutable(AbstractBoatBridge.class) .create(Keys.MAX_SPEED) - .get(BoatBridge::bridge$getMaxSpeed) - .set(BoatBridge::bridge$setMaxSpeed) - .asMutable(BoatBridge.class) + .get(AbstractBoatBridge::bridge$getMaxSpeed) + .set(AbstractBoatBridge::bridge$setMaxSpeed) + .asMutable(AbstractBoatBridge.class) .create(Keys.UNOCCUPIED_DECELERATION) - .get(BoatBridge::bridge$getUnoccupiedDecelerationSpeed) - .set(BoatBridge::bridge$setUnoccupiedDecelerationSpeed) + .get(AbstractBoatBridge::bridge$getUnoccupiedDecelerationSpeed) + .set(AbstractBoatBridge::bridge$setUnoccupiedDecelerationSpeed) ; final ResourceKey boatDataStoreKey = ResourceKey.sponge("boat"); - registrator.spongeDataStore(boatDataStoreKey, 2, new DataContentUpdater[]{BoatData.BOAT_UPDATER_BYTE_TO_BOOL_FIX}, BoatBridge.class, + registrator.spongeDataStore(boatDataStoreKey, 2, new DataContentUpdater[]{BoatData.BOAT_UPDATER_BYTE_TO_BOOL_FIX}, AbstractBoatBridge.class, Keys.MAX_SPEED, Keys.CAN_MOVE_ON_LAND, Keys.OCCUPIED_DECELERATION, Keys.UNOCCUPIED_DECELERATION); SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Boat.BOAT_MAX_SPEED, boatDataStoreKey, Keys.MAX_SPEED); SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Boat.BOAT_MOVE_ON_LAND, boatDataStoreKey, Keys.CAN_MOVE_ON_LAND); diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/CreakingData.java b/src/main/java/org/spongepowered/common/data/provider/entity/CreakingData.java new file mode 100644 index 00000000000..7bec37c48c6 --- /dev/null +++ b/src/main/java/org/spongepowered/common/data/provider/entity/CreakingData.java @@ -0,0 +1,50 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.data.provider.entity; + +import net.minecraft.world.entity.monster.creaking.Creaking; +import net.minecraft.world.entity.monster.creaking.CreakingTransient; +import org.spongepowered.api.data.Keys; +import org.spongepowered.common.accessor.world.entity.monster.creaking.CreakingTransientAccessor; +import org.spongepowered.common.data.provider.DataProviderRegistrator; +import org.spongepowered.common.util.VecHelper; + +public final class CreakingData { + + // @formatter:off + public static void register(final DataProviderRegistrator registrator) { + registrator + .asImmutable(Creaking.class) + .create(Keys.CREAKING_IS_LINKED) + .get(e -> e instanceof CreakingTransient); + registrator + .asMutable(CreakingTransient.class) + .create(Keys.CREAKING_HOME_POSITION) + .get(h -> VecHelper.toVector3i(((CreakingTransientAccessor) h).accessor$homePos())) + .set((h, v) -> ((CreakingTransientAccessor) h).accessor$setHomePos(VecHelper.toBlockPos(v))); + ; + } + // @formatter:on +} diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/EntityDataProviders.java b/src/main/java/org/spongepowered/common/data/provider/entity/EntityDataProviders.java index facac285ef6..0741cb7dadb 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/EntityDataProviders.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/EntityDataProviders.java @@ -49,6 +49,7 @@ public void registerProviders() { CatData.register(this.registrator); ChickenData.register(this.registrator); CommandBlockMinecartData.register(this.registrator); + CreakingData.register(this.registrator); CreeperData.register(this.registrator); DamagingProjectileData.register(this.registrator); DolphinData.register(this.registrator); diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/FoxData.java b/src/main/java/org/spongepowered/common/data/provider/entity/FoxData.java index f13dc6efb5e..9ab53c3d8aa 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/FoxData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/FoxData.java @@ -46,7 +46,7 @@ public static void register(final DataProviderRegistrator registrator) { .set((h, v) -> h.getEntityData().set(FoxAccessor.accessor$DATA_TRUSTED_ID_0(), Optional.ofNullable(v))) .create(Keys.FOX_TYPE) .get(h -> (FoxType) (Object) h.getVariant()) - .set((h, v) -> h.setVariant((Fox.Type) (Object) v)) + .set((h, v) -> h.setVariant((Fox.Variant) (Object) v)) .create(Keys.IS_CROUCHING) .get(Fox::isCrouching) .set(Fox::setIsCrouching) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/MooshroomData.java b/src/main/java/org/spongepowered/common/data/provider/entity/MooshroomData.java index 73587f66a71..61fdd8ad81e 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/MooshroomData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/MooshroomData.java @@ -40,7 +40,7 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(MushroomCow.class) .create(Keys.MOOSHROOM_TYPE) .get(h -> (MooshroomType) (Object) h.getVariant()) - .set((h, v) -> h.setVariant((MushroomCow.MushroomType) (Object) v)); + .set((h, v) -> h.setVariant((MushroomCow.Variant) (Object) v)); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/PaintingData.java b/src/main/java/org/spongepowered/common/data/provider/entity/PaintingData.java index b5f7f253f77..97771ab0dfc 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/PaintingData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/PaintingData.java @@ -53,7 +53,7 @@ public static void register(final DataProviderRegistrator registrator) { .setAnd((h, v) -> { if (!h.level().isClientSide) { final Holder oldArt = h.getVariant(); - var newArt = SpongeCommon.server().registryAccess().registryOrThrow(Registries.PAINTING_VARIANT).wrapAsHolder((PaintingVariant) (Object) v); + var newArt = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.PAINTING_VARIANT).wrapAsHolder((PaintingVariant) (Object) v); h.setVariant(newArt); ((HangingEntityAccessor) h).invoker$setDirection(h.getDirection()); if (!h.survives()) { diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/PlayerData.java b/src/main/java/org/spongepowered/common/data/provider/entity/PlayerData.java index ba5b59f02f5..745bd8a8c1c 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/PlayerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/PlayerData.java @@ -60,7 +60,7 @@ public static void register(final DataProviderRegistrator registrator) { .get(h -> (HandPreference) (Object) h.getMainArm()) .set((h, v) -> h.setMainArm((HumanoidArm) (Object) v)) .create(Keys.EXHAUSTION) - .get(h -> (double) h.getFoodData().getExhaustionLevel()) + .get(h -> (double) ((FoodDataAccessor) h.getFoodData()).accessor$exhaustionLevel()) .set((h, v) -> ((FoodDataAccessor) h.getFoodData()).accessor$exhaustionLevel(v.floatValue())) .create(Keys.EXPERIENCE) .get(h -> h.totalExperience) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java b/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java index 124becfdac8..8a4699c6344 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java @@ -46,7 +46,7 @@ public static void register(final DataProviderRegistrator registrator) { .get(h -> Streams.of(h.getItem().getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getAllEffects()).map(PotionEffect.class::cast).toList()) .set((h, v) -> { final var mcEffects = v.stream().map(MobEffectInstance.class::cast).toList(); - h.getItem().update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcEffects)); + h.getItem().update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcEffects, contents.customName())); }); } // @formatter:on diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java index 61c63ce3516..1d238384131 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java @@ -32,13 +32,11 @@ import net.minecraft.network.protocol.game.ClientboundRespawnPacket; import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket; import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; -import net.minecraft.network.protocol.game.CommonPlayerSpawnInfo; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import net.minecraft.stats.Stat; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.level.GameType; -import net.minecraft.world.level.biome.BiomeManager; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.chat.ChatVisibilities; @@ -143,16 +141,8 @@ private static void resendProfile(final ServerPlayer h) { // Add Entity h.serverLevel().getChunkSource().addEntity(h); // Reconnect local player - h.connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo( - h.level().dimensionTypeRegistration(), - h.level().dimension(), - BiomeManager.obfuscateSeed(h.serverLevel().getSeed()), - h.gameMode.getGameModeForPlayer(), - h.gameMode.getPreviousGameModeForPlayer(), - h.serverLevel().isDebug(), - h.serverLevel().isFlat(), - h.getLastDeathLocation(), - h.getPortalCooldown()), (byte) 0)); + final var commonSpawnInfo = h.createCommonSpawnInfo(h.serverLevel()); + h.connection.send(new ClientboundRespawnPacket(commonSpawnInfo, (byte) 0)); // tp - just in case h.connection.teleport(h.getX(), h.getY(), h.getZ(), h.getYRot(), h.getXRot()); // resend remaining player data... (see ServerPlayer#changeDimension) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java index 58f68dec195..fb77ce9b733 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java @@ -24,11 +24,18 @@ */ package org.spongepowered.common.data.provider.item.stack; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemAttributeModifiers; +import net.minecraft.world.item.equipment.Equippable; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.Keys; -import org.spongepowered.api.data.type.ArmorMaterial; -import org.spongepowered.api.item.inventory.equipment.EquipmentTypes; +import org.spongepowered.api.item.inventory.equipment.EquipmentType; +import org.spongepowered.api.registry.RegistryEntry; +import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.common.data.provider.DataProviderRegistrator; public final class ArmorItemStackData { @@ -42,37 +49,38 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.ARMOR_MATERIAL) .get(h -> { - if (h.getItem() instanceof ArmorItem armorItem) { - return (ArmorMaterial) (Object) armorItem.getMaterial().value(); + final @Nullable Equippable equippable = h.get(DataComponents.EQUIPPABLE); + if (equippable == null) { + return null; } - return null; + return equippable.model() + .map(rl -> (ResourceKey) (Object) rl) + .flatMap(rk -> RegistryTypes.ARMOR_MATERIAL.get().findEntry(rk)) + .map(RegistryEntry::value) + .orElse(null); }) .supports(h -> h.getItem() instanceof ArmorItem) .create(Keys.DAMAGE_ABSORPTION) .get(h -> { - if (h.getItem() instanceof ArmorItem armorItem) { - return (double) armorItem.getDefense(); + final @Nullable ItemAttributeModifiers modifiersContainer = h.get(DataComponents.ATTRIBUTE_MODIFIERS); + if (modifiersContainer == null) { + return null; } - return null; + return modifiersContainer.modifiers().stream() + .filter(e1 -> e1.attribute() == Attributes.ARMOR) + .findFirst() + .map(e -> e.modifier().amount()) + .orElse(null); }) .supports(h -> h.getItem() instanceof ArmorItem) .create(Keys.EQUIPMENT_TYPE) .get(h -> { - if (h.getItem() instanceof ArmorItem armorItem) { - switch (armorItem.getEquipmentSlot()) { - case FEET: - return EquipmentTypes.FEET.get(); - case LEGS: - return EquipmentTypes.LEGS.get(); - case CHEST: - return EquipmentTypes.CHEST.get(); - case HEAD: - return EquipmentTypes.HEAD.get(); - default: - break; - } + final @Nullable Equippable equippable = h.get(DataComponents.EQUIPPABLE); + if (equippable == null) { + return null; } - return null; + + return (EquipmentType) (Object) equippable.slot(); }) .supports(h -> h.getItem() instanceof ArmorItem); } diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java index bf4a788432b..1c281273d53 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java @@ -25,7 +25,6 @@ package org.spongepowered.common.data.provider.item.stack; import net.minecraft.core.component.DataComponents; -import net.minecraft.world.LockCode; import net.minecraft.world.item.BannerItem; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -52,18 +51,18 @@ public static void register(final DataProviderRegistrator registrator) { return ((DyeColorBlockBridge) block).bridge$getDyeColor().orElse(null); }) .supports(h -> h.getItem() instanceof BlockItem && !(h.getItem() instanceof BannerItem)) - .create(Keys.LOCK_TOKEN) - .get(h -> { - var component = h.getOrDefault(DataComponents.LOCK, LockCode.NO_LOCK); - return component.key().isEmpty() ? null : component.key(); - }) - .set((h, v) -> { - if (v.isEmpty()) { - h.remove(DataComponents.LOCK); - return; - } - h.set(DataComponents.LOCK, new LockCode(v)); - }) + .create(Keys.LOCK_TOKEN) // TODO - Implement Item Predicates +// .get(h -> { +// var component = h.getOrDefault(DataComponents.LOCK, LockCode.NO_LOCK); +// return component.key().isEmpty() ? null : component.key(); +// }) +// .set((h, v) -> { +// if (v.isEmpty()) { +// h.remove(DataComponents.LOCK); +// return; +// } +// h.set(DataComponents.LOCK, new LockCode(v)); +// }) .delete(h -> h.remove(DataComponents.LOCK)) .supports(h -> { if (!(h.getItem() instanceof BlockItem)) { diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java index f05aa2200fb..18306b9294b 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java @@ -29,6 +29,7 @@ import net.minecraft.core.HolderSet; import net.minecraft.core.component.DataComponentType; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.item.AdventureModePredicate; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; @@ -78,7 +79,8 @@ private static boolean set(final ItemStack stack, final DataComponentType value if (value.isEmpty()) { return BookPagesItemStackData.delete(holder, component); } - final var registry = SpongeCommon.server().registryAccess().registryOrThrow(Registries.ENCHANTMENT); + final var registry = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.ENCHANTMENT); holder.update(component, ItemEnchantments.EMPTY, ench -> { final ItemEnchantments.Mutable mutable = new ItemEnchantments.Mutable(ench); mutable.keySet().clear(); diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index 616b362f397..4b991d5a3ca 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -25,47 +25,60 @@ package org.spongepowered.common.data.provider.item.stack; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.DamageTypeTags; import net.minecraft.util.StringUtil; import net.minecraft.util.Unit; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.damagesource.DamageTypes; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ItemUseAnimation; import net.minecraft.world.item.Items; import net.minecraft.world.item.Rarity; import net.minecraft.world.item.component.ChargedProjectiles; +import net.minecraft.world.item.component.Consumable; import net.minecraft.world.item.component.CustomModelData; +import net.minecraft.world.item.component.DamageResistant; import net.minecraft.world.item.component.ItemContainerContents; import net.minecraft.world.item.component.ItemLore; import net.minecraft.world.item.component.Unbreakable; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.item.component.UseCooldown; +import net.minecraft.world.item.component.UseRemainder; +import net.minecraft.world.item.consume_effects.ApplyStatusEffectsConsumeEffect; +import net.minecraft.world.item.consume_effects.ClearAllStatusEffectsConsumeEffect; +import net.minecraft.world.item.consume_effects.ConsumeEffect; +import net.minecraft.world.item.consume_effects.PlaySoundConsumeEffect; +import net.minecraft.world.item.consume_effects.RemoveStatusEffectsConsumeEffect; +import net.minecraft.world.item.consume_effects.TeleportRandomlyConsumeEffect; +import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Platform; +import org.spongepowered.api.ResourceKey; +import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.Keys; -import org.spongepowered.api.effect.potion.PotionEffect; +import org.spongepowered.api.data.value.Value; import org.spongepowered.api.item.ItemRarity; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.util.Ticks; -import org.spongepowered.api.util.weighted.ChanceTable; -import org.spongepowered.api.util.weighted.NestedTableEntry; -import org.spongepowered.api.util.weighted.TableEntry; -import org.spongepowered.api.util.weighted.WeightedObject; -import org.spongepowered.api.util.weighted.WeightedTable; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.item.util.ItemStackUtil; -import java.util.ArrayList; import java.util.List; import java.util.Optional; @SuppressWarnings({"unchecked", "UnstableApiUsage"}) public final class ItemStackData { - public static final FoodProperties DEFAULT_FOOD_PROPERTIES = new FoodProperties(0, 0, false, 1.6F, Optional.empty(), List.of()); + public static final FoodProperties DEFAULT_FOOD_PROPERTIES = new FoodProperties(0, 0, false); + public static final Consumable DEFAULT_CONSUMABLE_PROPERTIES = new Consumable(1.6F, ItemUseAnimation.EAT, null, true, List.of()); private ItemStackData() { } @@ -87,51 +100,21 @@ public static void register(final DataProviderRegistrator registrator) { // TODO DataComponents.RECIPES - for Items.KNOWLEDGE_BOOK // TODO DataComponents.MAX_STACK_SIZE; incompatible with MAX_DAMAGE? // TODO DataComponents.OMINOUS_BOTTLE_AMPLIFIER 1.21 - registrator - .asMutable(ItemStack.class) - .create(Keys.APPLICABLE_POTION_EFFECTS) - .get(h -> { - if (h.has(DataComponents.FOOD)) { - final var itemEffects = h.get(DataComponents.FOOD).effects(); - final WeightedTable effects = new WeightedTable<>(); - final ChanceTable chance = new ChanceTable<>(); - for (final var effect : itemEffects) { - chance.add((PotionEffect) effect.effect(), effect.probability()); - } - effects.add(new NestedTableEntry<>(1, chance)); + // TODO rework applicable potion effects to consume effects + final var applicablePotionEffects = Keys.APPLICABLE_POTION_EFFECTS; + ConsumeEffect newPotionEffects = new ApplyStatusEffectsConsumeEffect(List.of()); + ConsumeEffect teleportRand = new TeleportRandomlyConsumeEffect(5); + ConsumeEffect removeStatusEffects = new RemoveStatusEffectsConsumeEffect(HolderSet.empty()); + ConsumeEffect clearStatusEffects = new ClearAllStatusEffectsConsumeEffect(); + ConsumeEffect playSoundEffect = new PlaySoundConsumeEffect(Holder.direct(null)); - return effects; - } - return null; - }) - .set((h, v) -> { - List newEffects = new ArrayList<>(); - for (final TableEntry entry : v.entries()) { - if (entry instanceof NestedTableEntry nestedTableEntry) { - if (nestedTableEntry.getNestedTable() instanceof ChanceTable chanceTable) { - for (final TableEntry te : chanceTable.entries()) { - if (te instanceof WeightedObject wo) { - newEffects.add(new FoodProperties.PossibleEffect((MobEffectInstance) wo.get(), (float) te.weight())); - } - } - } - } - } - h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), fp.saturation(), fp.canAlwaysEat(), fp.eatSeconds(), fp.usingConvertsTo(), newEffects)); - }) - + registrator + .asMutable(ItemStack.class) .create(Keys.BURN_TIME) - .get(h -> { - final Integer burnTime = AbstractFurnaceBlockEntity.getFuel().get(h.getItem()); - if (burnTime != null && burnTime > 0) { - return burnTime; - } - return null; - }) + .get(h -> SpongeCommon.server().fuelValues().burnDuration(h)) .create(Keys.CONTAINER_ITEM) - .get(h -> (ItemType) h.getItem().getCraftingRemainingItem()) + .get(h -> (ItemType) h.getItem().getCraftingRemainder().getItem()) .create(Keys.DISPLAY_NAME) .get(h -> SpongeAdventure.asAdventure(h.getDisplayName())) .create(Keys.CUSTOM_MODEL_DATA) @@ -213,37 +196,35 @@ public static void register(final DataProviderRegistrator registrator) { return food == null ? null : food.nutrition(); }) .set((h, v) -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(v, fp.saturation(), fp.canAlwaysEat(), fp.eatSeconds(), fp.usingConvertsTo(), fp.effects()))) + fp -> new FoodProperties(v, fp.saturation(), fp.canAlwaysEat()))) .create(Keys.REPLENISHED_SATURATION) .get(h -> { final var food = h.get(DataComponents.FOOD); return food == null ? null : (double) food.saturation(); }) .set((h, v) -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), v.floatValue(), fp.canAlwaysEat(), fp.eatSeconds(), fp.usingConvertsTo(), fp.effects()))) + fp -> new FoodProperties(fp.nutrition(), v.floatValue(), fp.canAlwaysEat()))) .create(Keys.CAN_ALWAYS_EAT) .get(h -> { final var food = h.get(DataComponents.FOOD); return food == null ? null : food.canAlwaysEat(); }) .set((h, v) -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), fp.saturation(), v, fp.eatSeconds(), fp.usingConvertsTo(), fp.effects()))) + fp -> new FoodProperties(fp.nutrition(), fp.saturation(), v))) .create(Keys.EATING_TIME) .get(h -> { - final var food = h.get(DataComponents.FOOD); - return food == null ? null : Ticks.of(food.eatDurationTicks()); + final var consumable = h.get(DataComponents.CONSUMABLE); + return consumable == null ? null : Ticks.of(consumable.consumeTicks()); }) - .set((h, v) -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), fp.saturation(), fp.canAlwaysEat(), v.ticks() / 20f, fp.usingConvertsTo(), fp.effects()))) + .set((h, v) -> h.update(DataComponents.CONSUMABLE, DEFAULT_CONSUMABLE_PROPERTIES, + c -> new Consumable(v.ticks() / 20f, c.animation(), c.sound(), c.hasConsumeParticles(), c.onConsumeEffects()))) .create(Keys.FOOD_CONVERTS_TO) .get(h -> { - final var food = h.get(DataComponents.FOOD); - return food == null ? null : food.usingConvertsTo().map(ItemStackUtil::fromNative).orElse(null); + final var remainder = h.get(DataComponents.USE_REMAINDER); + return remainder == null ? null : ItemStackUtil.fromNative(remainder.convertInto()); }) - .set((h, v) -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), fp.saturation(), fp.canAlwaysEat(), fp.eatSeconds(), Optional.ofNullable(ItemStackUtil.toNative(v)), fp.effects()))) - .delete(h -> h.update(DataComponents.FOOD, DEFAULT_FOOD_PROPERTIES, - fp -> new FoodProperties(fp.nutrition(), fp.saturation(), fp.canAlwaysEat(), fp.eatSeconds(), Optional.empty(), fp.effects()))) + .set((h, v) -> h.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackUtil.toNative(v)))) + .delete(h -> h.remove(DataComponents.USE_REMAINDER)) .create(Keys.REPAIR_COST) .get(h -> h.getOrDefault(DataComponents.REPAIR_COST, 0)) .set((stack, cost) -> stack.set(DataComponents.REPAIR_COST, cost)) @@ -274,18 +255,26 @@ public static void register(final DataProviderRegistrator registrator) { }) .delete(stack -> stack.remove(DataComponents.CONTAINER)) .create(Keys.FIRE_RESISTANT) - .get(h -> h.get(DataComponents.FIRE_RESISTANT) != null) + .get(h -> { + final @Nullable DamageResistant resist = h.get(DataComponents.DAMAGE_RESISTANT); + if (resist == null) { + return false; + } + return resist.types().location().equals(DamageTypes.IN_FIRE.location()); + }) .set((h, value) -> { if (value) { - h.set(DataComponents.FIRE_RESISTANT, Unit.INSTANCE); + h.applyComponents(DataComponentPatch.builder() + .set(DataComponents.DAMAGE_RESISTANT, new DamageResistant(DamageTypeTags.IS_FIRE)) + .build()); } else { - h.remove(DataComponents.FIRE_RESISTANT); + h.remove(DataComponents.DAMAGE_RESISTANT); } }) - .delete(stack -> stack.remove(DataComponents.FIRE_RESISTANT)) + .delete(stack -> stack.remove(DataComponents.DAMAGE_RESISTANT)) .create(Keys.ITEM_NAME) .get(h -> { - final Component component = h.get(DataComponents.ITEM_NAME); + final @Nullable Component component = h.get(DataComponents.ITEM_NAME); if (component == null) { return null; } @@ -293,7 +282,56 @@ public static void register(final DataProviderRegistrator registrator) { }) .set((h, value) -> h.set(DataComponents.ITEM_NAME, SpongeAdventure.asVanillaMutable(value))) .delete(stack -> stack.remove(DataComponents.ITEM_NAME)) - ; + .create(Keys.COOLDOWN_GROUP) + .get(h -> { + final @Nullable UseCooldown cooldown = h.get(DataComponents.USE_COOLDOWN); + if (cooldown == null) { + return null; + } + return (ResourceKey) (Object) cooldown.cooldownGroup().orElse(null); + }) + .set((h, value) -> { + if (value == null) { + h.remove(DataComponents.USE_COOLDOWN); + return; + } + h.set(DataComponents.USE_COOLDOWN, new UseCooldown(1, Optional.of((ResourceLocation) (Object) value))); + }) + .deleteAndGet(ItemStackData::deleteAndTransactUseCooldown) + .create(Keys.COOLDOWN) + .get(h -> { + final @Nullable UseCooldown cooldown = h.get(DataComponents.USE_COOLDOWN); + if (cooldown == null) { + return null; + } + return Ticks.of(cooldown.ticks()); + }) + .setAndGet((h, value) -> { + if (value == null) { + return ItemStackData.deleteAndTransactUseCooldown(h); + } + final var existing = h.get(DataComponents.USE_COOLDOWN); + var builder = DataTransactionResult.builder() + .success(Value.immutableOf(Keys.COOLDOWN, value)); + if (existing != null) { + h.set(DataComponents.USE_COOLDOWN, new UseCooldown(value.ticks(), existing.cooldownGroup())); + builder.replace(existing.cooldownGroup().map(ResourceKey.class::cast) + .map(group -> + List.of( + Value.immutableOf(Keys.COOLDOWN, Ticks.of(existing.ticks())), + Value.immutableOf(Keys.COOLDOWN_GROUP, group) + ) + ) + .orElseGet(() -> List.of( + Value.immutableOf(Keys.COOLDOWN, Ticks.of(existing.ticks())) + ))); + } else { + h.set(DataComponents.USE_COOLDOWN, new UseCooldown(value.ticks(), Optional.empty())); + } + return builder.build(); + }) + .deleteAndGet(ItemStackData::deleteAndTransactUseCooldown) + ; } // @formatter:on @@ -320,4 +358,18 @@ private static void setIsUnbrekable(final ItemStack stack, final Boolean value) } } + private static DataTransactionResult deleteAndTransactUseCooldown(final ItemStack stack) { + final @Nullable UseCooldown cooldown = stack.remove(DataComponents.USE_COOLDOWN); + if (cooldown == null) { + return DataTransactionResult.successNoData(); + } + return cooldown.cooldownGroup() + .map(group -> DataTransactionResult.successRemove(List.of( + Value.immutableOf(Keys.COOLDOWN, Ticks.of(cooldown.ticks())), + Value.immutableOf(Keys.COOLDOWN_GROUP, (ResourceKey) (Object) group) + ))).orElseGet(() -> DataTransactionResult.successRemove(List.of( + Value.immutableOf(Keys.COOLDOWN, Ticks.of(cooldown.ticks())) + ))); + } + } diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java index be2f98a5f69..5c22eacc624 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java @@ -56,8 +56,8 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.COLOR) .get(h -> Color.ofRgb(h.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getColor())) - .set((h, v) -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects()))) - .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.empty(), contents.customEffects()))) + .set((h, v) -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects(), contents.customName()))) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.empty(), contents.customEffects(), contents.customName()))) .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) .create(Keys.CUSTOM_POTION_EFFECTS) .get(h -> { @@ -66,17 +66,17 @@ public static void register(final DataProviderRegistrator registrator) { }) .set((h, v) -> { final var mcList = v.stream().map(MobEffectInstance.class::cast).toList(); - h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcList)); + h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcList, contents.customName())); }) - .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), Collections.emptyList()))) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), Collections.emptyList(), contents.customName()))) .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) .create(Keys.POTION_TYPE) .get(h -> (PotionType) h.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion().map(Holder::value).orElse(null)) // TODO empty POTION gone? .set((h, v) -> { final var potion = Optional.ofNullable(v).map(Potion.class::cast).map(BuiltInRegistries.POTION::wrapAsHolder); // TODO set empty POTION? same as delete? - h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(potion, contents.customColor(), contents.customEffects())); + h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(potion, contents.customColor(), contents.customEffects(), contents.customName())); }) - .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(Optional.empty(), contents.customColor(), contents.customEffects()))) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(Optional.empty(), contents.customColor(), contents.customEffects(), contents.customName()))) .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) .create(Keys.POTION_EFFECTS) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/TieredItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/TieredItemStackData.java index 63321580580..f6a67c892ee 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/TieredItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/TieredItemStackData.java @@ -24,12 +24,8 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Tier; -import net.minecraft.world.item.TieredItem; import org.spongepowered.api.data.Keys; -import org.spongepowered.api.data.type.ItemTier; import org.spongepowered.common.data.provider.DataProviderRegistrator; public final class TieredItemStackData { @@ -41,18 +37,21 @@ private TieredItemStackData() { public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) - .create(Keys.TOOL_TYPE) - .get(h -> { - final Item item = h.getItem(); - if (item instanceof TieredItem) { - final Tier tier = ((TieredItem) item).getTier(); - if (tier instanceof ItemTier) { - return (ItemTier) tier; - } - } - return null; - }) - .supports(h -> h.getItem() instanceof TieredItem); + .create(Keys.TOOL_TYPE); + // TODO - snapshot 24w34a changes away from the enum to a record and data components +// .get(h -> { +// h.is(ItemTags.WOODEN_TOOL_MATERIALS) +// final Item item = h.getItem(); +// final Tool tool = h.get(DataComponents.TOOL); +// if (item instanceof ToolItem) { +// final Tier tier = ((TieredItem) item).getTier(); +// if (tier instanceof ItemTier) { +// return (ItemTier) tier; +// } +// } +// return null; +// }) +// .supports(h -> h.getItem() instanceof TieredItem); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/WoolItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/WoolItemStackData.java index 1543024420f..6ab69a33d37 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/WoolItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/WoolItemStackData.java @@ -24,11 +24,11 @@ */ package org.spongepowered.common.data.provider.item.stack; +import net.minecraft.data.loot.packs.LootData; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.DyeColor; -import org.spongepowered.common.accessor.world.entity.animal.SheepAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.DyeColorUtil; @@ -43,7 +43,7 @@ public static void register(final DataProviderRegistrator registrator) { .asImmutable(ItemStack.class) .create(Keys.DYE_COLOR) .get(h -> (DyeColor) (Object) DyeColorUtil.COLOR_BY_WOOL.get(((BlockItem) h.getItem()).getBlock())) - .supports(h -> h.getItem() instanceof BlockItem && SheepAccessor.accessor$ITEM_BY_DYE().containsValue(((BlockItem) h.getItem()).getBlock())); + .supports(h -> h.getItem() instanceof BlockItem && LootData.WOOL_ITEM_BY_DYE.containsValue(((BlockItem) h.getItem()).getBlock())); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/world/biome/BiomeData.java b/src/main/java/org/spongepowered/common/data/provider/world/biome/BiomeData.java index 4b5e92d46c8..e63a348dd9e 100644 --- a/src/main/java/org/spongepowered/common/data/provider/world/biome/BiomeData.java +++ b/src/main/java/org/spongepowered/common/data/provider/world/biome/BiomeData.java @@ -41,7 +41,6 @@ import org.spongepowered.api.world.biome.spawner.NaturalSpawnCost; import org.spongepowered.api.world.biome.spawner.NaturalSpawner; import org.spongepowered.api.world.generation.carver.Carver; -import org.spongepowered.api.world.generation.carver.CarvingStep; import org.spongepowered.api.world.generation.feature.DecorationStep; import org.spongepowered.api.world.generation.feature.PlacedFeature; import org.spongepowered.common.accessor.world.level.biome.BiomeAccessor; @@ -116,15 +115,9 @@ public static void register(final DataProviderRegistrator registrator) { } // @formatter:on - private static Map> carvers(final Biome biome) { + public static List carvers(final Biome biome) { final var settings = biome.getGenerationSettings(); - return Arrays.stream(GenerationStep.Carving.values()) - .collect(Collectors.toMap(step -> (CarvingStep) (Object) step, - step -> BiomeData.carverList(settings, step))); - } - - private static List carverList(final BiomeGenerationSettings settings, final GenerationStep.Carving step) { - final var carvers = settings.getCarvers(step); + final var carvers = settings.getCarvers(); return StreamSupport.stream(carvers.spliterator(), false) .map(carver -> (Carver) (Object) carver.value()) .collect(Collectors.toList()); diff --git a/src/main/java/org/spongepowered/common/data/type/SpongeArtTypeTemplate.java b/src/main/java/org/spongepowered/common/data/type/SpongeArtTypeTemplate.java index b97360fe3d6..1b184a83ef8 100644 --- a/src/main/java/org/spongepowered/common/data/type/SpongeArtTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/data/type/SpongeArtTypeTemplate.java @@ -44,6 +44,7 @@ import java.io.IOException; import java.util.Objects; +import java.util.Optional; import java.util.function.Function; public record SpongeArtTypeTemplate(ResourceKey key, PaintingVariant representedType, DataPack pack) implements ArtTypeTemplate { @@ -130,7 +131,7 @@ protected ArtTypeTemplate build0() { Preconditions.checkArgument(this.width >= 0, "width must set"); Preconditions.checkArgument(this.height >= 0, "height must set"); Objects.requireNonNull(this.assetId, "assetId"); - return new SpongeArtTypeTemplate(this.key, new PaintingVariant(this.width, this.height, this.assetId), this.pack); + return new SpongeArtTypeTemplate(this.key, new PaintingVariant(this.width, this.height, this.assetId, Optional.empty(), Optional.empty()), this.pack); } } } diff --git a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java index 3e582e1edab..c09654d2ca8 100644 --- a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java +++ b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java @@ -38,7 +38,7 @@ import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBundlePacket; import net.minecraft.network.protocol.game.ClientboundLevelParticlesPacket; -import net.minecraft.util.FastColor; +import net.minecraft.util.ARGB; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.effect.particle.ParticleEffect; @@ -108,27 +108,15 @@ private static CachedParticlePacket getNamedPacket(final ParticleEffect effect, final Color toColor = effect.optionOrDefault(ParticleOptions.TO_COLOR).get(); final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); final DustColorTransitionOptions particleData = new DustColorTransitionOptions( - new org.joml.Vector3f( - (float) color.red() / 255, - (float) color.green() / 255, - (float) color.blue() / 255 - ), - new org.joml.Vector3f( - (float) toColor.red() / 255, - (float) toColor.green() / 255, - (float) toColor.blue() / 255 - ), + ARGB.color(color.red(), color.green(), color.blue()), + ARGB.color(toColor.red(), toColor.green(), toColor.blue()), (float) scale); return new NamedCachedPacket(particleData, offset, quantity, velocity); } else if (internalType == ParticleTypes.DUST) { //This particle type supports a color option. final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); - final DustParticleOptions particleData = new DustParticleOptions(new org.joml.Vector3f( - (float) color.red() / 255, - (float) color.green() / 255, - (float) color.blue() / 255), - (float) scale); + final DustParticleOptions particleData = new DustParticleOptions(ARGB.color(color.red(), color.green(), color.blue()), (float) scale); return new NamedCachedPacket(particleData, offset, quantity, velocity); } else if (internalType == ParticleTypes.ITEM) { //This particle type supports an item option. @@ -158,7 +146,7 @@ private static CachedParticlePacket getNamedPacket(final ParticleEffect effect, final double opacity = effect.optionOrDefault(ParticleOptions.OPACITY).get(); final ColorParticleOption particleData = ColorParticleOption.create( (net.minecraft.core.particles.ParticleType) internalType, - FastColor.ARGB32.color(FastColor.as8BitChannel((float) opacity), color.red(), color.green(), color.blue())); + ARGB.color(ARGB.as8BitChannel((float) opacity), color.red(), color.green(), color.blue())); return new NamedCachedPacket(particleData, offset, quantity, velocity); } diff --git a/src/main/java/org/spongepowered/common/effect/sound/SpongeSoundBuilder.java b/src/main/java/org/spongepowered/common/effect/sound/SpongeSoundBuilder.java index d6f6dbb9a6a..9b99d2bfb6c 100644 --- a/src/main/java/org/spongepowered/common/effect/sound/SpongeSoundBuilder.java +++ b/src/main/java/org/spongepowered/common/effect/sound/SpongeSoundBuilder.java @@ -33,6 +33,6 @@ public final class SpongeSoundBuilder extends AbstractResourceKeyedBuilder apply(final ServerLocation compound.put(Constants.Entity.ENTITY_POSITION, pos); compound.remove(Constants.Entity.ENTITY_UUID); - final @Nullable Entity entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(compound, level, e -> { + final @Nullable Entity entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(compound, level, EntitySpawnReason.LOAD, e -> { e.moveTo(location.x(), location.y(), location.z()); if (e instanceof Mob mobentity) { mobentity.yHeadRot = mobentity.getYRot(); diff --git a/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/SpongeAvoidLivingGoalBuilder.java b/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/SpongeAvoidLivingGoalBuilder.java index d71213c7d9f..a075bb4af60 100644 --- a/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/SpongeAvoidLivingGoalBuilder.java +++ b/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/SpongeAvoidLivingGoalBuilder.java @@ -29,6 +29,7 @@ import org.spongepowered.api.entity.ai.goal.builtin.creature.AvoidLivingGoal; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.PathfinderAgent; +import org.spongepowered.api.world.server.ServerWorld; import java.util.Objects; import java.util.function.Predicate; @@ -69,7 +70,7 @@ public AvoidLivingGoal.Builder farRangeSpeed(double speed) { @Override public AvoidLivingGoal.Builder from(AvoidLivingGoal value) { - return this.targetSelector(value.targetSelector()) + return this.targetSelector((e) -> value.targetSelector().test(e, (ServerWorld) e.world())) .searchDistance(value.searchDistance()) .closeRangeSpeed(value.closeRangeSpeed()) .farRangeSpeed(value.farRangeSpeed()); diff --git a/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/target/SpongeFindNearestAttackableTargetGoalBuilder.java b/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/target/SpongeFindNearestAttackableTargetGoalBuilder.java index a85069f64e2..435b72001e8 100644 --- a/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/target/SpongeFindNearestAttackableTargetGoalBuilder.java +++ b/src/main/java/org/spongepowered/common/entity/ai/goal/builtin/creature/target/SpongeFindNearestAttackableTargetGoalBuilder.java @@ -28,6 +28,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal; +import net.minecraft.world.entity.ai.targeting.TargetingConditions; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.entity.ai.goal.builtin.creature.target.FindNearestAttackableTargetGoal; import org.spongepowered.api.entity.living.Living; @@ -40,7 +41,7 @@ public final class SpongeFindNearestAttackableTargetGoalBuilder extends SpongeTargetGoalBuilder implements FindNearestAttackableTargetGoal.Builder { - private static final Predicate ALWAYS_TRUE = e -> true; + private static final TargetingConditions.Selector ALWAYS_TRUE = (e, l) -> true; private Class targetClass; private int chance; @@ -94,6 +95,6 @@ public FindNearestAttackableTargetGoal build(PathfinderAgent owner) { Objects.requireNonNull(this.targetClass); return (FindNearestAttackableTargetGoal) new NearestAttackableTargetGoal((PathfinderMob) owner, this.targetClass, this.chance, - this.checkSight, this.checkOnlyNearby, this.predicate == null ? SpongeFindNearestAttackableTargetGoalBuilder.ALWAYS_TRUE : this.predicate); + this.checkSight, this.checkOnlyNearby, this.predicate == null ? SpongeFindNearestAttackableTargetGoalBuilder.ALWAYS_TRUE : (e, l) -> ((Predicate) this.predicate).test(l)); } } diff --git a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java index a38c2d70259..f985c34e232 100644 --- a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java +++ b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java @@ -429,7 +429,8 @@ public void untrackFrom(final ServerPlayer player) { public ClientboundPlayerInfoUpdatePacket createPlayerListPacket(final EnumSet actions) { final ClientboundPlayerInfoUpdatePacket packet = new ClientboundPlayerInfoUpdatePacket(actions, List.of()); - ((ClientboundPlayerInfoUpdatePacketAccessor) packet).accessor$entries(List.of(new ClientboundPlayerInfoUpdatePacket.Entry(this.uuid, this.fakeProfile.gameProfile(), false, 0, GameType.DEFAULT_MODE, this.getDisplayName(), null))); + ((ClientboundPlayerInfoUpdatePacketAccessor) packet).accessor$entries(List.of( + new ClientboundPlayerInfoUpdatePacket.Entry(this.uuid, this.fakeProfile.gameProfile(), false, 0, GameType.DEFAULT_MODE, this.getDisplayName(), 0, null))); return packet; } diff --git a/src/main/java/org/spongepowered/common/entity/player/tab/SpongeTabList.java b/src/main/java/org/spongepowered/common/entity/player/tab/SpongeTabList.java index cf350b3d665..8d49e1212f2 100644 --- a/src/main/java/org/spongepowered/common/entity/player/tab/SpongeTabList.java +++ b/src/main/java/org/spongepowered/common/entity/player/tab/SpongeTabList.java @@ -190,11 +190,11 @@ public Optional removeEntry(final UUID uniqueId) { @SuppressWarnings("ConstantConditions") void sendUpdate(final TabListEntry entry, final EnumSet actions) { final ClientboundPlayerInfoUpdatePacket packet = new ClientboundPlayerInfoUpdatePacket(actions, List.of()); - + int listOrder = 0; // TODO expose to API final RemoteChatSession.Data chatSessionData = ((SpongeTabListEntry) entry).profilePublicKey() == null ? null : new RemoteChatSession.Data(entry.profile().uuid(), ((SpongeTabListEntry) entry).profilePublicKey()); final net.minecraft.network.chat.Component displayName = entry.displayName().isPresent() ? SpongeAdventure.asVanilla(entry.displayName().get()) : null; final ClientboundPlayerInfoUpdatePacket.Entry data = new ClientboundPlayerInfoUpdatePacket.Entry(entry.profile().uniqueId(), SpongeGameProfile.toMcProfile(entry.profile()), - entry.listed(), entry.latency(), (GameType) (Object) entry.gameMode(), displayName, chatSessionData); + entry.listed(), entry.latency(), (GameType) (Object) entry.gameMode(), displayName, listOrder, chatSessionData); ((ClientboundPlayerInfoUpdatePacketAccessor) packet).accessor$entries(List.of(data)); this.player.connection.send(packet); } diff --git a/src/main/java/org/spongepowered/common/entity/projectile/DispenserSourceLogic.java b/src/main/java/org/spongepowered/common/entity/projectile/DispenserSourceLogic.java index 7aa7c741042..58e29308780 100644 --- a/src/main/java/org/spongepowered/common/entity/projectile/DispenserSourceLogic.java +++ b/src/main/java/org/spongepowered/common/entity/projectile/DispenserSourceLogic.java @@ -57,7 +57,7 @@ public

Optional

launch(final ProjectileLogic

logic, if (projectile.isPresent()) { final Direction enumfacing = DispenserSourceLogic.getFacing((DispenserBlockEntity) source); final net.minecraft.world.entity.Entity projectileEntity = (net.minecraft.world.entity.Entity) projectile.get(); - final BlockPos adjustedPosition = projectileEntity.blockPosition().offset(enumfacing.getNormal()); + final BlockPos adjustedPosition = projectileEntity.blockPosition().offset(enumfacing.getUnitVec3i()); projectileEntity.setPos(adjustedPosition.getX(), adjustedPosition.getY(), adjustedPosition.getZ()); } return projectile; diff --git a/src/main/java/org/spongepowered/common/entity/projectile/ProjectileUtil.java b/src/main/java/org/spongepowered/common/entity/projectile/ProjectileUtil.java index 8d73b2dde50..c7963bdab4d 100644 --- a/src/main/java/org/spongepowered/common/entity/projectile/ProjectileUtil.java +++ b/src/main/java/org/spongepowered/common/entity/projectile/ProjectileUtil.java @@ -197,7 +197,7 @@ protected Optional createProjectile(final LivingEntity source, fi @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { - final ThrownEgg egg = new ThrownEgg(source.level(), source); + final ThrownEgg egg = new ThrownEgg(source.level(), source, new ItemStack(Items.EGG)); egg.shoot(source.getXRot(), source.getYRot(), 0.0F, 1.5F, 0); return ProjectileUtil.doLaunch(loc.world(), (Egg) egg); } @@ -226,7 +226,8 @@ protected Optional createProjectile(final LivingEntity source, f @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { - final net.minecraft.world.entity.projectile.Snowball snowball = new net.minecraft.world.entity.projectile.Snowball(source.level(), source); + final net.minecraft.world.entity.projectile.Snowball snowball = new net.minecraft.world.entity.projectile.Snowball( + source.level(), source, new ItemStack(Items.SNOWBALL)); snowball.shoot(source.getXRot(), source.getYRot(), 0.0F, 1.5F, 0); return ProjectileUtil.doLaunch(loc.world(), (Snowball) snowball); } @@ -236,7 +237,7 @@ protected Optional createProjectile(final LivingEntity source, final S @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { - final ThrownExperienceBottle expBottle = new ThrownExperienceBottle(source.level(), source); + final ThrownExperienceBottle expBottle = new ThrownExperienceBottle(source.level(), source, new ItemStack(Items.EXPERIENCE_BOTTLE)); expBottle.shoot(source.getXRot(), source.getYRot(), -20.0F, 0.7F, 0); return ProjectileUtil.doLaunch(loc.world(), (ExperienceBottle) expBottle); } @@ -247,7 +248,7 @@ protected Optional createProjectile(final LivingEntity source, @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { - final ThrownEnderpearl pearl = new ThrownEnderpearl(source.level(), source); + final ThrownEnderpearl pearl = new ThrownEnderpearl(source.level(), source, new ItemStack(Items.ENDER_PEARL)); pearl.shoot(source.getXRot(), source.getYRot(), 0.0F, 1.5F, 0); return ProjectileUtil.doLaunch(loc.world(), (EnderPearl) pearl); } @@ -295,7 +296,7 @@ protected Optional createProjectile(final LivingEntity source, fina @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { if (source instanceof Player) { - final FishingHook hook = new FishingHook((Player) source, source.level(), 0, 0); + final FishingHook hook = new FishingHook((Player) source, source.level(), 0, 0, new ItemStack(Items.FISHING_ROD)); hook.setPos(loc.x(), loc.y(), loc.z()); return ProjectileUtil.doLaunch(loc.world(), (FishingBobber) hook); } @@ -306,7 +307,7 @@ protected Optional createProjectile(final LivingEntity source, fi @Override protected Optional createProjectile(final LivingEntity source, final ServerLocation loc) { - final ThrownPotion potion = new ThrownPotion(source.level(), source); + final ThrownPotion potion = new ThrownPotion(source.level(), source, new ItemStack(this.item)); potion.setItem(new ItemStack(Items.SPLASH_POTION, 1)); potion.shoot(source.getXRot(), source.getYRot(), -20.0F, 0.5F, 0); return ProjectileUtil.doLaunch(loc.world(), (Potion) potion); diff --git a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java index acb07d0647e..6ec6a447ce9 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java +++ b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java @@ -63,7 +63,6 @@ import org.spongepowered.api.effect.sound.music.MusicDisc; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityTypes; -import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.entity.living.Agent; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.player.Player; @@ -85,7 +84,6 @@ import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.event.entity.RotateEntityEvent; import org.spongepowered.api.event.entity.ai.SetAITargetEvent; -import org.spongepowered.api.event.entity.explosive.DetonateExplosiveEvent; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.item.inventory.InteractItemEvent; import org.spongepowered.api.event.sound.PlaySoundEvent; @@ -97,13 +95,11 @@ import org.spongepowered.api.world.DefaultWorldKeys; import org.spongepowered.api.world.LocatableBlock; import org.spongepowered.api.world.World; -import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.CreatorTrackedBridge; -import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.map.MapIdTrackerBridge; import org.spongepowered.common.bridge.server.level.ServerLevelBridge; import org.spongepowered.common.bridge.world.TrackedWorldBridge; @@ -116,7 +112,6 @@ import org.spongepowered.common.entity.projectile.UnknownProjectileSource; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseTracker; -import org.spongepowered.common.event.tracking.phase.general.GeneralPhase; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.map.SpongeMapStorage; import org.spongepowered.common.registry.provider.DirectionFacingProvider; @@ -508,7 +503,7 @@ public static DestructEntityEvent.Death callDestructEntityEventDeath(final Livin final DestructEntityEvent.Death event = SpongeEventFactory.createDestructEntityEventDeath(frame.currentCause(), originalChannel, Optional.of(originalChannel), originalMessage, originalMessage, (Living) entity, - entity.level().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY), messageCancelled); + ((ServerLevel) entity.level()).getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY), messageCancelled); SpongeCommon.post(event); return event; @@ -527,7 +522,7 @@ public static boolean handleCollideBlockEvent(final Block block, final Level wor return false; } - if (world.isClientSide() || pos.getY() < world.getMinBuildHeight()) { + if (world.isClientSide() || pos.getY() < world.getMinY()) { return false; } @@ -591,7 +586,7 @@ public static boolean handleCollideImpactEvent(final net.minecraft.world.entity. if (movingObjectType == HitResult.Type.BLOCK) { final BlockHitResult blockMovingObjectPosition = (BlockHitResult) movingObjectPosition; final BlockPos blockPos = blockMovingObjectPosition.getBlockPos(); - if (blockPos.getY() < projectile.level().getMinBuildHeight()) { + if (blockPos.getY() < projectile.level().getMinY()) { return false; } @@ -626,24 +621,6 @@ public static SetAITargetEvent callSetAttackTargetEvent(final @Nullable Entity t return event; } - public static Optional detonateExplosive(final ExplosiveBridge explosiveBridge, final Explosion.Builder builder) { - final DetonateExplosiveEvent event = SpongeEventFactory.createDetonateExplosiveEvent( - PhaseTracker.getCauseStackManager().currentCause(), builder, (Explosive) explosiveBridge, builder.build() - ); - if (!Sponge.eventManager().post(event)) { - final Explosion explosion = event.explosionBuilder().build(); - if (explosion.radius() > 0) { - ((TrackedWorldBridge) ((Explosive) explosiveBridge).world()) - .tracker$triggerInternalExplosion( - explosion, - e -> GeneralPhase.State.EXPLOSION.createPhaseContext(PhaseTracker.SERVER).explosion(e) - ); - } - return Optional.of((net.minecraft.world.level.Explosion) explosion); - } - return Optional.empty(); - } - /** * @author gabizou - April 19th, 2018 * Creates two events here: @@ -740,14 +717,14 @@ public static PlaySoundEvent.AtEntity callPlaySoundAtEntityEvent(final Cause cau final SoundEvent name, final float pitch, final float volume) { final ServerLocation location = ServerLocation.of((ServerWorld) worldMixin, x, y, z); final PlaySoundEvent.AtEntity event = SpongeEventFactory.createPlaySoundEventAtEntity(cause, location, - Optional.ofNullable((ServerPlayer) entity), SpongeAdventure.asAdventure(category), (SoundType) name, pitch, volume); + Optional.ofNullable((ServerPlayer) entity), SpongeAdventure.asAdventure(category), (SoundType) (Object) name, pitch, volume); SpongeCommon.post(event); return event; } public static PlaySoundEvent.NoteBlock callPlaySoundNoteBlockEvent(final Cause cause, final World world, final BlockPos pos, final SoundEvent soundEvent, final InstrumentType instrument, final NotePitch notePitch, final Float pitch) { final ServerLocation location = ServerLocation.of((ServerWorld) world, pos.getX(), pos.getY(), pos.getZ()); - final PlaySoundEvent.NoteBlock event = SpongeEventFactory.createPlaySoundEventNoteBlock(cause, instrument, location, notePitch, Sound.Source.RECORD, (SoundType)soundEvent, pitch, 3.0F); + final PlaySoundEvent.NoteBlock event = SpongeEventFactory.createPlaySoundEventNoteBlock(cause, instrument, location, notePitch, Sound.Source.RECORD, (SoundType) (Object) soundEvent, pitch, 3.0F); SpongeCommon.post(event); return event; } diff --git a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageSourceBuilder.java b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageSourceBuilder.java index 6e3b1bb45ce..c2141f4b563 100644 --- a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageSourceBuilder.java +++ b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageSourceBuilder.java @@ -63,7 +63,7 @@ public DamageSource build() throws IllegalStateException { @Override public DamageSource.Builder type(final DamageType damageType) { - final var registry = SpongeCommon.server().registryAccess().registryOrThrow(Registries.DAMAGE_TYPE); + final var registry = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.DAMAGE_TYPE); this.damageType = registry.wrapAsHolder((net.minecraft.world.damagesource.DamageType) (Object) damageType); return this; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/IPhaseState.java b/src/main/java/org/spongepowered/common/event/tracking/IPhaseState.java index 54ea2b458ae..b5d7f058589 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/IPhaseState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/IPhaseState.java @@ -60,6 +60,7 @@ import org.spongepowered.api.util.Tuple; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.World; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.server.TickTaskBridge; import org.spongepowered.common.bridge.server.level.ServerLevelBridge; @@ -159,12 +160,14 @@ default boolean isInteraction() { /** * Performs any necessary custom logic after the provided {@link BlockSnapshot} * {@link Transaction} has taken place. - * @param context The context for information + * + * @param context The context for information + * @param serverWorld * @param blockChange The block change performed - * @param receipt The transaction of the old and new snapshots + * @param receipt The transaction of the old and new snapshots */ default void postBlockTransactionApplication( - final C context, final BlockChange blockChange, + final C context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt receipt ) { } diff --git a/src/main/java/org/spongepowered/common/event/tracking/PhaseStateProxy.java b/src/main/java/org/spongepowered/common/event/tracking/PhaseStateProxy.java index 9f2aa7307b0..78bc12d574b 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/PhaseStateProxy.java +++ b/src/main/java/org/spongepowered/common/event/tracking/PhaseStateProxy.java @@ -53,6 +53,7 @@ import org.spongepowered.api.item.inventory.transaction.SlotTransaction; import org.spongepowered.api.util.Tuple; import org.spongepowered.api.world.BlockChangeFlag; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.server.TickTaskBridge; import org.spongepowered.common.bridge.world.TrackedWorldBridge; @@ -102,11 +103,13 @@ default boolean isInteraction() { /** * Performs any necessary custom logic after the provided {@link BlockSnapshot} * {@link Transaction} has taken place. - * @param blockChange The block change performed - * @param receipt The transaction of the old and new snapshots + * + * @param serverWorld + * @param blockChange The block change performed + * @param receipt The transaction of the old and new snapshots */ - default void postBlockTransactionApplication(final BlockChange blockChange, final BlockTransactionReceipt receipt) { - this.getState().postBlockTransactionApplication(this.asContext(), blockChange, receipt); + default void postBlockTransactionApplication(ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt receipt) { + this.getState().postBlockTransactionApplication(this.asContext(), serverWorld, blockChange, receipt); } /** diff --git a/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java b/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java index e969fb1baee..67a35d5fa35 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java +++ b/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java @@ -233,12 +233,10 @@ public static void updateTickBlock( } public static void updateTickFluid( - final TrackedWorldBridge mixinWorld, final FluidState fluidState, final BlockPos pos - ) { + final TrackedWorldBridge mixinWorld, final FluidState fluidState, final BlockPos pos, final net.minecraft.world.level.block.state.BlockState blockState) { final ServerLevel world = (ServerLevel) mixinWorld; final org.spongepowered.api.world.server.ServerWorld apiWorld = (org.spongepowered.api.world.server.ServerWorld) world; - final net.minecraft.world.level.block.state.BlockState blockState = fluidState.createLegacyBlock(); if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot snapshot = mixinWorld.bridge$createSnapshot(blockState, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventScheduled(PhaseTracker.getCauseStackManager().currentCause(), snapshot); @@ -261,7 +259,7 @@ public static void updateTickFluid( try (final PhaseContext context = phaseContext) { context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.FLUID_TICK, () -> "Wrapping Fluid Tick: " + fluidState.toString()); - fluidState.tick(world, pos); + fluidState.tick(world, pos, blockState); } catch (final Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, phaseContext); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/block/ChangeBlock.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/block/ChangeBlock.java index 527a30c23a0..7efa1a2dfa7 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/block/ChangeBlock.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/block/ChangeBlock.java @@ -71,7 +71,7 @@ public ChangeBlock( this.original = attachedSnapshot; this.newState = newState; this.blockChangeFlag = blockChange; - this.originalOpacity = this.originalState.getLightBlock(this.original.getServerWorld().get(), this.affectedPosition); + this.originalOpacity = this.originalState.getLightBlock(); } public BlockState getNewState() { diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/AddBlockLootDropsEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/AddBlockLootDropsEffect.java index 51e1a40d109..05d963c3f60 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/AddBlockLootDropsEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/AddBlockLootDropsEffect.java @@ -60,8 +60,8 @@ public EffectResult processSideEffect( final PhaseContext<@NonNull ?> phaseContext = PhaseTracker.getInstance().getPhaseContext(); final ServerLevel world = pipeline.getServerWorld(); - final @Nullable BlockEntity existingTile = oldState.tileEntity; - final BlockPos pos = oldState.pos; + final @Nullable BlockEntity existingTile = oldState.tileEntity(); + final BlockPos pos = oldState.pos(); final LootParams.Builder lootBuilder = new LootParams.Builder(world) .withParameter(LootContextParams.ORIGIN, VecHelper.toVanillaVector3d(pos)) @@ -70,6 +70,6 @@ public EffectResult processSideEffect( phaseContext.populateLootContext(lootBuilder); - return new EffectResult(newState, oldState.state.getDrops(lootBuilder), false); + return new EffectResult(newState, oldState.state().getDrops(lootBuilder), false); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/BlockAddedEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/BlockAddedEffect.java index bb2a8c66667..50b2977f8b2 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/BlockAddedEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/BlockAddedEffect.java @@ -53,7 +53,7 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli // so we wrap the onPlace with the flag check (also, we're always on the // server in this context). if (flag.performBlockPhysics()) { - newState.onPlace(pipeline.getServerWorld(), oldState.pos, oldState.state, flag.movingBlocks()); + newState.onPlace(pipeline.getServerWorld(), oldState.pos(), oldState.state(), flag.movingBlocks()); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/CheckBlockPostPlacementIsSameEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/CheckBlockPostPlacementIsSameEffect.java index f3693379738..951ba947beb 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/CheckBlockPostPlacementIsSameEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/CheckBlockPostPlacementIsSameEffect.java @@ -44,9 +44,9 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final SpongeBlockChangeFlag flag, final int limit ) { final LevelChunkSection chunkSection = pipeline.getAffectedSection(); - final int x = oldState.pos.getX() & 15; - final int y = oldState.pos.getY() & 15; - final int z = oldState.pos.getZ() & 15; + final int x = oldState.pos().getX() & 15; + final int y = oldState.pos().getY() & 15; + final int z = oldState.pos().getZ() & 15; final BlockState currentState = chunkSection.getBlockState(x, y, z); if (!currentState.is(newState.getBlock())) { return new EffectResult(newState, true); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ChunkChangeCompleteEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ChunkChangeCompleteEffect.java index eecb265b5b7..426a2637da3 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ChunkChangeCompleteEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ChunkChangeCompleteEffect.java @@ -49,7 +49,7 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final LevelChunk chunk = pipeline.getAffectedChunk(); // this.unsaved = true; // Vanilla, we'll just call the accessor available - chunk.setUnsaved(true); - return new EffectResult(oldState.state, true); + chunk.markUnsaved(); + return new EffectResult(oldState.state(), true); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ExplodeBlockEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ExplodeBlockEffect.java index baaf064fadd..f47669e56ea 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ExplodeBlockEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/ExplodeBlockEffect.java @@ -56,9 +56,9 @@ public EffectResult processSideEffect( final PhaseContext<@NonNull ?> phaseContext = PhaseTracker.getInstance().getPhaseContext(); final ServerLevel world = pipeline.getServerWorld(); - final BlockPos pos = oldState.pos; + final BlockPos pos = oldState.pos(); if (phaseContext instanceof ExplosionContext) { - oldState.state.getBlock().wasExploded(world, pos, ((ExplosionContext) phaseContext).getExplosion()); + oldState.state().getBlock().wasExploded(world, pos, ((ExplosionContext) phaseContext).getExplosion()); } return EffectResult.NULL_PASS; diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyClientEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyClientEffect.java index 63f49fc4df6..db70695e346 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyClientEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyClientEffect.java @@ -56,7 +56,7 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli // if ((flags & 2) != 0 && (!this.isClientSide || (flags & 4) == 0) && (this.isClientSide || chunk.getLocationType() != null && chunk.getLocationType().isAtLeast(ChunkHolder.LocationType.TICKING))) { if (flag.notifyClients() && (chunk.getFullStatus().isOrAfter(FullChunkStatus.BLOCK_TICKING))) { // this.notifyBlockUpdate(pos, blockstate, newWorldState, flags); - world.sendBlockUpdated(oldState.pos, oldState.state, newState, flag.getRawFlag()); + world.sendBlockUpdated(oldState.pos(), oldState.state(), newState, flag.getRawFlag()); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyNeighborSideEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyNeighborSideEffect.java index 8702afdf483..f69722fdf70 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyNeighborSideEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/NotifyNeighborSideEffect.java @@ -53,10 +53,10 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli // if (!this.isClientSide && (flags & 1) != 0) { if (flag.updateNeighbors()) { // this.notifyNeighbors(pos, originalState.getBlock()); - world.blockUpdated(oldState.pos, oldState.state.getBlock()); + world.blockUpdated(oldState.pos(), oldState.state().getBlock()); if (newState.hasAnalogOutputSignal()) { // this.updateComparatorOutputLevel(pos, block); - world.updateNeighbourForOutputSignal(oldState.pos, newState.getBlock()); + world.updateNeighbourForOutputSignal(oldState.pos(), newState.getBlock()); } } return EffectResult.NULL_PASS; diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/OldBlockOnReplaceEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/OldBlockOnReplaceEffect.java index ffaaf61c60b..e635d85aa93 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/OldBlockOnReplaceEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/OldBlockOnReplaceEffect.java @@ -56,7 +56,7 @@ public EffectResult processSideEffect( // However, since we know we're not on the client (ChunkPipeline is not // used outside of server world context) // we can safely just do oldState.onRemove(this.level, var1, var2, var3). - oldState.state.onRemove(pipeline.getServerWorld(), oldState.pos, newState, flag.movingBlocks()); + oldState.state().onRemove(pipeline.getServerWorld(), oldState.pos(), newState, flag.movingBlocks()); return EffectResult.NULL_PASS; } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/PerformBlockDropsFromDestruction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/PerformBlockDropsFromDestruction.java index 0e6a2b9d443..c2f898c2c4a 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/PerformBlockDropsFromDestruction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/PerformBlockDropsFromDestruction.java @@ -46,7 +46,7 @@ public static PerformBlockDropsFromDestruction getInstance() { public EffectResult processSideEffect(final BlockPipeline pipeline, final PipelineCursor oldState, final BlockState newState, final SpongeBlockChangeFlag flag, final int limit ) { - Block.dropResources(oldState.state, pipeline.getServerWorld(), oldState.pos, oldState.tileEntity, oldState.destroyer, ItemStack.EMPTY); + Block.dropResources(oldState.state(), pipeline.getServerWorld(), oldState.pos(), oldState.tileEntity(), oldState.destroyer(), ItemStack.EMPTY); return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/RemoveTileEntityFromChunkEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/RemoveTileEntityFromChunkEffect.java index cc118789df8..ff4588db8da 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/RemoveTileEntityFromChunkEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/RemoveTileEntityFromChunkEffect.java @@ -46,11 +46,11 @@ public static RemoveTileEntityFromChunkEffect getInstance() { public EffectResult processSideEffect(final BlockPipeline pipeline, final PipelineCursor oldState, final BlockState newState, final SpongeBlockChangeFlag flag, final int limit ) { - final BlockEntity tileEntity = oldState.tileEntity; + final BlockEntity tileEntity = oldState.tileEntity(); if (tileEntity == null) { return EffectResult.NULL_RETURN; } - pipeline.getAffectedChunk().removeBlockEntity(oldState.pos); + pipeline.getAffectedChunk().removeBlockEntity(oldState.pos()); return EffectResult.NULL_RETURN; } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetAndRegisterBlockEntityToLevelChunk.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetAndRegisterBlockEntityToLevelChunk.java index 7733123bc27..196a7c20bf2 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetAndRegisterBlockEntityToLevelChunk.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetAndRegisterBlockEntityToLevelChunk.java @@ -51,8 +51,8 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final int limit ) { final ServerLevel serverWorld = pipeline.getServerWorld(); - final @Nullable BlockEntity blockEntity = oldState.tileEntity; - final BlockPos pos = oldState.pos; + final @Nullable BlockEntity blockEntity = oldState.tileEntity(); + final BlockPos pos = oldState.pos(); if (serverWorld.isOutsideBuildHeight(pos)) { return EffectResult.NULL_RETURN; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetBlockToChunkSectionEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetBlockToChunkSectionEffect.java index 6db0b84c8fa..678aa48cff2 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetBlockToChunkSectionEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SetBlockToChunkSectionEffect.java @@ -46,9 +46,9 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final SpongeBlockChangeFlag flag, final int limit ) { final LevelChunkSection chunkSection = pipeline.getAffectedSection(); - final int x = oldState.pos.getX() & 15; - final int y = oldState.pos.getY() & 15; - final int z = oldState.pos.getZ() & 15; + final int x = oldState.pos().getX() & 15; + final int y = oldState.pos().getY() & 15; + final int z = oldState.pos().getZ() & 15; final BlockState oldStateReturned = chunkSection.setBlockState(x, y, z, newState); if (oldStateReturned == newState) { return EffectResult.NULL_RETURN; diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SpawnDestructBlocksEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SpawnDestructBlocksEffect.java index b167636ec06..3e144a2249d 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SpawnDestructBlocksEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/SpawnDestructBlocksEffect.java @@ -54,9 +54,9 @@ public EffectResult processSideEffect( final int limit ) { final ServerLevel world = pipeline.getServerWorld(); - final BlockPos pos = oldState.pos; + final BlockPos pos = oldState.pos(); - final List drops = oldState.drops; + final List drops = oldState.drops(); drops.forEach(drop -> Block.popResource(world, pos, drop)); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateChunkLightManagerEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateChunkLightManagerEffect.java index b27cfad1ec7..4cedc0c5810 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateChunkLightManagerEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateChunkLightManagerEffect.java @@ -51,7 +51,7 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final boolean wasEmpty = pipeline.wasEmpty(); final boolean isStillEmpty = chunkSection.hasOnlyAir(); if (wasEmpty != isStillEmpty) { - pipeline.getServerWorld().getChunkSource().getLightEngine().updateSectionStatus(oldState.pos, isStillEmpty); + pipeline.getServerWorld().getChunkSource().getLightEngine().updateSectionStatus(oldState.pos(), isStillEmpty); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateConnectingBlocksEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateConnectingBlocksEffect.java index ca520619017..28049195867 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateConnectingBlocksEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateConnectingBlocksEffect.java @@ -48,12 +48,12 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final BlockState newState, final SpongeBlockChangeFlag flag, final int limit ) { final ServerLevel world = pipeline.getServerWorld(); - final BlockPos pos = oldState.pos; + final BlockPos pos = oldState.pos(); if (flag.updateNeighboringShapes() && limit > 0) { // int i = p_241211_3_ & -34; // Vanilla negates 34 to flip neighbor notification and and "state drops" final int withoutNeighborDropsAndNestedNeighborUpdates = flag.asNestedNeighborUpdates().getRawFlag(); // blockstate.updateIndirectNeighbourShapes(this, p_241211_1_, i, p_241211_4_ - 1); - oldState.state.updateIndirectNeighbourShapes(world, pos, withoutNeighborDropsAndNestedNeighborUpdates, limit - 1); + oldState.state().updateIndirectNeighbourShapes(world, pos, withoutNeighborDropsAndNestedNeighborUpdates, limit - 1); // p_241211_2_.updateNeighbourShapes(this, p_241211_1_, i, p_241211_4_ - 1); newState.updateNeighbourShapes(world, pos, withoutNeighborDropsAndNestedNeighborUpdates, limit - 1); // p_241211_2_.updateIndirectNeighbourShapes(this, p_241211_1_, i, p_241211_4_ - 1); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateHeightMapEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateHeightMapEffect.java index 00693ff8e4a..de2b04b4949 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateHeightMapEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateHeightMapEffect.java @@ -53,9 +53,9 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli if (heightMap == null) { throw new IllegalStateException("Heightmap dereferenced!"); } - final int x = oldState.pos.getX() & 15; - final int y = oldState.pos.getY(); - final int z = oldState.pos.getZ() & 15; + final int x = oldState.pos().getX() & 15; + final int y = oldState.pos().getY(); + final int z = oldState.pos().getZ() & 15; heightMap.get(Heightmap.Types.MOTION_BLOCKING).update(x, y, z, newState); heightMap.get(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES).update(x, y, z, newState); heightMap.get(Heightmap.Types.OCEAN_FLOOR).update(x, y, z, newState); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateLightSideEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateLightSideEffect.java index c3f799992bb..b8962419f59 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateLightSideEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateLightSideEffect.java @@ -25,9 +25,10 @@ package org.spongepowered.common.event.tracking.context.transaction.effect; import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.profiling.Profiler; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.lighting.LightEngine; import org.spongepowered.common.event.tracking.context.transaction.pipeline.BlockPipeline; import org.spongepowered.common.event.tracking.context.transaction.pipeline.PipelineCursor; import org.spongepowered.common.world.SpongeBlockChangeFlag; @@ -53,10 +54,8 @@ public EffectResult processSideEffect( if (!flag.updateLighting()) { return EffectResult.NULL_PASS; } - final int originalOpactiy = oldState.opacity; final ServerLevel serverWorld = pipeline.getServerWorld(); - final LevelChunk chunk = pipeline.getAffectedChunk(); - final BlockState currentState = chunk.getBlockState(oldState.pos); + final BlockState currentState = pipeline.getAffectedChunk().getBlockState(oldState.pos()); // local variable notes: // var2 = oldState.state // var3 = currentState @@ -70,24 +69,26 @@ public EffectResult processSideEffect( // || var2.useShapeForLightOcclusion() // ) // ) { - if (oldState.state != currentState - && (currentState.getLightBlock(serverWorld, oldState.pos) != originalOpactiy - || currentState.getLightEmission() != oldState.state.getLightEmission() - || currentState.useShapeForLightOcclusion() - || oldState.state.useShapeForLightOcclusion() - )) { - final int x = oldState.pos.getX() & 15; - final int y = oldState.pos.getY(); - final int z = oldState.pos.getZ() & 15; + if (LightEngine.hasDifferentLightProperties(oldState.state(), currentState)) { // ProfilerFiller $$12 = this.level.getProfiler(); - final ProfilerFiller profiler = serverWorld.getProfiler(); - profiler.push("updateSkyLightSources"); - // this.skyLightSources.update(this, x, y, z); - chunk.getSkyLightSources().update(chunk, x, y, z); - profiler.popPush("queueCheckLight"); - // this.level.getChunkProvider().getLightManager().checkBlock(pos); - serverWorld.getChunkSource().getLightEngine().checkBlock(oldState.pos); - profiler.pop(); + final ProfilerFiller filler = Profiler.get(); + + filler.push("updateSkyLightSources"); +// this.skyLightSources.update(this, $$6, $$3, $$8); + final var pos = oldState.pos(); + final var x = pos.getX() & 15; + final var y = pos.getY() & 15; + final var z = pos.getZ() & 15; + + final var levelChunk = serverWorld.getChunk(pos); + levelChunk.getSkyLightSources().update(levelChunk, x, y, z); +// serverWorld.getChunkSource().update(this, $$6, $$3, $$8); + // this.profiler.startSection("queueCheckLight"); + filler.push("queueCheckLight"); + // this.getChunkProvider().getLightManager().checkBlock(pos); + serverWorld.getChunkSource().getLightEngine().checkBlock(pos); + // this.profiler.endSection(); + filler.pop(); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateOrCreateNewTileEntityPostPlacementEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateOrCreateNewTileEntityPostPlacementEffect.java index 0ecc8ef372d..aec887a346a 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateOrCreateNewTileEntityPostPlacementEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateOrCreateNewTileEntityPostPlacementEffect.java @@ -55,12 +55,12 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final ServerLevel serverWorld = pipeline.getServerWorld(); final LevelChunk chunk = pipeline.getAffectedChunk(); if (((BlockStateBridge) newState).bridge$hasTileEntity()) { - final @Nullable BlockEntity maybeNewTileEntity = chunk.getBlockEntity(oldState.pos, LevelChunk.EntityCreationType.CHECK); + final @Nullable BlockEntity maybeNewTileEntity = chunk.getBlockEntity(oldState.pos(), LevelChunk.EntityCreationType.CHECK); if (maybeNewTileEntity == null) { // var15 = ((EntityBlock)var12).newBlockEntity(var1, var2); // Vanilla // tileentity1 = state.createTileEntity(this.world); // Forge // We cast to our bridge for easy access - @Nullable final BlockEntity newBlockEntity = ((BlockStateBridge) newState).bridge$createNewTileEntity(serverWorld, oldState.pos); + @Nullable final BlockEntity newBlockEntity = ((BlockStateBridge) newState).bridge$createNewTileEntity(serverWorld, oldState.pos()); if (newBlockEntity != null) { chunk.addAndRegisterBlockEntity(newBlockEntity); } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateWorldRendererEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateWorldRendererEffect.java index 67608577360..41a44be0d32 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateWorldRendererEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/UpdateWorldRendererEffect.java @@ -45,8 +45,8 @@ public static UpdateWorldRendererEffect getInstance() { public EffectResult processSideEffect(final BlockPipeline pipeline, final PipelineCursor oldState, final BlockState newState, final SpongeBlockChangeFlag flag, final int limit ) { - if (oldState.state != newState) { - pipeline.getServerWorld().setBlocksDirty(oldState.pos, oldState.state, newState); + if (oldState.state() != newState) { + pipeline.getServerWorld().setBlocksDirty(oldState.pos(), oldState.state(), newState); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldBlockChangeCompleteEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldBlockChangeCompleteEffect.java index 3afdc4e476f..58491086353 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldBlockChangeCompleteEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldBlockChangeCompleteEffect.java @@ -46,8 +46,8 @@ public EffectResult processSideEffect(final BlockPipeline pipeline, final Pipeli final SpongeBlockChangeFlag flag, final int limit ) { if (flag.notifyPathfinding()) { - pipeline.getServerWorld().onBlockStateChange(oldState.pos, oldState.state, newState); + pipeline.getServerWorld().onBlockStateChange(oldState.pos(), oldState.state(), newState); } - return new EffectResult(oldState.state, true); + return new EffectResult(oldState.state(), true); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldDestroyBlockLevelEffect.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldDestroyBlockLevelEffect.java index d1dafaa2841..86e5e16119c 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldDestroyBlockLevelEffect.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/effect/WorldDestroyBlockLevelEffect.java @@ -47,8 +47,8 @@ public static WorldDestroyBlockLevelEffect getInstance() { public EffectResult processSideEffect(final BlockPipeline pipeline, final PipelineCursor oldState, final BlockState newState, final SpongeBlockChangeFlag flag, final int limit ) { - if (!(oldState.state.getBlock() instanceof BaseFireBlock)) { - pipeline.getServerWorld().levelEvent(2001, oldState.pos, Block.getId(oldState.state)); + if (!(oldState.state().getBlock() instanceof BaseFireBlock)) { + pipeline.getServerWorld().levelEvent(2001, oldState.pos(), Block.getId(oldState.state())); } return EffectResult.NULL_PASS; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/ContainerBasedTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/ContainerBasedTransaction.java index 52811cbb503..3bd55e1b709 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/ContainerBasedTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/ContainerBasedTransaction.java @@ -284,11 +284,11 @@ private void handleCrafting(final Player player, final ClickContainerEvent event } private void handleCraftingPreview(final Player player, final ClickContainerEvent event) { - if (this.craftingInventory != null) { + if (this.craftingInventory != null && player instanceof ServerPlayer sp) { // TODO push event to cause? // TODO prevent event when there is no preview? final SlotTransaction previewTransaction = this.getPreviewTransaction(this.craftingInventory.result(), event.transactions()); - final var recipe = player.level().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftingContainer.asCraftInput(), player.level()); + final var recipe = sp.serverLevel().recipeAccess().getRecipeFor(RecipeType.CRAFTING, this.craftingContainer.asCraftInput(), player.level()); final CraftItemEvent.Preview previewEvent = SpongeEventFactory.createCraftItemEventPreview(event.cause(), (Container) this.menu, this.craftingInventory, event.cursorTransaction(), previewTransaction, recipe.map(RecipeHolder::value).map(CraftingRecipe.class::cast), recipe.map(h -> h.id()).map(ResourceKey.class::cast), Optional.empty(), event.transactions()); SpongeCommon.post(previewEvent); diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/CraftingPreviewTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/CraftingPreviewTransaction.java index 2fb3bf724e7..80a4fc5c600 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/CraftingPreviewTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/CraftingPreviewTransaction.java @@ -71,12 +71,12 @@ public Optional parentAbsorber() { @Override Optional createInventoryEvent(final List slotTransactions, final List entities, final PhaseContext<@NonNull ?> context, final Cause currentCause) { - if (slotTransactions.isEmpty()) { + if (slotTransactions.isEmpty() || !(this.player instanceof ServerPlayer sp)) { return Optional.empty(); } final ItemStackSnapshot cursor = ItemStackUtil.snapshotOf(this.player.containerMenu.getCarried()); final SlotTransaction previewTransaction = this.getPreviewTransaction(this.craftingInventory.result(), slotTransactions); - final var recipe = this.player.level().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftSlots.asCraftInput(), this.player.level()); + final var recipe = sp.serverLevel().recipeAccess().getRecipeFor(RecipeType.CRAFTING, this.craftSlots.asCraftInput(), this.player.level()); final CraftItemEvent.Preview event = SpongeEventFactory.createCraftItemEventPreview(currentCause, ContainerUtil.fromNative(this.menu), this.craftingInventory, new Transaction<>(cursor, cursor), previewTransaction, recipe.map(RecipeHolder::value).map(CraftingRecipe.class::cast), diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/PlaceRecipeTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/PlaceRecipeTransaction.java index b64b10b0236..ab486784a6c 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/PlaceRecipeTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/PlaceRecipeTransaction.java @@ -105,7 +105,7 @@ boolean isContainerEventAllowed(final PhaseContext<@Nullable ?> context) { if (!(context instanceof InventoryPacketContext)) { return false; } - final int containerId = ((InventoryPacketContext) context).getPacket().getContainerId(); + final int containerId = ((InventoryPacketContext) context).getPacket().containerId(); return containerId != this.player.containerMenu.containerId; } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SelectTradeTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SelectTradeTransaction.java index 8d5f9eaf98e..c5f6a2ad3c1 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SelectTradeTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SelectTradeTransaction.java @@ -91,7 +91,7 @@ boolean isContainerEventAllowed(final PhaseContext<@NonNull ?> context) { if (!(context instanceof InventoryPacketContext)) { return false; } - final int containerId = ((InventoryPacketContext) context).getPacket().getContainerId(); + final int containerId = ((InventoryPacketContext) context).getPacket().containerId(); return containerId != this.player.containerMenu.containerId; } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SetCarriedItemTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SetCarriedItemTransaction.java index 84a00d5bc79..00657ace3cc 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SetCarriedItemTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/SetCarriedItemTransaction.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.tracking.context.transaction.inventory; -import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ClientboundSetHeldSlotPacket; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import org.checkerframework.checker.nullness.qual.NonNull; @@ -76,7 +76,7 @@ Optional createInventoryEvent(final List @Override public void restore(final PhaseContext<@NonNull ?> context, final ChangeInventoryEvent event) { - this.player.connection.send(new ClientboundSetCarriedItemPacket(this.prevSlotId)); + this.player.connection.send(new ClientboundSetHeldSlotPacket(this.prevSlotId)); this.player.getInventory().selected = this.prevSlotId; this.handleEventResults(this.player, event); } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/ChunkPipeline.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/ChunkPipeline.java index a6b34239bc1..accd704f681 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/ChunkPipeline.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/ChunkPipeline.java @@ -111,10 +111,10 @@ public LevelChunkSection getAffectedSection() { return null; } final ServerLevel serverWorld = this.serverWorld.get(); - final int oldOpacity = currentState.getLightBlock(serverWorld, pos); + final int oldOpacity = currentState.getLightBlock(); final SpongeBlockChangeFlag flag = this.transaction.getBlockChangeFlag(); final @Nullable BlockEntity existing = this.chunkSupplier.get().getBlockEntity(pos, LevelChunk.EntityCreationType.CHECK); - PipelineCursor formerState = new PipelineCursor(currentState, oldOpacity, pos, existing, (Entity) null, limit); + PipelineCursor formerState = new PipelineCursor(currentState, pos, existing, (Entity) null, limit); for (final ResultingTransactionBySideEffect effect : this.chunkEffects) { try (final EffectTransactor ignored = context.getTransactor().pushEffect(effect)) { @@ -128,8 +128,8 @@ public LevelChunkSection getAffectedSection() { if (result.hasResult) { return result.resultingState; } - if (formerState.drops.isEmpty() && !result.drops.isEmpty()) { - formerState = new PipelineCursor(currentState, oldOpacity, pos, existing, null, result.drops, limit); + if (formerState.drops().isEmpty() && !result.drops.isEmpty()) { + formerState = new PipelineCursor(currentState, pos, existing, null, result.drops, limit); } } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/PipelineCursor.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/PipelineCursor.java index 6681d1e055c..4b3da670861 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/PipelineCursor.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/PipelineCursor.java @@ -33,57 +33,20 @@ import java.util.Collections; import java.util.List; -import java.util.StringJoiner; -public final class PipelineCursor { - public final BlockState state; - public final int opacity; - public final BlockPos pos; - public final @Nullable BlockEntity tileEntity; - public final @Nullable Entity destroyer; - public final List drops; - public final int limit; - - public PipelineCursor(final BlockState state, final int opacity, final BlockPos pos, - final @Nullable BlockEntity tileEntity, - final @Nullable Entity destroyer, final int limit +public record PipelineCursor( + BlockState state, + BlockPos pos, + @Nullable BlockEntity tileEntity, + @Nullable Entity destroyer, + List drops, + int limit +) { + public PipelineCursor(final BlockState state, final BlockPos pos, + final @Nullable BlockEntity tileEntity, + final @Nullable Entity destroyer, final int limit ) { - this.state = state; - this.opacity = opacity; - this.pos = pos; - this.tileEntity = tileEntity; - this.destroyer = destroyer; - this.drops = Collections.emptyList(); - this.limit = limit; + this(state, pos, tileEntity, destroyer, Collections.emptyList(), limit); } - public PipelineCursor(final BlockState state, final int opacity, final BlockPos pos, - final @Nullable BlockEntity tileEntity, - final @Nullable Entity destroyer, - final List drops, - final int limit - ) { - this.state = state; - this.opacity = opacity; - this.pos = pos; - this.tileEntity = tileEntity; - this.drops = drops; - this.limit = limit; - this.destroyer = destroyer; - } - - @Override - public String toString() { - return new StringJoiner( - ", ", - PipelineCursor.class.getSimpleName() + "[", - "]" - ) - .add("state=" + this.state) - .add("opacity=" + this.opacity) - .add("pos=" + this.pos) - .add("tileEntity=" + this.tileEntity) - .add("drops=" + this.drops) - .toString(); - } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/TileEntityPipeline.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/TileEntityPipeline.java index ac6fdd6ac4b..2a5dc819629 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/TileEntityPipeline.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/TileEntityPipeline.java @@ -103,18 +103,17 @@ public boolean processEffects(final PhaseContext context, final PipelineCurso final EffectResult result = effect.effect.processSideEffect( this, currentCursor, - currentCursor.state, + currentCursor.state(), (SpongeBlockChangeFlag) BlockChangeFlags.NONE, - currentCursor.limit + currentCursor.limit() ); - if (result.resultingState != currentCursor.state) { + if (result.resultingState != currentCursor.state()) { currentCursor = new PipelineCursor( result.resultingState, - currentCursor.opacity, - currentCursor.pos, - currentCursor.tileEntity, - currentCursor.destroyer, - currentCursor.limit + currentCursor.pos(), + currentCursor.tileEntity(), + currentCursor.destroyer(), + currentCursor.limit() ); } if (result.hasResult) { diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/WorldPipeline.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/WorldPipeline.java index 81165311770..fe5a8e9b355 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/WorldPipeline.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/pipeline/WorldPipeline.java @@ -98,8 +98,8 @@ public boolean processEffects(final PhaseContext context, final BlockState cu if (oldState == null) { return false; } - final int oldOpacity = oldState.getLightBlock(serverWorld, pos); - PipelineCursor formerState = new PipelineCursor(oldState, oldOpacity, pos, existing, destroyer, limit); + final int oldOpacity = oldState.getLightBlock(); + PipelineCursor formerState = new PipelineCursor(oldState, pos, existing, destroyer, limit); for (final ResultingTransactionBySideEffect effect : this.worldEffects) { try (final EffectTransactor ignored = context.getTransactor().pushEffect(effect)) { @@ -113,8 +113,8 @@ public boolean processEffects(final PhaseContext context, final BlockState cu if (result.hasResult) { return result.resultingState != null; } - if (formerState.drops.isEmpty() && !result.drops.isEmpty()) { - formerState = new PipelineCursor(oldState, oldOpacity, pos, existing, formerState.destroyer, result.drops, limit); + if (formerState.drops().isEmpty() && !result.drops.isEmpty()) { + formerState = new PipelineCursor(oldState, pos, existing, formerState.destroyer(), result.drops, limit); } } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/type/BlockTransactionType.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/type/BlockTransactionType.java index b8605f062fe..965ea025c85 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/type/BlockTransactionType.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/type/BlockTransactionType.java @@ -63,7 +63,7 @@ protected void consumeEventsAndMarker( eventsByWorld.asMap().forEach((key, events) -> { final Optional serverWorld = ((SpongeServer) SpongeCommon.server()).worldManager().world(key); - if (!serverWorld.isPresent()) { + if (serverWorld.isEmpty()) { return; } @@ -85,7 +85,7 @@ protected void consumeEventsAndMarker( final Operation operation = context.getBlockOperation(original, result); final BlockTransactionReceipt eventTransaction = new BlockTransactionReceipt(original, result, operation); transactions.add(eventTransaction); - context.postBlockTransactionApplication(original.blockChange, eventTransaction); + context.postBlockTransactionApplication(serverWorld.get(), original.blockChange, eventTransaction); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/general/CommandState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/general/CommandState.java index 43a9b373744..d365efa21f5 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/general/CommandState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/general/CommandState.java @@ -35,6 +35,7 @@ import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.cause.entity.SpawnType; import org.spongepowered.api.event.cause.entity.SpawnTypes; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.event.tracking.PhaseTracker; @@ -66,7 +67,7 @@ public BiConsumer getFrameMod @Override public void postBlockTransactionApplication( - final CommandPhaseContext context, final BlockChange blockChange, + final CommandPhaseContext context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt transaction ) { // We want to investigate if there is a user on the cause stack diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionContext.java b/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionContext.java index 0c901223d8c..eb40f98eba9 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionContext.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionContext.java @@ -26,17 +26,17 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.ServerExplosion; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.common.accessor.world.level.ExplosionAccessor; +import org.spongepowered.common.accessor.world.level.ServerExplosionAccessor; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.PrettyPrinter; public final class ExplosionContext extends GeneralPhaseContext { - private Explosion explosion; + private ServerExplosion explosion; public ExplosionContext(PhaseTracker tracker) { super(GeneralPhase.State.EXPLOSION, tracker); @@ -57,12 +57,12 @@ public ExplosionContext potentialExplosionSource(final ServerLevel worldServer, return this; } - public ExplosionContext explosion(final Explosion explosion) { + public ExplosionContext explosion(final ServerExplosion explosion) { this.explosion = explosion; return this; } - public Explosion getExplosion() { + public ServerExplosion getExplosion() { return this.explosion; } @@ -88,12 +88,10 @@ protected boolean isRunaway(final PhaseContext phaseContext) { if (phaseContext.getClass() != ExplosionContext.class) { return false; } - final ExplosionAccessor otherExplosion = (ExplosionAccessor) ((ExplosionContext) phaseContext).explosion; - final ExplosionAccessor thisExplosion = (ExplosionAccessor) this.explosion; + final ServerExplosionAccessor otherExplosion = (ServerExplosionAccessor) ((ExplosionContext) phaseContext).explosion; + final ServerExplosionAccessor thisExplosion = (ServerExplosionAccessor) this.explosion; return otherExplosion.accessor$level() == thisExplosion.accessor$level() - && otherExplosion.accessor$x() == thisExplosion.accessor$x() - && otherExplosion.accessor$y() == thisExplosion.accessor$y() - && otherExplosion.accessor$z() == thisExplosion.accessor$z(); + && ((ExplosionContext) phaseContext).explosion.center().equals(this.explosion.center()); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionState.java index 141853b01aa..26e10b29deb 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/general/ExplosionState.java @@ -39,7 +39,7 @@ import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.util.Tuple; -import org.spongepowered.common.accessor.world.level.ExplosionAccessor; +import org.spongepowered.common.accessor.world.level.ServerExplosionAccessor; import org.spongepowered.common.bridge.CreatorTrackedBridge; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.TrackingUtil; @@ -88,8 +88,8 @@ public void populateLootContext(final ExplosionContext phaseContext, final LootP final Explosion explosion = phaseContext.getExplosion(); lootBuilder.withOptionalParameter(LootContextParams.THIS_ENTITY, explosion.getDirectSourceEntity()); - if (((ExplosionAccessor) explosion).accessor$blockInteraction() == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY) { - lootBuilder.withParameter(LootContextParams.EXPLOSION_RADIUS, ((ExplosionAccessor) explosion).accessor$radius()); + if (((ServerExplosionAccessor) explosion).accessor$blockInteraction() == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY) { + lootBuilder.withParameter(LootContextParams.EXPLOSION_RADIUS, ((ServerExplosionAccessor) explosion).accessor$radius()); } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PacketCommandState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PacketCommandState.java index 30041525395..57d93ca2df8 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PacketCommandState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PacketCommandState.java @@ -37,6 +37,7 @@ import org.spongepowered.api.event.cause.entity.SpawnTypes; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.util.Tuple; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.TrackingUtil; import org.spongepowered.common.event.tracking.context.transaction.GameTransaction; @@ -69,7 +70,7 @@ public BiConsumer getFr @Override public void postBlockTransactionApplication( - final PlayerCommandPhaseContext context, final BlockChange blockChange, + final PlayerCommandPhaseContext context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt transaction ) { // We want to investigate if there is a user on the cause stack diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PlaceBlockPacketState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PlaceBlockPacketState.java index 5ba2f9e9330..660f5ec66da 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PlaceBlockPacketState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/PlaceBlockPacketState.java @@ -87,7 +87,7 @@ public void populateContext(final net.minecraft.server.level.ServerPlayer player @Override public void postBlockTransactionApplication( - final BasicPacketContext context, final BlockChange blockChange, + final BasicPacketContext context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt transaction ) { TrackingUtil.associateTrackerToTarget(blockChange, transaction, ((ServerPlayer) context.getPacketPlayer()).uniqueId()); diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/UseItemPacketState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/UseItemPacketState.java index a07ab05571f..887044374d0 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/UseItemPacketState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/player/UseItemPacketState.java @@ -41,6 +41,7 @@ import org.spongepowered.api.event.cause.entity.SpawnTypes; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.event.tracking.PhaseTracker; @@ -91,7 +92,7 @@ public void populateContext( @Override public void postBlockTransactionApplication( - final BasicPacketContext context, final BlockChange blockChange, + final BasicPacketContext context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt transaction ) { final ServerPlayer player = context.getSpongePlayer(); diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockEventTickPhaseState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockEventTickPhaseState.java index ab67914b419..c0bd38061b6 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockEventTickPhaseState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockEventTickPhaseState.java @@ -34,6 +34,7 @@ import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.cause.entity.SpawnType; import org.spongepowered.api.event.cause.entity.SpawnTypes; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.world.level.TrackableBlockEventDataBridge; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; @@ -84,7 +85,7 @@ public void associateNeighborStateNotifier( @Override public void postBlockTransactionApplication( - final BlockEventTickContext context, final BlockChange blockChange, + final BlockEventTickContext context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt receipt ) { final Block block = (Block) receipt.originalBlock().state().type(); diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockTickPhaseState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockTickPhaseState.java index 26c145f1376..8eee3c662b6 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockTickPhaseState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/BlockTickPhaseState.java @@ -26,7 +26,7 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; -import net.minecraft.world.level.Level; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; @@ -73,9 +73,9 @@ public BlockChange associateBlockChangeWithSnapshot( if (newBlock instanceof BonemealableBlock) { return BlockChange.GROW; } else if (phaseContext.tickingBlock instanceof final StemBlock stemBlock) { - final Registry registry = ((Level) phaseContext.world).registryAccess().registryOrThrow(Registries.BLOCK); - final @Nullable Block fruitBlock = registry.get(((StemBlockAccessor) stemBlock).accessor$fruit()); - final @Nullable Block attachedStemBlock = registry.get(((StemBlockAccessor) stemBlock).accessor$attachedStem()); + final Registry registry = ((ServerLevel) phaseContext.world).registryAccess().lookupOrThrow(Registries.BLOCK); + final @Nullable Block fruitBlock = registry.getValue(((StemBlockAccessor) stemBlock).accessor$fruit()); + final @Nullable Block attachedStemBlock = registry.getValue(((StemBlockAccessor) stemBlock).accessor$attachedStem()); if (newBlock == fruitBlock || newBlock == attachedStemBlock) { return BlockChange.GROW; } diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/EntityTickPhaseState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/EntityTickPhaseState.java index 27405e72373..962b8c0cbd2 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/EntityTickPhaseState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/EntityTickPhaseState.java @@ -40,6 +40,7 @@ import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.cause.entity.SpawnType; import org.spongepowered.api.event.cause.entity.SpawnTypes; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.accessor.world.entity.decoration.ItemFrameAccessor; import org.spongepowered.common.bridge.world.entity.EntityBridge; import org.spongepowered.common.bridge.world.entity.TrackableEntityBridge; @@ -124,7 +125,7 @@ protected EntityTickContext createNewContext(final PhaseTracker tracker) { @Override public void postBlockTransactionApplication( - final EntityTickContext context, final BlockChange blockChange, + final EntityTickContext context, final ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt transaction ) { if (blockChange == BlockChange.BREAK) { @@ -159,12 +160,11 @@ public void postBlockTransactionApplication( return false; }); for (final HangingEntity entityHanging : hangingEntities) { - if (entityHanging instanceof ItemFrame) { - final ItemFrame itemFrame = (ItemFrame) entityHanging; - if (!itemFrame.isRemoved()) { - ((ItemFrameAccessor) itemFrame).invoker$dropItem((net.minecraft.world.entity.Entity) tickingEntity, true); + if (entityHanging instanceof ItemFrame iframe) { + if (!iframe.isRemoved()) { + ((ItemFrameAccessor) iframe).invoker$dropItem((ServerLevel) serverWorld, (net.minecraft.world.entity.Entity) tickingEntity, true); } - itemFrame.remove(net.minecraft.world.entity.Entity.RemovalReason.DISCARDED); + iframe.remove(net.minecraft.world.entity.Entity.RemovalReason.DISCARDED); } } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/LocationBasedTickPhaseState.java b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/LocationBasedTickPhaseState.java index edb6df776fb..c6c59b088f8 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/tick/LocationBasedTickPhaseState.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/tick/LocationBasedTickPhaseState.java @@ -35,6 +35,7 @@ import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.world.LocatableBlock; import org.spongepowered.api.world.World; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.world.TrackedWorldBridge; import org.spongepowered.common.bridge.world.level.TrackableBlockEventDataBridge; @@ -122,7 +123,7 @@ public void appendContextPreExplosion(final ExplosionContext explosionContext, f @Override public void postBlockTransactionApplication( - final T context, final BlockChange blockChange, + final T context, ServerWorld serverWorld, final BlockChange blockChange, final BlockTransactionReceipt receipt ) { // If we do not have a notifier at this point then there is no need to attempt to retrieve one from the chunk diff --git a/src/main/java/org/spongepowered/common/inventory/lens/impl/comp/CraftingGridInventoryLens.java b/src/main/java/org/spongepowered/common/inventory/lens/impl/comp/CraftingGridInventoryLens.java index 6edb093807f..3dc828381ac 100644 --- a/src/main/java/org/spongepowered/common/inventory/lens/impl/comp/CraftingGridInventoryLens.java +++ b/src/main/java/org/spongepowered/common/inventory/lens/impl/comp/CraftingGridInventoryLens.java @@ -28,7 +28,7 @@ import net.minecraft.world.inventory.InventoryMenu; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.crafting.CraftingGridInventory; -import org.spongepowered.common.accessor.world.inventory.CraftingMenuAccessor; +import org.spongepowered.common.accessor.world.inventory.AbstractCraftingMenuAccessor; import org.spongepowered.common.inventory.fabric.Fabric; import org.spongepowered.common.inventory.fabric.OffsetFabric; import org.spongepowered.common.inventory.lens.impl.AbstractLens; @@ -70,7 +70,7 @@ public Inventory getAdapter(Fabric fabric, Inventory parent) { return ((CraftingGridInventory) ((InventoryMenu) fabric).getCraftSlots()); } if (fabric instanceof CraftingMenu) { - return ((CraftingGridInventory) ((CraftingMenuAccessor) fabric).accessor$craftSlots()); + return ((CraftingGridInventory) ((AbstractCraftingMenuAccessor) fabric).accessor$craftSlots()); } throw new IllegalStateException(fabric.getClass().getName() + " is not a known CraftingGridInventory."); } diff --git a/src/main/java/org/spongepowered/common/inventory/lens/impl/slot/EquipmentSlotLens.java b/src/main/java/org/spongepowered/common/inventory/lens/impl/slot/EquipmentSlotLens.java index e63fe04826a..c741fa7967d 100644 --- a/src/main/java/org/spongepowered/common/inventory/lens/impl/slot/EquipmentSlotLens.java +++ b/src/main/java/org/spongepowered/common/inventory/lens/impl/slot/EquipmentSlotLens.java @@ -24,8 +24,8 @@ */ package org.spongepowered.common.inventory.lens.impl.slot; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.Equipable; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.equipment.EquipmentType; @@ -52,8 +52,8 @@ private static FilteringSlotLens.ItemStackFilter equipmentTypeFilter(EquipmentTy if (item.isEmpty()) { return true; } - final var equipable = Equipable.get(ItemStackUtil.fromLikeToNative(item)); - final var itemSlotType = equipable != null ? equipable.getEquipmentSlot() : EquipmentSlot.MAINHAND; + final var equippable = ItemStackUtil.fromLikeToNative(item).get(DataComponents.EQUIPPABLE); + final var itemSlotType = equippable != null ? equippable.slot() : EquipmentSlot.MAINHAND; return itemSlotType == (Object) type; }; } diff --git a/src/main/java/org/spongepowered/common/inventory/util/InventoryUtil.java b/src/main/java/org/spongepowered/common/inventory/util/InventoryUtil.java index b6c489f060c..dbdcfcdbe12 100644 --- a/src/main/java/org/spongepowered/common/inventory/util/InventoryUtil.java +++ b/src/main/java/org/spongepowered/common/inventory/util/InventoryUtil.java @@ -51,9 +51,8 @@ import org.spongepowered.api.item.recipe.crafting.RecipeInput; import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.accessor.world.inventory.CraftingMenuAccessor; +import org.spongepowered.common.accessor.world.inventory.AbstractCraftingMenuAccessor; import org.spongepowered.common.accessor.world.inventory.SmithingMenuAccessor; -import org.spongepowered.common.accessor.world.inventory.StonecutterMenuAccessor; import org.spongepowered.common.bridge.world.inventory.container.TrackedInventoryBridge; import org.spongepowered.common.entity.player.SpongeUserData; import org.spongepowered.common.event.tracking.context.transaction.EffectTransactor; @@ -97,9 +96,9 @@ public static Optional toCraftingInput(final Invent case AbstractFurnaceBlockEntity furnace -> new SingleRecipeInput(furnace.getItem(0)); case CampfireBlockEntity campfire -> campfire.getItems().stream().filter(stack -> !stack.isEmpty()).findFirst() .map(SingleRecipeInput::new).orElse(null); - case CraftingMenuAccessor menu -> menu.accessor$craftSlots().asCraftInput(); + case AbstractCraftingMenuAccessor menu -> menu.accessor$craftSlots().asCraftInput(); case InventoryMenu menu -> menu.getCraftSlots().asCraftInput(); - case StonecutterMenu menu -> StonecutterMenuAccessor.invoker$createRecipeInput(menu.container); + case StonecutterMenu menu -> new SingleRecipeInput(menu.container.getItem(0)); case SmithingMenuAccessor menu -> menu.invoker$createRecipeInput(); default -> null; }; diff --git a/src/main/java/org/spongepowered/common/item/SpongeToolRuleFactory.java b/src/main/java/org/spongepowered/common/item/SpongeToolRuleFactory.java index 5850e53f41d..5ce79c4d06f 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeToolRuleFactory.java +++ b/src/main/java/org/spongepowered/common/item/SpongeToolRuleFactory.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item; +import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.tags.TagKey; @@ -41,12 +42,16 @@ public class SpongeToolRuleFactory implements ToolRule.Factory { @Override public ToolRule minesAndDrops(final List blocks, final double speed) { - return (ToolRule) (Object) Tool.Rule.minesAndDrops(blocks.stream().map(Block.class::cast).toList(), (float) speed); + // TODO is Holder::direct allowed here? + final var holderSet = HolderSet.direct(blocks.stream().map(Block.class::cast).map(Holder::direct).toList()); + return (ToolRule) (Object) Tool.Rule.minesAndDrops(holderSet, (float) speed); } @Override public ToolRule minesAndDrops(final Tag blockTypeTag, final double speed) { - return (ToolRule) (Object) Tool.Rule.minesAndDrops((TagKey) (Object) blockTypeTag, (float) speed); + final var tag = (TagKey) (Object) blockTypeTag; + final var holderSet = BuiltInRegistries.BLOCK.get(tag).map(hs -> (HolderSet) hs).orElse(HolderSet.empty()); + return (ToolRule) (Object) Tool.Rule.minesAndDrops(holderSet, (float) speed); } @Override @@ -58,17 +63,22 @@ public ToolRule deniesDrops(final List blocks) { @Override public ToolRule deniesDrops(final Tag blockTypeTag) { - return (ToolRule) (Object) Tool.Rule.deniesDrops((TagKey) (Object) blockTypeTag); + final var tag = (TagKey) (Object) blockTypeTag; + final var holderSet = BuiltInRegistries.BLOCK.get(tag).map(hs -> (HolderSet) hs).orElse(HolderSet.empty()); + return (ToolRule) (Object) Tool.Rule.deniesDrops(holderSet); } @Override public ToolRule overrideSpeed(final List blocks, final double speed) { - return (ToolRule) (Object) Tool.Rule.overrideSpeed(blocks.stream().map(Block.class::cast).toList(), (float) speed); + final var holderSet = HolderSet.direct(blocks.stream().map(Block.class::cast).map(Block::builtInRegistryHolder).toList()); + return (ToolRule) (Object) Tool.Rule.overrideSpeed(holderSet, (float) speed); } @Override public ToolRule overrideSpeed(final Tag blockTypeTag, final double speed) { - return (ToolRule) (Object) Tool.Rule.overrideSpeed((TagKey) (Object) blockTypeTag, (float) speed); + final var tag = (TagKey) (Object) blockTypeTag; + final var holderSet = BuiltInRegistries.BLOCK.get(tag).map(hs -> (HolderSet) hs).orElse(HolderSet.empty()); + return (ToolRule) (Object) Tool.Rule.overrideSpeed(holderSet, (float) speed); } @Override @@ -81,7 +91,8 @@ public ToolRule forBlocks(final List blocks, @Nullable final Double s @Override public ToolRule forTag(final Tag blockTypeTag, @Nullable final Double speed, @Nullable final Boolean drops) { // See Tool#forTag - final var holderSet = BuiltInRegistries.BLOCK.getOrCreateTag((TagKey) (Object) blockTypeTag); + final var tag = (TagKey) (Object) blockTypeTag; + final var holderSet = BuiltInRegistries.BLOCK.get(tag).map(hs -> (HolderSet) hs).orElse(HolderSet.empty()); return (ToolRule) (Object) new Tool.Rule(holderSet, Optional.ofNullable(speed).map(Double::floatValue), Optional.ofNullable(drops)); } } diff --git a/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java b/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java index 1c8c25e8881..7c2699c0549 100644 --- a/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java +++ b/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java @@ -93,8 +93,8 @@ public List build() throws IllegalStateException { if (this.pool == null || this.pool.isEmpty()) { Objects.requireNonNull(this.item, "The item cannot be null"); this.randomSource.setSeed(this.seed + this.option); - final var registry = SpongeCommon.server().registryAccess().registryOrThrow(Registries.ENCHANTMENT); - var stream = registry.holders().map($$0x -> (Holder)$$0x); + final var registry = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.ENCHANTMENT); + var stream = registry.listElements().map($$0x -> (Holder)$$0x); enchantments = EnchantmentHelper.selectEnchantment(this.randomSource, ItemStackUtil.toNative(this.item), this.level, stream); } else { this.randomSource.setSeed(this.seed + this.option); @@ -139,7 +139,7 @@ public static List fromNative(final List list) } public static List toNative(final List list) { - final var registry = SpongeCommon.server().registryAccess().registryOrThrow(Registries.ENCHANTMENT); + final var registry = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.ENCHANTMENT); return list.stream().map(ench -> { var mcEnch = registry.wrapAsHolder((net.minecraft.world.item.enchantment.Enchantment) (Object) ench.type()); return new EnchantmentInstance(mcEnch, ench.level()); diff --git a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java index 7688025bf6a..ceddabfb89a 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java @@ -35,6 +35,7 @@ import net.minecraft.advancements.critereon.RecipeUnlockedTrigger; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; import net.minecraft.data.recipes.RecipeCategory; import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceLocation; @@ -71,9 +72,10 @@ public SpongeRecipeRegistration(final ResourceLocation key, this.key = key; this.serializer = serializer; this.pack = pack; + var rKey = net.minecraft.resources.ResourceKey.create(Registries.RECIPE, key); this.advancement = Advancement.Builder.advancement() - .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(key)) - .rewards(AdvancementRewards.Builder.recipe(key)) + .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(rKey)) + .rewards(AdvancementRewards.Builder.recipe(rKey)) .build(ResourceLocation.fromNamespaceAndPath(key.getNamespace(), "recipes/" + recipeCategory.getFolderName() + "/" + key.getPath())); this.group = group == null ? "" : group; } @@ -101,12 +103,7 @@ public static boolean isVanillaSerializer(final ItemStac if (!resultStack.getComponents().isEmpty() || resultFunction != null || remainingItemsFunction != null) { return false; } - for (final Ingredient value : ingredients) { - if (value instanceof SpongeIngredient) { - return false; - } - } - return true; + return ingredients.stream().noneMatch(value -> value instanceof SpongeIngredient); } @Override diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java index 6675d43b475..4d3223616b3 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java @@ -59,12 +59,5 @@ public ItemStack assemble(final SingleRecipeInput $$0, final HolderLookup.Provid return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { -// if (this.resultFunction != null) { -// return ItemStack.EMPTY; -// } - return super.getResultItem($$1); - } } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java index ecce010f0ab..6fd30630776 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java @@ -59,12 +59,4 @@ public ItemStack assemble(final SingleRecipeInput $$0, final HolderLookup.Provid return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { - if (this.resultFunctionId != null) { - return ItemStack.EMPTY; - } - return super.getResultItem($$1); - } - } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCookingRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCookingRecipeRegistration.java index 040c5be9642..6a1b01b74e4 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCookingRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCookingRecipeRegistration.java @@ -47,7 +47,6 @@ import org.spongepowered.common.util.SpongeTicks; import java.util.Collections; -import java.util.List; import java.util.function.Function; public class SpongeCookingRecipeRegistration extends SpongeRecipeRegistration implements SpongeRecipeRegistration.ResultFunctionRegistration{ @@ -118,7 +117,7 @@ public Recipe recipe() { final int ticksCookingTime = SpongeTicks.toSaturatedIntOrInfinite(this.cookingTime); final String resultFunctionId = this.resultFunction == null ? null : this.key.toString(); - final List ingredientList = Collections.singletonList(ingredient); + final var ingredientList = Collections.singletonList(ingredient); final boolean isVanilla = SpongeRecipeRegistration.isVanillaSerializer(this.spongeResult, this.resultFunction, null, ingredientList); if (type == RecipeType.BLASTING) { diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java index 13e51a37ac7..cdd5b5e9999 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java @@ -59,12 +59,4 @@ public ItemStack assemble(final SingleRecipeInput $$0, final HolderLookup.Provid return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { - if (this.resultFunctionId != null) { - return ItemStack.EMPTY; - } - return super.getResultItem($$1); - } - } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java index 5397cad2138..e761bb39b93 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java @@ -59,13 +59,5 @@ public ItemStack assemble(final SingleRecipeInput $$0, final HolderLookup.Provid return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { - if (this.resultFunctionId != null) { - return ItemStack.EMPTY; - } - return super.getResultItem($$1); - } - } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/EquipableMixin_ItemStackLike.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/RecipeUtil.java similarity index 54% rename from src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/EquipableMixin_ItemStackLike.java rename to src/main/java/org/spongepowered/common/item/recipe/crafting/RecipeUtil.java index a1b9f45069e..180026731e4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/EquipableMixin_ItemStackLike.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/RecipeUtil.java @@ -22,31 +22,33 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory; +package org.spongepowered.common.item.recipe.crafting; -import org.spongepowered.api.item.inventory.Equipable; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.equipment.EquipmentType; -import org.spongepowered.asm.mixin.Mixin; +import net.minecraft.util.context.ContextMap; +import net.minecraft.world.item.crafting.display.DisplayContentsFactory; +import net.minecraft.world.item.crafting.display.SlotDisplayContext; +import org.spongepowered.api.Sponge; +import org.spongepowered.common.SpongeCommon; -import java.util.function.Supplier; +import java.util.List; -@Mixin(value = Equipable.class, remap = false) -public interface EquipableMixin_ItemStackLike { +public final class RecipeUtil { - default boolean canEquip(EquipmentType type, ItemStack equipment) { - return ((Equipable) this).canEquip(type, equipment); + public static ContextMap serverBasedContextMap() { + if (!Sponge.isServerAvailable()) { + return new ContextMap.Builder().create(SlotDisplayContext.CONTEXT); + } + final var server = SpongeCommon.server(); + return new ContextMap.Builder() + .withParameter(SlotDisplayContext.FUEL_VALUES, server.fuelValues()) + .withParameter(SlotDisplayContext.REGISTRIES, server.registryAccess()) + .create(SlotDisplayContext.CONTEXT); } - default boolean canEquip(Supplier type, ItemStack equipment) { - return ((Equipable) this).canEquip(type, equipment); - } - - default boolean equip(EquipmentType type, ItemStack equipment) { - return ((Equipable) this).equip(type, equipment); - } - - default boolean equip(Supplier type, ItemStack equipment) { - return ((Equipable) this).equip(type, equipment); + public class RemainderResolver implements DisplayContentsFactory.ForRemainders { + @Override + public T addRemainder(T var1, List var2) { + return null; + } } } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java index 09531ed46b4..bc2ec36d749 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java @@ -36,14 +36,11 @@ import net.minecraft.world.item.crafting.CustomRecipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import org.spongepowered.api.item.recipe.crafting.RecipeInput; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.inventory.util.InventoryUtil; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.MissingImplementationException; import java.util.List; import java.util.function.BiPredicate; @@ -91,12 +88,6 @@ public ItemStack assemble(final CraftingInput input, final HolderLookup.Provider return ItemStackUtil.toNative(this.resultFunction.apply(InventoryUtil.toSponge(input))); } - @OnlyIn(Dist.CLIENT) - @Override - public boolean canCraftInDimensions(int width, int height) { - throw new MissingImplementationException("SpongeSpecialRecipe", "canFit"); - } - @Override public NonNullList getRemainingItems(final CraftingInput input) { if (this.remainingItemsFunction == null) { @@ -109,7 +100,7 @@ public NonNullList getRemainingItems(final CraftingInput input) { } @Override - public RecipeSerializer getSerializer() { + public RecipeSerializer getSerializer() { // Fake special crafting serializer // because of Unknown recipe serializer when using our serializer with a vanilla client // return Registry.RECIPE_SERIALIZER.getOrDefault(this.id()); diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedCraftingRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedCraftingRecipeRegistration.java index b65c5c09b99..8574bdcfaeb 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedCraftingRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedCraftingRecipeRegistration.java @@ -39,6 +39,7 @@ import org.spongepowered.api.item.recipe.crafting.ShapedCraftingRecipe; import org.spongepowered.common.item.recipe.SpongeRecipeRegistration; +import java.util.Optional; import java.util.function.Function; public class SpongeShapedCraftingRecipeRegistration extends SpongeRecipeRegistration implements @@ -79,7 +80,8 @@ public Function> remainingItems() { @Override public Recipe recipe() { - if (SpongeRecipeRegistration.isVanillaSerializer(this.spongeResult, this.resultFunction, this.remainingItemsFunction, this.pattern.ingredients())) { + final var ingredients = this.pattern.ingredients().stream().filter(Optional::isPresent).map(Optional::get).toList(); + if (SpongeRecipeRegistration.isVanillaSerializer(this.spongeResult, this.resultFunction, this.remainingItemsFunction, ingredients)) { return (ShapedCraftingRecipe) new ShapedRecipe(this.group, this.craftingBookCategory, this.pattern, this.spongeResult, this.showNotification); } this.ensureCached(); diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java index 0dd447c0c7c..6ce7547a3f7 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java @@ -48,7 +48,7 @@ public class SpongeShapedRecipe extends ShapedRecipe implements ResultFunctionRe public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$0 -> $$0.group( Codec.STRING.fieldOf(Constants.Recipe.SPONGE_TYPE).forGetter(t -> "custom"), // important to fail early when decoding vanilla recipes - Codec.STRING.optionalFieldOf(Constants.Recipe.GROUP, "").forGetter(ShapedRecipe::getGroup), + Codec.STRING.optionalFieldOf(Constants.Recipe.GROUP, "").forGetter(ShapedRecipe::group), CraftingBookCategory.CODEC.fieldOf(Constants.Recipe.CATEGORY).orElse(CraftingBookCategory.MISC).forGetter(ShapedRecipe::category), ShapedRecipePattern.MAP_CODEC.forGetter($$0x -> ((ShapedRecipeBridge) $$0x).bridge$pattern()), ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), @@ -118,12 +118,4 @@ public ItemStack assemble(final CraftingInput $$0, final HolderLookup.Provider $ return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$0) { - if (this.resultFunctionId != null) { - return ItemStack.EMPTY; - } - return super.getResultItem($$0); - } - } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java index 8090a7189f6..daed310a648 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java @@ -25,7 +25,6 @@ package org.spongepowered.common.item.recipe.crafting.shapeless; import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.HolderLookup; @@ -36,6 +35,7 @@ import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.ShapelessRecipe; import net.minecraft.world.level.Level; +import org.spongepowered.common.accessor.world.item.crafting.ShapelessRecipeAccessor; import org.spongepowered.common.bridge.world.item.crafting.RecipeResultBridge; import org.spongepowered.common.item.recipe.ingredient.IngredientResultUtil; import org.spongepowered.common.item.recipe.ingredient.SpongeIngredient; @@ -60,26 +60,12 @@ public class SpongeShapelessRecipe extends ShapelessRecipe { public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$0 -> $$0.group( Codec.STRING.fieldOf(Constants.Recipe.SPONGE_TYPE).forGetter(t -> "custom"), // important to fail early when decoding vanilla recipes - Codec.STRING.optionalFieldOf("group", "").forGetter(ShapelessRecipe::getGroup), + Codec.STRING.optionalFieldOf("group", "").forGetter(ShapelessRecipe::group), CraftingBookCategory.CODEC.fieldOf("category").orElse(CraftingBookCategory.MISC).forGetter(ShapelessRecipe::category), ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), - Ingredient.CODEC_NONEMPTY - .listOf() + Ingredient.CODEC.listOf(1,9) .fieldOf(Constants.Recipe.SHAPELESS_INGREDIENTS) - .flatXmap( - $$0x -> { - Ingredient[] $$1 = $$0x.stream().filter($$0xx -> !$$0xx.isEmpty()).toArray(Ingredient[]::new); - if ($$1.length == 0) { - return DataResult.error(() -> "No ingredients for shapeless recipe"); - } else { - return $$1.length > 9 - ? DataResult.error(() -> "Too many ingredients for shapeless recipe") - : DataResult.success(NonNullList.of(Ingredient.EMPTY, $$1)); - } - }, - DataResult::success - ) - .forGetter(ShapelessRecipe::getIngredients), + .forGetter(sr -> ((ShapelessRecipeAccessor) sr).accessor$ingredients()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(SpongeShapelessRecipe::resultFunctionId), IngredientResultUtil.CACHED_REMAINING_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_REMAINING_ITEMS).forGetter(SpongeShapelessRecipe::remainingItemsFunctionId) ) @@ -96,7 +82,7 @@ public static SpongeShapelessRecipe of( final String groupIn, final CraftingBookCategory category, final ItemStack recipeOutputIn, - final NonNullList recipeItemsIn, + final List recipeItemsIn, final Optional resultFunctionId, final Optional remainingItemsFunctionId) { @@ -106,7 +92,7 @@ public static SpongeShapelessRecipe of( public SpongeShapelessRecipe(final String groupIn, final CraftingBookCategory category, - final NonNullList recipeItemsIn, + final List recipeItemsIn, final ItemStack spongeResultStack, final String resultFunctionId, final String remainingItemsFunctionId) { @@ -129,7 +115,7 @@ public boolean matches(final CraftingInput $$0, final Level $$1) { if (this.onlyVanillaIngredients) { return super.matches($$0, $$1); } - return SpongeShapelessRecipe.matches($$0.items(), this.getIngredients()); + return SpongeShapelessRecipe.matches($$0.items(), ((ShapelessRecipeAccessor) this).accessor$ingredients()); } @Override @@ -149,14 +135,6 @@ public ItemStack assemble(final CraftingInput $$0, final HolderLookup.Provider $ return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { -// if (this.resultFunctionId != null) { -// return ItemStack.EMPTY; -// } - return super.getResultItem($$1); - } - private static boolean matches(List stacks, List ingredients) { final int elements = ingredients.size(); diff --git a/src/main/java/org/spongepowered/common/item/recipe/ingredient/IngredientUtil.java b/src/main/java/org/spongepowered/common/item/recipe/ingredient/IngredientUtil.java index 23c02c5921f..228ba81923a 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/ingredient/IngredientUtil.java +++ b/src/main/java/org/spongepowered/common/item/recipe/ingredient/IngredientUtil.java @@ -24,6 +24,8 @@ */ package org.spongepowered.common.item.recipe.ingredient; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; @@ -59,7 +61,8 @@ public static org.spongepowered.api.item.recipe.crafting.Ingredient of(ItemType. public static org.spongepowered.api.item.recipe.crafting.@Nullable Ingredient of(ResourceKey tagKey) { final TagKey key = TagKey.create(Registries.ITEM, (ResourceLocation) (Object) tagKey); - return IngredientUtil.fromNative(Ingredient.of(key)); + var holderset = BuiltInRegistries.ITEM.get(key).map(hs -> (HolderSet) hs).orElse(HolderSet.empty()); + return IngredientUtil.fromNative(Ingredient.of(holderset)); } private static net.minecraft.world.item.ItemStack[] toNativeStacks(ItemStack[] stacks) { diff --git a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java index 887b9e888ff..bbb97b5c596 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java +++ b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java @@ -28,6 +28,7 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderSet; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -44,7 +45,6 @@ import java.util.Map; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Stream; public class SpongeIngredient extends Ingredient { @@ -83,8 +83,8 @@ public class SpongeIngredient extends Ingredient { if (predicate == null) { return DataResult.error(() -> "Could not find predicate for custom ingredient with id " + raw.predicateId.get()); } - final SpongeIngredient ingredient = new SpongeIngredient(raw.type, - new SpongePredicateItemList(raw.predicateId.get(), predicate, raw.stacks.toArray(new ItemStack[0])), raw.predicateId.orElse(null)); + final var predicateList = new SpongePredicateItemList(raw.predicateId.get(), predicate, raw.stacks.toArray(new ItemStack[0])); + final SpongeIngredient ingredient = new SpongeIngredient(raw.type, predicateList, raw.predicateId.orElse(null)); return DataResult.success(ingredient); } default -> { @@ -94,7 +94,7 @@ public class SpongeIngredient extends Ingredient { }, spongeIngredient -> { switch (spongeIngredient.type) { case SpongeStackItemList.TYPE_STACK -> { - var stacks = Arrays.stream(spongeIngredient.values).flatMap(v -> v.getItems().stream()).toList(); + final var stacks = Arrays.asList(spongeIngredient.itemList.stacks); return DataResult.success(new SpongeRawIngredient(spongeIngredient.type, stacks, Optional.empty())); } case SpongePredicateItemList.TYPE_PREDICATE -> { @@ -105,19 +105,17 @@ public class SpongeIngredient extends Ingredient { }); public final String type; public final String predicateId; + private final SpongeItemList itemList; record SpongeRawIngredient(String type, List stacks, Optional predicateId) { } - public SpongeIngredient(final String type, final Stream values, final String predicateId) { - super(values); + public SpongeIngredient(final String type, final SpongeItemList itemList, final String predicateId) { + super(HolderSet.direct(itemList.stream().toList())); this.type = type; this.predicateId = predicateId; - } - - public SpongeIngredient(final String type, final Ingredient.Value value, final String predicateId) { - this(type, Stream.of(value), predicateId); + this.itemList = itemList; } public static void clearCache() { @@ -130,22 +128,7 @@ public boolean test(final ItemStack testStack) { return false; } - for (final Value acceptedItem : this.values) { - if (acceptedItem instanceof SpongeItemList) { - if (((SpongeItemList) acceptedItem).test(testStack)) { - return true; - } - } else { - // TODO caching (relevant for TagList) - for (final ItemStack stack : acceptedItem.getItems()) { - if (stack.getItem() == testStack.getItem()) { - return true; - } - } - } - } - - return false; + return this.itemList.test(testStack); } public static SpongeIngredient spongeFromStacks(net.minecraft.world.item.ItemStack... stacks) { diff --git a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeItemList.java b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeItemList.java index 80def6626f2..27a5e0a08b4 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeItemList.java +++ b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeItemList.java @@ -26,13 +26,25 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import com.mojang.datafixers.util.Either; +import net.minecraft.Util; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderOwner; +import net.minecraft.core.HolderSet; +import net.minecraft.tags.TagKey; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; -public abstract class SpongeItemList implements Ingredient.Value { +public abstract class SpongeItemList implements HolderSet { public static final String INGREDIENT_TYPE = "sponge:type"; public static final String INGREDIENT_ITEM = "sponge:item"; @@ -44,6 +56,62 @@ public SpongeItemList(ItemStack... stacks) { } @Override + public Stream> stream() { + return Arrays.stream(this.stacks) + .map(ItemStack::getItemHolder); + } + + @Override + public int size() { + return this.stacks.length; + } + + @Override + public boolean isBound() { + return true; + } + + @Override + public Either, List>> unwrap() { + return Either.right(this.stream().toList()); + } + + @Override + public Optional> getRandomElement(RandomSource source) { + return this.stacks.length == 0 ? Optional.empty() : + Optional.of(Util.getRandom(this.stacks, source)). + map(ItemStack::getItemHolder); + } + + @Override + public Holder get(int var1) { + final var stack = this.stacks[var1]; + return stack.getItemHolder(); + } + + @Override + public boolean contains(Holder var1) { + return false; + } + + @Override + public boolean canSerializeIn(HolderOwner var1) { + // TODO - maybe? What's this for? + return true; + } + + @Override + public Optional> unwrapKey() { + return Optional.empty(); + } + + @Override + public @NotNull Iterator> iterator() { + return Arrays.stream(this.stacks) + .map(ItemStack::getItemHolder) + .iterator(); + } + public Collection getItems() { return Arrays.asList(this.stacks); } diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java index bff50643488..42e3cf263b2 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java @@ -47,9 +47,9 @@ public class SpongeSmithingRecipe extends SmithingTransformRecipe implements Res public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$0 -> $$0.group( Codec.STRING.fieldOf(SPONGE_TYPE).forGetter(a -> "custom"), - Ingredient.CODEC.fieldOf("template").forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$template()), - Ingredient.CODEC.fieldOf(Constants.Recipe.SMITHING_BASE_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$base()), - Ingredient.CODEC.fieldOf(Constants.Recipe.SMITHING_ADDITION_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$addition()), + Ingredient.CODEC.optionalFieldOf(Constants.Recipe.SMITHING_TEMPLATE_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$template()), + Ingredient.CODEC.optionalFieldOf(Constants.Recipe.SMITHING_BASE_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$base()), + Ingredient.CODEC.optionalFieldOf(Constants.Recipe.SMITHING_ADDITION_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$addition()), ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge) $$0x).bridge$result()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId) ) @@ -58,14 +58,14 @@ public class SpongeSmithingRecipe extends SmithingTransformRecipe implements Res private final String resultFunctionId; - public static SpongeSmithingRecipe of(final String spongeType, final Ingredient template, final Ingredient base, - final Ingredient addition, final ItemStack resultIn, final Optional resultFunctionId) + public static SpongeSmithingRecipe of(final String spongeType, final Optional template, final Optional base, + final Optional addition, final ItemStack resultIn, final Optional resultFunctionId) { return new SpongeSmithingRecipe(template, base, addition, resultIn, resultFunctionId.orElse(null)); } - public SpongeSmithingRecipe(final Ingredient template, final Ingredient base, - final Ingredient addition, final ItemStack spongeResult, final String resultFunctionId) { + public SpongeSmithingRecipe(final Optional template, final Optional base, + final Optional addition, final ItemStack spongeResult, final String resultFunctionId) { super(template, base, addition, spongeResult); this.resultFunctionId = resultFunctionId; } @@ -81,25 +81,7 @@ public ItemStack assemble(final SmithingRecipeInput $$0, final HolderLookup.Prov return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply($$0); } - final ItemStack resultItem = this.getResultItem($$1); - if (!resultItem.getComponents().isEmpty()) { - final ItemStack itemStack = resultItem.copy(); - var patch = $$0.getItem(0).getComponentsPatch(); - if (!patch.isEmpty()) { - itemStack.applyComponents(patch); - return itemStack; - } - } return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(HolderLookup.Provider $$1) { - if (this.resultFunctionId != null) { - return ItemStack.EMPTY; - } - return super.getResultItem($$1); - } - - } diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipeRegistration.java index 39a62cbb37a..26261ca7cc3 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipeRegistration.java @@ -38,6 +38,7 @@ import org.spongepowered.common.item.recipe.SpongeRecipeRegistration; import java.util.List; +import java.util.Optional; import java.util.function.Function; public class SpongeSmithingRecipeRegistration extends SpongeRecipeRegistration implements @@ -68,10 +69,11 @@ public SpongeSmithingRecipeRegistration(ResourceLocation key, String group, fina public Recipe recipe() { this.ensureCached(); if (SpongeRecipeRegistration.isVanillaSerializer(this.spongeResult, this.resultFunction, null, List.of(this.template, this.base, this.addition))) { - return (SmithingRecipe) new SmithingTransformRecipe(this.template, this.base, this.addition, this.spongeResult); + return (SmithingRecipe) new SmithingTransformRecipe(Optional.of(this.template), Optional.of(this.base), Optional.of(this.addition), this.spongeResult); } - return (SmithingRecipe) new SpongeSmithingRecipe(this.template, this.base, this.addition, this.spongeResult, this.resultFunction == null ? null : this.key.toString()); + return (SmithingRecipe) new SpongeSmithingRecipe(Optional.ofNullable(this.template), Optional.ofNullable(this.base), Optional.ofNullable(this.addition), + this.spongeResult, this.resultFunction == null ? null : this.key.toString()); } @Override diff --git a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java index a2401eadcd8..7cc74df448e 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java @@ -57,9 +57,9 @@ public class SpongeStonecuttingRecipe extends StonecutterRecipe implements Resul public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$1 -> $$1.group( Codec.STRING.fieldOf(SPONGE_TYPE).forGetter(a -> "custom"), - Codec.STRING.optionalFieldOf("group", "").forGetter(SingleItemRecipe::getGroup), - Ingredient.CODEC_NONEMPTY.fieldOf(Constants.Recipe.STONECUTTING_INGREDIENT).forGetter($$0x -> $$0x.getIngredients().get(0)), - RESULT_CODEC.forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), + Codec.STRING.optionalFieldOf("group", "").forGetter(SingleItemRecipe::group), + Ingredient.CODEC.fieldOf(Constants.Recipe.STONECUTTING_INGREDIENT).forGetter(SingleItemRecipe::input), + RESULT_CODEC.forGetter($$0x -> $$0x.result()), ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$spongeResult()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId) ) @@ -95,12 +95,4 @@ public ItemStack assemble(final SingleRecipeInput $$0, final HolderLookup.Provid return super.assemble($$0, $$1); } - @Override - public ItemStack getResultItem(final HolderLookup.Provider $$1) { -// if (this.resultFunctionId != null) { -// return ItemStack.EMPTY; -// } - return super.getResultItem($$1); - } - } diff --git a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java index a77808af907..7c611271f66 100644 --- a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java +++ b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java @@ -99,7 +99,7 @@ public static void init(final SpongeChannelManager registry) { return; } - final DimensionType dimensionType = SpongeCommon.vanillaRegistry(Registries.DIMENSION_TYPE).get(packet.dimensionLogic); + final DimensionType dimensionType = SpongeCommon.vanillaRegistry(Registries.DIMENSION_TYPE).getValue(packet.dimensionLogic); ((ClientLevelAccessor) world).accessor$effects(DimensionSpecialEffects.forType(dimensionType)); } ); diff --git a/src/main/java/org/spongepowered/common/registry/ProxiedRegistryAccess.java b/src/main/java/org/spongepowered/common/registry/ProxiedRegistryAccess.java deleted file mode 100644 index f37c2ef7ac5..00000000000 --- a/src/main/java/org/spongepowered/common/registry/ProxiedRegistryAccess.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.registry; - -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceKey; -import org.checkerframework.checker.nullness.qual.Nullable; - -import java.util.Map; -import java.util.Optional; -import java.util.stream.Stream; - -public final class ProxiedRegistryAccess implements RegistryAccess { - - private final RegistryAccess access; - private final Map>, Registry> overrides; - - public ProxiedRegistryAccess(final RegistryAccess access, final Map>, Registry> overrides) { - this.access = access; - this.overrides = Map.copyOf(overrides); - } - - @Override - @SuppressWarnings("unchecked") - public Optional> registry(final ResourceKey> var1) { - final @Nullable Registry override = this.overrides.get(var1); - if (override != null) { - return Optional.of((Registry) override); - } - return this.access.registry(var1); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Stream> registries() { - return Stream.concat( - this.access.registries().filter(entry -> !this.overrides.containsKey(entry.key())), - (Stream>) (Stream) this.overrides.entrySet().stream().map(entry -> new RegistryAccess.RegistryEntry(entry.getKey(), entry.getValue())) - ); - } - -} diff --git a/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java b/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java index 5b1d397126f..2e48e15fb31 100644 --- a/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java +++ b/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java @@ -94,14 +94,12 @@ public void setRootMinecraftRegistry(final net.minecraft.core.Registry Registry registry(final RegistryType type) { - final net.minecraft.core.Registry> root = this.roots.get(Objects.requireNonNull(type, "type").root()); + final var root = this.roots.get(Objects.requireNonNull(type, "type").root()); if (root == null) { throw new ValueNotFoundException(String.format("No '%s' root registry has been defined", type.root())); } - final net.minecraft.core.Registry registry = root.get((ResourceLocation) (Object) type.location()); - if (registry == null) { - throw new ValueNotFoundException(String.format("No '%s' registry has been defined in root '%s'", type.location(), type.root())); - } + final var registry = root.getOptional((ResourceLocation) (Object) type.location()) + .orElseThrow(() -> new ValueNotFoundException(String.format("No '%s' registry has been defined in root '%s'", type.location(), type.root()))); return (Registry) registry; } @@ -161,7 +159,7 @@ public Registry createRegistry(final RegistryType type, final @Nullabl if (root == null) { throw new ValueNotFoundException(String.format("No '%s' root registry has been defined", type.root())); } - net.minecraft.core.Registry registry = root.get((ResourceLocation) (Object) type.location()); + var registry = root.getValue((ResourceLocation) (Object) type.location()); final boolean exists = registry != null; if (!replace && exists) { throw new DuplicateRegistrationException(String.format("Registry '%s' in root '%s' has already been defined", type.location(), type.root())); diff --git a/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java index 4b6f07a7b43..f0c4ab3d9c8 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java @@ -217,7 +217,7 @@ public static RegistryLoader clientCompletionType() { public static RegistryLoader clientSuggestionProvider() { return RegistryLoader.of(l -> { // TODO based on SuggestionProviders.PROVIDERS_BY_NAME instead - l.add(CommandCompletionProviders.ALL_RECIPES, k -> (CommandCompletionProvider) SuggestionProviders.ALL_RECIPES); +// l.add(CommandCompletionProviders.ALL_RECIPES, k -> (CommandCompletionProvider) SuggestionProviders.ALL_RECIPES); l.add(CommandCompletionProviders.AVAILABLE_SOUNDS, k -> (CommandCompletionProvider) SuggestionProviders.AVAILABLE_SOUNDS); l.add(CommandCompletionProviders.SUMMONABLE_ENTITIES, k -> (CommandCompletionProvider) SuggestionProviders.SUMMONABLE_ENTITIES); }); @@ -293,7 +293,7 @@ public static RegistryLoader> commandRegistrarType() { // Helper static ArgumentType argumentTypeFromKey(ResourceKey key, CommandBuildContext ctx) { - final ArgumentTypeInfo argumentTypeInfo = BuiltInRegistries.COMMAND_ARGUMENT_TYPE.get((ResourceLocation) (Object) key); + final ArgumentTypeInfo argumentTypeInfo = BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getValue((ResourceLocation) (Object) key); if (argumentTypeInfo instanceof SingletonArgumentInfo s) { return s.unpack(null).instantiate(ctx); } diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index de3bfb4931a..54cc7107c21 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -581,7 +581,7 @@ public static RegistryLoader noiseConfig() { } public static RegistryLoader flatGeneratorConfig(RegistryAccess registryAccess) { - final Registry registry = registryAccess.registryOrThrow(Registries.FLAT_LEVEL_GENERATOR_PRESET); + final Registry registry = registryAccess.lookupOrThrow(Registries.FLAT_LEVEL_GENERATOR_PRESET); return RegistryLoader.of(l -> { for (final var entry : registry.entrySet()) { l.add(RegistryKey.of(RegistryTypes.FLAT_GENERATOR_CONFIG, (ResourceKey) (Object) entry.getKey().location()), () -> (FlatGeneratorConfig) entry.getValue().settings()); diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index 8dd24c87c8d..8a2491cc8d2 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -54,12 +54,11 @@ import net.minecraft.world.entity.player.ChatVisiblity; import net.minecraft.world.entity.projectile.AbstractArrow; import net.minecraft.world.entity.raid.Raid; -import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.Rarity; -import net.minecraft.world.item.Tiers; import net.minecraft.world.item.component.FireworkExplosion; +import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameType; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.biome.Biome; @@ -142,6 +141,17 @@ private void loadInstanceRegistries() { map.put(EnderDragonPhase.HOVERING, "hover"); }, phase -> CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, ((EnderDragonPhaseAccessor) phase).accessor$name())); this.holder.createRegistry(RegistryTypes.FIREWORK_SHAPE, VanillaRegistryLoader.fireworkShape()); +// final var materials = new HashMap(); +// materials.put(ArmorMaterials.LEATHER, ArmorMaterials.LEATHER.modelId().toString()); +// materials.put(ArmorMaterials.CHAIN, ArmorMaterials.CHAIN.modelId().toString()); +// materials.put(ArmorMaterials.IRON, ArmorMaterials.IRON.modelId().toString()); +// materials.put(ArmorMaterials.GOLD, ArmorMaterials.GOLD.modelId().toString()); +// materials.put(ArmorMaterials.DIAMOND, ArmorMaterials.DIAMOND.modelId().toString()); +// materials.put(ArmorMaterials.TURTLE_SCUTE, ResourceKey.minecraft("turtle").toString()); +// materials.put(ArmorMaterials.NETHERITE, ArmorMaterials.NETHERITE.modelId().toString()); +// materials.put(ArmorMaterials.ARMADILLO_SCUTE, ArmorMaterials.ARMADILLO_SCUTE.modelId().toString()); +// +// this.naming(RegistryTypes.ARMOR_MATERIAL, materials.keySet().toArray(new ArmorMaterial[]{}), materials); this.knownName(RegistryTypes.GAME_RULE, GameRulesAccessor.accessor$GAME_RULE_TYPES().keySet(), rule -> CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, rule.getId())); } @@ -155,7 +165,6 @@ private void loadEnumRegistries() { map.put(AttributeModifier.Operation.ADD_MULTIPLIED_BASE, "multiply_base"); map.put(AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL, "multiply_total"); }); - this.automaticName(RegistryTypes.BOAT_TYPE, Boat.Type.values()); this.automaticName(RegistryTypes.CHEST_ATTACHMENT_TYPE, ChestType.values()); this.automaticName(RegistryTypes.COLLISION_RULE, Team.CollisionRule.values()); this.automaticName(RegistryTypes.COMPARATOR_MODE, ComparatorMode.values()); @@ -165,15 +174,16 @@ private void loadEnumRegistries() { this.automaticName(RegistryTypes.DRIPSTONE_SEGMENT, DripstoneThickness.values()); this.automaticName(RegistryTypes.EQUIPMENT_GROUP, EquipmentSlot.Type.values()); this.automaticName(RegistryTypes.EQUIPMENT_TYPE, EquipmentSlot.values()); - this.automaticName(RegistryTypes.FOX_TYPE, Fox.Type.values()); + this.automaticName(RegistryTypes.FOX_TYPE, Fox.Variant.values()); this.automaticName(RegistryTypes.GAME_MODE, GameType.values()); this.automaticName(RegistryTypes.HAND_PREFERENCE, HumanoidArm.values()); this.automaticName(RegistryTypes.HAND_TYPE, InteractionHand.values()); this.automaticName(RegistryTypes.INSTRUMENT_TYPE, NoteBlockInstrument.values()); this.automaticName(RegistryTypes.ITEM_RARITY, Rarity.values()); - this.automaticName(RegistryTypes.ITEM_TIER, Tiers.values()); + // TODO - Figure out if we should make a registry - Snapshot 24w34a +// this.automaticName(RegistryTypes.ITEM_TIER, ToolMaterial.values()); this.automaticName(RegistryTypes.JIGSAW_BLOCK_ORIENTATION, FrontAndTop.values()); - this.automaticName(RegistryTypes.MOOSHROOM_TYPE, MushroomCow.MushroomType.values()); + this.automaticName(RegistryTypes.MOOSHROOM_TYPE, MushroomCow.Variant.values()); this.automaticName(RegistryTypes.OBJECTIVE_DISPLAY_MODE, ObjectiveCriteria.RenderType.values()); this.automaticName(RegistryTypes.PANDA_GENE, Panda.Gene.values()); this.automaticName(RegistryTypes.PHANTOM_PHASE, Phantom.AttackPhase.values()); @@ -202,7 +212,6 @@ private void loadEnumRegistries() { this.automaticName(RegistryTypes.GRASS_COLOR_MODIFIER, BiomeSpecialEffects.GrassColorModifier.values()); this.automaticName(RegistryTypes.PRECIPITATION, Biome.Precipitation.values()); this.automaticName(RegistryTypes.TEMPERATURE_MODIFIER, Biome.TemperatureModifier.values()); - this.automaticName(RegistryTypes.CARVING_STEP, GenerationStep.Carving.values()); this.automaticName(RegistryTypes.DECORATION_STEP, GenerationStep.Decoration.values()); this.automaticName(RegistryTypes.PARROT_TYPE, Parrot.Variant.values()); this.automaticName(RegistryTypes.RABBIT_TYPE, Rabbit.Variant.values()); @@ -219,6 +228,7 @@ private void loadEnumRegistries() { this.automaticName(RegistryTypes.PUSH_REACTION, PushReaction.values()); this.automaticName(RegistryTypes.TRIAL_SPAWNER_STATE, TrialSpawnerState.values()); this.automaticName(RegistryTypes.VAULT_STATE, VaultState.values()); + this.automaticName(RegistryTypes.EXPLOSION_BLOCK_INTERACTION, Explosion.BlockInteraction.values()); } private static RegistryLoader criterion() { diff --git a/src/main/java/org/spongepowered/common/util/DirectionUtil.java b/src/main/java/org/spongepowered/common/util/DirectionUtil.java index dcbede764bb..d7d8dd9365f 100644 --- a/src/main/java/org/spongepowered/common/util/DirectionUtil.java +++ b/src/main/java/org/spongepowered/common/util/DirectionUtil.java @@ -25,7 +25,7 @@ package org.spongepowered.common.util; -import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.block.state.properties.EnumProperty; import org.spongepowered.api.util.Direction; import java.util.Objects; @@ -34,45 +34,31 @@ public final class DirectionUtil { public static net.minecraft.core.Direction getFor(final Direction direction) { Objects.requireNonNull(direction); - switch (direction) { - case UP: - return net.minecraft.core.Direction.UP; - case DOWN: - return net.minecraft.core.Direction.DOWN; - case WEST: - return net.minecraft.core.Direction.WEST; - case SOUTH: - return net.minecraft.core.Direction.SOUTH; - case EAST: - return net.minecraft.core.Direction.EAST; - case NORTH: - return net.minecraft.core.Direction.NORTH; - default: - return null; - } + return switch (direction) { + case UP -> net.minecraft.core.Direction.UP; + case DOWN -> net.minecraft.core.Direction.DOWN; + case WEST -> net.minecraft.core.Direction.WEST; + case SOUTH -> net.minecraft.core.Direction.SOUTH; + case EAST -> net.minecraft.core.Direction.EAST; + case NORTH -> net.minecraft.core.Direction.NORTH; + default -> null; + }; } public static Direction getFor(final net.minecraft.core.Direction facing) { Objects.requireNonNull(facing); - switch (facing) { - case UP: - return Direction.UP; - case DOWN: - return Direction.DOWN; - case WEST: - return Direction.WEST; - case SOUTH: - return Direction.SOUTH; - case EAST: - return Direction.EAST; - case NORTH: - return Direction.NORTH; - default: - throw new IllegalStateException(); - } + return switch (facing) { + case UP -> Direction.UP; + case DOWN -> Direction.DOWN; + case WEST -> Direction.WEST; + case SOUTH -> Direction.SOUTH; + case EAST -> Direction.EAST; + case NORTH -> Direction.NORTH; + default -> throw new IllegalStateException(); + }; } - public static net.minecraft.world.level.block.state.BlockState set(final net.minecraft.world.level.block.state.BlockState holder, final Direction value, final DirectionProperty property) { + public static net.minecraft.world.level.block.state.BlockState set(final net.minecraft.world.level.block.state.BlockState holder, final Direction value, final EnumProperty property) { final net.minecraft.core.Direction direction = DirectionUtil.getFor(value); if (direction == null || !property.getPossibleValues().contains(direction)) { return holder; @@ -81,168 +67,101 @@ public static net.minecraft.world.level.block.state.BlockState set(final net.min } public static Direction fromRotation(int i) { - switch (i) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.SOUTH_SOUTHWEST; - case 2: - return Direction.SOUTHWEST; - case 3: - return Direction.WEST_SOUTHWEST; - case 4: - return Direction.WEST; - case 5: - return Direction.WEST_NORTHWEST; - case 6: - return Direction.NORTHWEST; - case 7: - return Direction.NORTH_NORTHWEST; - case 8: - return Direction.NORTH; - case 9: - return Direction.NORTH_NORTHEAST; - case 10: - return Direction.NORTHEAST; - case 11: - return Direction.EAST_NORTHEAST; - case 12: - return Direction.EAST; - case 13: - return Direction.EAST_SOUTHEAST; - case 14: - return Direction.SOUTHEAST; - case 15: - return Direction.SOUTH_SOUTHEAST; - default: - return Direction.NORTH; - } + return switch (i) { + case 0 -> Direction.SOUTH; + case 1 -> Direction.SOUTH_SOUTHWEST; + case 2 -> Direction.SOUTHWEST; + case 3 -> Direction.WEST_SOUTHWEST; + case 4 -> Direction.WEST; + case 5 -> Direction.WEST_NORTHWEST; + case 6 -> Direction.NORTHWEST; + case 7 -> Direction.NORTH_NORTHWEST; + case 8 -> Direction.NORTH; + case 9 -> Direction.NORTH_NORTHEAST; + case 10 -> Direction.NORTHEAST; + case 11 -> Direction.EAST_NORTHEAST; + case 12 -> Direction.EAST; + case 13 -> Direction.EAST_SOUTHEAST; + case 14 -> Direction.SOUTHEAST; + case 15 -> Direction.SOUTH_SOUTHEAST; + default -> Direction.NORTH; + }; } public static int toRotation(final Direction direction) { - switch (direction) { - case SOUTH: - return 0; - case SOUTH_SOUTHWEST: - return 1; - case SOUTHWEST: - return 2; - case WEST_SOUTHWEST: - return 3; - case WEST: - return 4; - case WEST_NORTHWEST: - return 5; - case NORTHWEST: - return 6; - case NORTH_NORTHWEST: - return 7; - case NORTH: - return 8; - case NORTH_NORTHEAST: - return 9; - case NORTHEAST: - return 10; - case EAST_NORTHEAST: - return 11; - case EAST: - return 12; - case EAST_SOUTHEAST: - return 13; - case SOUTHEAST: - return 14; - case SOUTH_SOUTHEAST: - return 15; - default: - return 0; - } + return switch (direction) { + case SOUTH -> 0; + case SOUTH_SOUTHWEST -> 1; + case SOUTHWEST -> 2; + case WEST_SOUTHWEST -> 3; + case WEST -> 4; + case WEST_NORTHWEST -> 5; + case NORTHWEST -> 6; + case NORTH_NORTHWEST -> 7; + case NORTH -> 8; + case NORTH_NORTHEAST -> 9; + case NORTHEAST -> 10; + case EAST_NORTHEAST -> 11; + case EAST -> 12; + case EAST_SOUTHEAST -> 13; + case SOUTHEAST -> 14; + case SOUTH_SOUTHEAST -> 15; + default -> 0; + }; } public static Direction fromHorizontalHanging(int i) { - switch (i) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.WEST; - case 2: - return Direction.NORTH; - case 3: - return Direction.EAST; - default: - return Direction.NORTH; - } + return switch (i) { + case 0 -> Direction.SOUTH; + case 1 -> Direction.WEST; + case 2 -> Direction.NORTH; + case 3 -> Direction.EAST; + default -> Direction.NORTH; + }; } public static int toHorizontalHanging(Direction direction) { - switch (direction) { - case SOUTH: - return 0; - case WEST: - return 1; - case NORTH: - return 2; - case EAST: - return 3; - default: - return 0; - } + return switch (direction) { + case SOUTH -> 0; + case WEST -> 1; + case NORTH -> 2; + case EAST -> 3; + default -> 0; + }; } public static Direction fromHanging(int i) { - switch (i) { - case 0: - return Direction.DOWN; - case 1: - return Direction.UP; - case 2: - return Direction.NORTH; - case 3: - return Direction.SOUTH; - case 4: - return Direction.WEST; - case 5: - return Direction.EAST; - default: - return Direction.DOWN; - } + return switch (i) { + case 0 -> Direction.DOWN; + case 1 -> Direction.UP; + case 2 -> Direction.NORTH; + case 3 -> Direction.SOUTH; + case 4 -> Direction.WEST; + case 5 -> Direction.EAST; + default -> Direction.DOWN; + }; } public static int toHanging(Direction direction) { - switch (direction) { - case DOWN: - return 0; - case UP: - return 1; - case NORTH: - return 2; - case SOUTH: - return 3; - case WEST: - return 4; - case EAST: - return 5; - default: - return 0; - } + return switch (direction) { + case DOWN -> 0; + case UP -> 1; + case NORTH -> 2; + case SOUTH -> 3; + case WEST -> 4; + case EAST -> 5; + default -> 0; + }; } public static int directionToIndex(final Direction direction) { - switch (direction) { - case NORTH: - case NORTHEAST: - case NORTHWEST: - return 0; - case SOUTH: - case SOUTHEAST: - case SOUTHWEST: - return 1; - case EAST: - return 2; - case WEST: - return 3; - default: - throw new IllegalArgumentException("Unexpected direction"); - } + return switch (direction) { + case NORTH, NORTHEAST, NORTHWEST -> 0; + case SOUTH, SOUTHEAST, SOUTHWEST -> 1; + case EAST -> 2; + case WEST -> 3; + default -> throw new IllegalArgumentException("Unexpected direction"); + }; } private DirectionUtil() { diff --git a/src/main/java/org/spongepowered/common/util/DyeColorUtil.java b/src/main/java/org/spongepowered/common/util/DyeColorUtil.java index 8a81546118f..fa690dafe0b 100644 --- a/src/main/java/org/spongepowered/common/util/DyeColorUtil.java +++ b/src/main/java/org/spongepowered/common/util/DyeColorUtil.java @@ -24,11 +24,11 @@ */ package org.spongepowered.common.util; +import net.minecraft.data.loot.packs.LootData; import net.minecraft.world.item.DyeColor; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import org.spongepowered.common.accessor.world.entity.animal.SheepAccessor; import java.util.HashMap; import java.util.Map; @@ -36,7 +36,7 @@ public class DyeColorUtil { - public static final Map COLOR_BY_WOOL = SheepAccessor.accessor$ITEM_BY_DYE().entrySet() + public static final Map COLOR_BY_WOOL = LootData.WOOL_ITEM_BY_DYE.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); diff --git a/src/main/java/org/spongepowered/common/util/ReflectionUtil.java b/src/main/java/org/spongepowered/common/util/ReflectionUtil.java index 557baa4bed3..6328a3e6616 100644 --- a/src/main/java/org/spongepowered/common/util/ReflectionUtil.java +++ b/src/main/java/org/spongepowered/common/util/ReflectionUtil.java @@ -28,7 +28,6 @@ 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.Block; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.apache.logging.log4j.Marker; @@ -47,40 +46,16 @@ public final class ReflectionUtil { public static final Marker REFLECTION_SCANNING = MarkerManager.getMarker("REFLECTION_SCANNING"); - private static final Class[] NEIGHBOR_CHANGED_METHOD_ARGS = { - BlockState.class, - Level.class, - BlockPos.class, - Block.class, - BlockPos.class, - boolean.class - }; private static final Class[] ENTITY_INSIDE_METHOD_ARGS = { BlockState.class, Level.class, BlockPos.class, Entity.class }; - private static final Class[] STEP_ON_METHOD_ARGS = { - Level.class, - BlockPos.class, - BlockState.class, - Entity.class - }; private static final Class[] PLAYER_TOUCH_METHOD_ARGS= { Player.class }; - public static boolean isNeighborChangedDeclared(final Class targetClass) { - return ReflectionUtil.doesMethodExist( - targetClass, - Block.class, - "neighborChanged", - ReflectionUtil.NEIGHBOR_CHANGED_METHOD_ARGS, - void.class - ); - } - public static boolean isEntityInsideDeclared(final Class targetClass) { return ReflectionUtil.doesMethodExist( targetClass, @@ -91,16 +66,6 @@ public static boolean isEntityInsideDeclared(final Class targetClass) { ); } - public static boolean isStepOnDeclared(final Class targetClass) { - return ReflectionUtil.doesMethodExist( - targetClass, - Block.class, - "stepOn", - ReflectionUtil.STEP_ON_METHOD_ARGS, - void.class - ); - } - public static boolean isPlayerTouchDeclared(final Class targetClass) { return ReflectionUtil.doesMethodExist( targetClass, diff --git a/src/main/java/org/spongepowered/common/util/TristateUtil.java b/src/main/java/org/spongepowered/common/util/TristateUtil.java deleted file mode 100644 index eb28df33435..00000000000 --- a/src/main/java/org/spongepowered/common/util/TristateUtil.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.util; - -import com.google.common.collect.EnumBiMap; -import net.minecraft.world.InteractionResult; -import org.spongepowered.api.util.Tristate; - -public final class TristateUtil { - - private static final EnumBiMap map = EnumBiMap.create(InteractionResult.class, Tristate.class); - - static { - TristateUtil.map.put(InteractionResult.FAIL, Tristate.FALSE); - TristateUtil.map.put(InteractionResult.PASS, Tristate.UNDEFINED); - TristateUtil.map.put(InteractionResult.SUCCESS, Tristate.TRUE); - } - - public static Tristate fromActionResult(final InteractionResult result) { - return TristateUtil.map.get(result); - } - - public static InteractionResult toActionResult(final Tristate tristate) { - return TristateUtil.map.inverse().get(tristate); - } - - private TristateUtil() { - } -} diff --git a/src/main/java/org/spongepowered/common/world/SpongeExplosionBuilder.java b/src/main/java/org/spongepowered/common/world/SpongeExplosionBuilder.java index 52a6f8486aa..b1ebdd6ef6b 100644 --- a/src/main/java/org/spongepowered/common/world/SpongeExplosionBuilder.java +++ b/src/main/java/org/spongepowered/common/world/SpongeExplosionBuilder.java @@ -24,18 +24,18 @@ */ package org.spongepowered.common.world; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.sounds.SoundEvents; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Explosion.BlockInteraction; -import net.minecraft.world.level.Level; +import net.minecraft.world.level.ServerExplosion; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.world.World; import org.spongepowered.api.world.explosion.Explosion; +import org.spongepowered.api.world.explosion.ExplosionBlockInteraction; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.common.bridge.world.level.ExplosionBridge; import org.spongepowered.common.util.Preconditions; +import org.spongepowered.common.util.VecHelper; import org.spongepowered.math.vector.Vector3d; import java.util.Objects; @@ -46,13 +46,14 @@ public class SpongeExplosionBuilder implements Explosion.Builder { @Nullable private Explosive sourceExplosive; private float radius; private boolean canCauseFire; - private boolean shouldBreakBlocks = true; + private net.minecraft.world.level.Explosion.BlockInteraction blockInteraction; private boolean shouldSmoke; private boolean shouldDamageEntities = true; private int resolution = 16; private float randomness = 1.0F; private double knockback = 1; + public SpongeExplosionBuilder() { this.reset(); } @@ -94,11 +95,12 @@ public Explosion.Builder shouldPlaySmoke(boolean smoke) { } @Override - public Explosion.Builder shouldBreakBlocks(boolean destroy) { - this.shouldBreakBlocks = destroy; + public Explosion.Builder blockInteraction(final ExplosionBlockInteraction interaction) { + this.blockInteraction = (net.minecraft.world.level.Explosion.BlockInteraction) (Object) interaction; return this; } + @Override public Explosion.Builder resolution(int resolution) { //A value of 1 would cause a DivideByZeroException @@ -124,7 +126,7 @@ public Explosion.Builder from(Explosion value) { this.sourceExplosive = value.sourceExplosive().orElse(null); this.radius = value.radius(); this.canCauseFire = value.canCauseFire(); - this.shouldBreakBlocks = value.shouldBreakBlocks(); + this.blockInteraction = ((ServerExplosion) value).getBlockInteraction(); this.shouldSmoke = value.shouldPlaySmoke(); this.shouldDamageEntities = value.shouldDamageEntities(); this.resolution = value.resolution(); @@ -136,10 +138,10 @@ public Explosion.Builder from(Explosion value) { @Override public SpongeExplosionBuilder reset() { this.location = null; + this.blockInteraction = null; this.sourceExplosive = null; this.radius = 0; this.canCauseFire = false; - this.shouldBreakBlocks = true; this.shouldSmoke = false; this.shouldDamageEntities = true; this.resolution = 16; @@ -155,14 +157,9 @@ public Explosion build() throws IllegalStateException { final World world = this.location.world(); final Vector3d origin = this.location.position(); - final net.minecraft.world.level.Explosion explosion = new net.minecraft.world.level.Explosion((Level) world, - (Entity) this.sourceExplosive, null, null, origin.x(), origin.y(), origin.z(), this.radius, - this.canCauseFire, this.shouldBreakBlocks ? BlockInteraction.DESTROY : BlockInteraction.KEEP, - // TODO configurable explosion particles & sound? - ParticleTypes.EXPLOSION, - ParticleTypes.EXPLOSION_EMITTER, - SoundEvents.GENERIC_EXPLODE); - ((ExplosionBridge) explosion).bridge$setShouldBreakBlocks(this.shouldBreakBlocks); + final var explosion = new net.minecraft.world.level.ServerExplosion((ServerLevel) world, + (Entity) this.sourceExplosive, null, null, VecHelper.toVanillaVector3d(origin), this.radius, + this.canCauseFire, this.blockInteraction); ((ExplosionBridge) explosion).bridge$setShouldDamageEntities(this.shouldDamageEntities); ((ExplosionBridge) explosion).bridge$setShouldPlaySmoke(this.shouldSmoke); ((ExplosionBridge) explosion).bridge$setResolution(this.resolution); diff --git a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeProviderFactory.java b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeProviderFactory.java index 44d1b9fdcd8..5e41f562610 100644 --- a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeProviderFactory.java +++ b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeProviderFactory.java @@ -61,7 +61,7 @@ public final class SpongeBiomeProviderFactory implements BiomeProvider.Factory { @Override public ConfigurableBiomeProvider overworld() { final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); return (ConfigurableBiomeProvider) MultiNoiseBiomeSource.createFromPreset(holder); } @@ -77,7 +77,7 @@ public ConfigurableBiomeProvider multiNoise(final MultiNo @Override public ConfigurableBiomeProvider nether() { final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); return (ConfigurableBiomeProvider) MultiNoiseBiomeSource.createFromPreset(holder); } @@ -94,7 +94,7 @@ public ConfigurableBiomeProvider endStyle(final EndStyleBio @Override public ConfigurableBiomeProvider end() { - return (ConfigurableBiomeProvider) TheEndBiomeSource.create(this.registry().asLookup()); + return (ConfigurableBiomeProvider) TheEndBiomeSource.create(this.registry()); } @Override @@ -114,6 +114,6 @@ private Registry registry() { } private Holder biomeHolder(final RegistryReference biome) { - return this.registry().getHolderOrThrow(ResourceKey.create(Registries.BIOME, (ResourceLocation) (Object) biome.location())); + return this.registry().getOrThrow(ResourceKey.create(Registries.BIOME, (ResourceLocation) (Object) biome.location())); } } diff --git a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java index cea046cce1d..481ed65a69c 100644 --- a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java +++ b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java @@ -63,7 +63,6 @@ import org.spongepowered.api.world.biome.spawner.NaturalSpawnCost; import org.spongepowered.api.world.biome.spawner.NaturalSpawner; import org.spongepowered.api.world.generation.carver.Carver; -import org.spongepowered.api.world.generation.carver.CarvingStep; import org.spongepowered.api.world.generation.feature.DecorationStep; import org.spongepowered.api.world.generation.feature.PlacedFeature; import org.spongepowered.common.SpongeCommon; @@ -185,7 +184,7 @@ protected BiomeTemplate build0() { final Map, NaturalSpawnCost> spawnerCosts = this.manipulator.getOrElse(Keys.NATURAL_SPAWNER_COST, Map.of()); final Map> features = this.manipulator.getOrElse(Keys.FEATURES, Map.of()); - final Map> carvers = this.manipulator.getOrElse(Keys.CARVERS, Map.of()); + final List carvers = this.manipulator.getOrElse(Keys.CARVERS, List.of()); final BiomeSpecialEffects.Builder effectsBuilder = new BiomeSpecialEffects.Builder() .fogColor(fogColor.rgb()) @@ -196,7 +195,7 @@ protected BiomeTemplate build0() { foliageColor.ifPresent(c -> effectsBuilder.foliageColorOverride(c.rgb())); grassColor.ifPresent(c -> effectsBuilder.grassColorOverride(c.rgb())); particleSettings.ifPresent(ps -> effectsBuilder.ambientParticle((AmbientParticleSettings) ps)); - ambientSound.ifPresent(s -> effectsBuilder.ambientLoopSound(Holder.direct((SoundEvent) s))); + ambientSound.ifPresent(s -> effectsBuilder.ambientLoopSound(Holder.direct((SoundEvent) (Object) s))); ambientMood.ifPresent(m -> effectsBuilder.ambientMoodSound((net.minecraft.world.level.biome.AmbientMoodSettings) m)); additionalSound.ifPresent(s -> effectsBuilder.ambientAdditionsSound((AmbientAdditionsSettings) s)); backgroundMusic.ifPresent(m -> effectsBuilder.backgroundMusic((Music) m)); @@ -211,11 +210,10 @@ protected BiomeTemplate build0() { final Registry placedFeatureRegistry = SpongeCommon.vanillaRegistry(Registries.PLACED_FEATURE); final Registry> configuredWorldCarverRegistry = SpongeCommon.vanillaRegistry(Registries.CONFIGURED_CARVER); - final BiomeGenerationSettings.Builder generationBuilder = new BiomeGenerationSettings.Builder(placedFeatureRegistry.asLookup(), configuredWorldCarverRegistry.asLookup()); + final BiomeGenerationSettings.Builder generationBuilder = new BiomeGenerationSettings.Builder(placedFeatureRegistry, configuredWorldCarverRegistry); features.forEach((step, list) -> list.forEach(feature -> generationBuilder.addFeature((GenerationStep.Decoration) (Object) step, Holder.direct((net.minecraft.world.level.levelgen.placement.PlacedFeature) (Object) feature)))); - carvers.forEach((step, list) -> list.forEach(carver -> generationBuilder.addCarver((GenerationStep.Carving) (Object) step, - Holder.direct((ConfiguredWorldCarver) (Object) carver)))); + carvers.forEach((carver) -> generationBuilder.addCarver(Holder.direct((ConfiguredWorldCarver) (Object) carver))); final Biome.BiomeBuilder vanillaBuilder = new Biome.BiomeBuilder() .hasPrecipitation(precipitation) diff --git a/src/main/java/org/spongepowered/common/world/biome/ambient/SpongeSoundConfigFactory.java b/src/main/java/org/spongepowered/common/world/biome/ambient/SpongeSoundConfigFactory.java index 425d535c24c..286d309f889 100644 --- a/src/main/java/org/spongepowered/common/world/biome/ambient/SpongeSoundConfigFactory.java +++ b/src/main/java/org/spongepowered/common/world/biome/ambient/SpongeSoundConfigFactory.java @@ -36,16 +36,16 @@ public class SpongeSoundConfigFactory implements SoundConfig.Factory { @Override public SoundConfig.Mood ofAmbientMood(final SoundType sound, final int tickDelay, final int searchRadius, final double distanceModifier) { - return (SoundConfig.Mood) new AmbientMoodSettings(Holder.direct((SoundEvent) sound), tickDelay, searchRadius, distanceModifier); + return (SoundConfig.Mood) new AmbientMoodSettings(Holder.direct((SoundEvent) (Object) sound), tickDelay, searchRadius, distanceModifier); } @Override public SoundConfig.Additional ofAdditional(final SoundType sound, final double tickChance) { - return (SoundConfig.Additional) new AmbientAdditionsSettings(Holder.direct((SoundEvent) sound), tickChance); + return (SoundConfig.Additional) new AmbientAdditionsSettings(Holder.direct((SoundEvent) (Object) sound), tickChance); } @Override public SoundConfig.BackgroundMusic ofBackroundMusic(final SoundType sound, final int minDelay, final int maxDelay, final boolean replacesCurrent) { - return (SoundConfig.BackgroundMusic) new Music(Holder.direct((SoundEvent) sound), minDelay, maxDelay, replacesCurrent); + return (SoundConfig.BackgroundMusic) new Music(Holder.direct((SoundEvent) (Object) sound), minDelay, maxDelay, replacesCurrent); } } diff --git a/src/main/java/org/spongepowered/common/world/biome/provider/SpongeMultiNoiseBiomeConfig.java b/src/main/java/org/spongepowered/common/world/biome/provider/SpongeMultiNoiseBiomeConfig.java index 8ce6d49e842..8d6a39836ad 100644 --- a/src/main/java/org/spongepowered/common/world/biome/provider/SpongeMultiNoiseBiomeConfig.java +++ b/src/main/java/org/spongepowered/common/world/biome/provider/SpongeMultiNoiseBiomeConfig.java @@ -131,7 +131,7 @@ public static final class FactoryImpl implements Factory { @Override public MultiNoiseBiomeConfig nether() { final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); final var biomeSource = (MultiNoiseBiomeSourceAccessor) MultiNoiseBiomeSource.createFromPreset(holder); return new BuilderImpl().addMcBiomes(biomeSource.accessor$parameters()).build(); } @@ -139,7 +139,7 @@ public MultiNoiseBiomeConfig nether() { @Override public MultiNoiseBiomeConfig overworld() { final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); final var biomeSource = (MultiNoiseBiomeSourceAccessor) MultiNoiseBiomeSource.createFromPreset(holder); return new BuilderImpl().addMcBiomes(biomeSource.accessor$parameters()).build(); } diff --git a/src/main/java/org/spongepowered/common/world/generation/SpongeChunkGeneratorFactory.java b/src/main/java/org/spongepowered/common/world/generation/SpongeChunkGeneratorFactory.java index 81c290117ee..9c52d42e4b0 100644 --- a/src/main/java/org/spongepowered/common/world/generation/SpongeChunkGeneratorFactory.java +++ b/src/main/java/org/spongepowered/common/world/generation/SpongeChunkGeneratorFactory.java @@ -72,26 +72,26 @@ public ConfigurableChunkGenerator noise(final BiomeProvide public ConfigurableChunkGenerator overworld() { var noiseGeneratorSettingsRegistry = SpongeCommon.vanillaRegistry(Registries.NOISE_SETTINGS); final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD); final var biomeSource = MultiNoiseBiomeSource.createFromPreset(holder); - return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getHolderOrThrow(NoiseGeneratorSettings.OVERWORLD)); + return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.OVERWORLD)); } @Override public ConfigurableChunkGenerator theNether() { var noiseGeneratorSettingsRegistry = SpongeCommon.vanillaRegistry(Registries.NOISE_SETTINGS); final var registry = SpongeCommon.vanillaRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); - final var holder = registry.getHolderOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); + final var holder = registry.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER); final var biomeSource = MultiNoiseBiomeSource.createFromPreset(holder); - return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getHolderOrThrow(NoiseGeneratorSettings.NETHER)); + return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.NETHER)); } @Override public ConfigurableChunkGenerator theEnd() { var biomeRegistry = SpongeCommon.vanillaRegistry(Registries.BIOME); var noiseGeneratorSettingsRegistry = SpongeCommon.vanillaRegistry(Registries.NOISE_SETTINGS); - var biomeSource = TheEndBiomeSource.create(biomeRegistry.asLookup()); - return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getHolderOrThrow(NoiseGeneratorSettings.END)); + var biomeSource = TheEndBiomeSource.create(biomeRegistry); + return this.noiseBasedChunkGenerator(biomeSource, noiseGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.END)); } @Override diff --git a/src/main/java/org/spongepowered/common/world/generation/config/flat/SpongeFlatGeneratorConfig.java b/src/main/java/org/spongepowered/common/world/generation/config/flat/SpongeFlatGeneratorConfig.java index 0581d934635..40eb67f8158 100644 --- a/src/main/java/org/spongepowered/common/world/generation/config/flat/SpongeFlatGeneratorConfig.java +++ b/src/main/java/org/spongepowered/common/world/generation/config/flat/SpongeFlatGeneratorConfig.java @@ -138,10 +138,10 @@ public FlatGeneratorConfig.Builder from(final FlatGeneratorConfig value) { throw new IllegalStateException("Flat generation requires at least 1 Layer!"); } final Registry biomeRegistry = SpongeCommon.vanillaRegistry(Registries.BIOME); - final HolderLookup.RegistryLookup placedFeatureRegistryLookup = SpongeCommon.vanillaRegistry(Registries.PLACED_FEATURE).asLookup(); + final HolderLookup.RegistryLookup placedFeatureRegistryLookup = SpongeCommon.vanillaRegistry(Registries.PLACED_FEATURE); final Holder.Reference biome = - biomeRegistry.asLookup().getOrThrow(ResourceKey.create(Registries.BIOME, (ResourceLocation) (Object) this.biome.location())); + biomeRegistry.getOrThrow(ResourceKey.create(Registries.BIOME, (ResourceLocation) (Object) this.biome.location())); return (FlatGeneratorConfig) FlatLevelGeneratorSettingsAccessor.invoker$new( this.structureSets == null ? Optional.empty() : Optional.of(HolderSet.direct((Function) Holder::direct, this.structureSets)), (List) (Object) this.layers, diff --git a/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java b/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java index 637c7386973..77a0b06ab0c 100644 --- a/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java @@ -131,7 +131,7 @@ public Builder feature(final Feature feature) { if (key == null) { this.feature = Holder.direct((ConfiguredFeature) (Object) feature); } else { - this.feature = registry.getHolderOrThrow(net.minecraft.resources.ResourceKey.create(Registries.CONFIGURED_FEATURE, key)); + this.feature = registry.getOrThrow(net.minecraft.resources.ResourceKey.create(Registries.CONFIGURED_FEATURE, key)); } return this; } @@ -141,7 +141,7 @@ public Builder feature(final FeatureTemplate feature) { final Registry> registry = SpongeCommon.vanillaRegistry(Registries.CONFIGURED_FEATURE); final net.minecraft.resources.ResourceKey> key = net.minecraft.resources.ResourceKey.create(Registries.CONFIGURED_FEATURE, ((ResourceLocation) (Object) feature.key())); - this.feature = Holder.Reference.createStandAlone(registry.asLookup(), key); + this.feature = Holder.Reference.createStandAlone(registry, key); return this; } diff --git a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructurePlacementBuilder.java b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructurePlacementBuilder.java index 4c8d9b61c12..60ed58a9dad 100644 --- a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructurePlacementBuilder.java +++ b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructurePlacementBuilder.java @@ -28,7 +28,6 @@ import net.minecraft.core.Registry; import net.minecraft.core.Vec3i; import net.minecraft.core.registries.Registries; -import net.minecraft.tags.TagKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement; import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement; @@ -154,7 +153,8 @@ public ConcentricRings count(final int count) { @Override public ConcentricRings preferredBiomes(final Tag preferredBiomes) { final Registry registry = SpongeCommon.vanillaRegistry(Registries.BIOME); - this.preferredBiomes = registry.getOrCreateTag((TagKey) (Object) preferredBiomes); + // TODO - Snapshot 24w34a +// this.preferredBiomes = registry.getOrCreateTag((TagKey) (Object) preferredBiomes); return this; } diff --git a/src/main/java/org/spongepowered/common/world/level/chunk/storage/SpongeEntityChunk.java b/src/main/java/org/spongepowered/common/world/level/chunk/storage/SpongeEntityChunk.java index 67f5bce8b7c..ba21ecb1e0a 100644 --- a/src/main/java/org/spongepowered/common/world/level/chunk/storage/SpongeEntityChunk.java +++ b/src/main/java/org/spongepowered/common/world/level/chunk/storage/SpongeEntityChunk.java @@ -76,7 +76,7 @@ public SpongeEntityChunk(final ServerLevel level, final Vector3i chunkPosition, public Vector3i min() { if (this.blockMin == null) { if (this.chunkLayout == null) { - this.chunkLayout = new SpongeChunkLayout(this.level.getMinBuildHeight(), this.level.getHeight()); + this.chunkLayout = new SpongeChunkLayout(this.level.getMinY(), this.level.getHeight()); } this.blockMin = this.chunkLayout.forceToWorld(this.chunkPosition); } @@ -87,7 +87,7 @@ public Vector3i min() { public Vector3i max() { if (this.blockMax == null) { if (this.chunkLayout == null) { - this.chunkLayout = new SpongeChunkLayout(this.level.getMinBuildHeight(), this.level.getHeight()); + this.chunkLayout = new SpongeChunkLayout(this.level.getMinY(), this.level.getHeight()); } this.blockMax = this.min().add(this.chunkLayout.chunkSize()).sub(1, 1, 1); } diff --git a/src/main/java/org/spongepowered/common/world/portal/SpongeCompositePortalLogic.java b/src/main/java/org/spongepowered/common/world/portal/SpongeCompositePortalLogic.java index 9e5f9112353..f517ca6991c 100644 --- a/src/main/java/org/spongepowered/common/world/portal/SpongeCompositePortalLogic.java +++ b/src/main/java/org/spongepowered/common/world/portal/SpongeCompositePortalLogic.java @@ -27,7 +27,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.jetbrains.annotations.Nullable; import org.spongepowered.api.util.Axis; import org.spongepowered.api.world.portal.Portal; @@ -50,7 +50,7 @@ public SpongeCompositePortalLogic(final List p.getPortalDestination(sourceLevel, entity, portalPos)) .filter(Objects::nonNull) diff --git a/src/main/java/org/spongepowered/common/world/portal/SpongeCustomPortalLogic.java b/src/main/java/org/spongepowered/common/world/portal/SpongeCustomPortalLogic.java index 65bf3c1c70d..7e73377ce5f 100644 --- a/src/main/java/org/spongepowered/common/world/portal/SpongeCustomPortalLogic.java +++ b/src/main/java/org/spongepowered/common/world/portal/SpongeCustomPortalLogic.java @@ -27,7 +27,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.util.Axis; import org.spongepowered.api.world.portal.Portal; @@ -60,7 +60,7 @@ public SpongeCustomPortalLogic(final PortalLogic.PortalExitCalculator calulator, } @Nullable @Override - public DimensionTransition getPortalDestination(final ServerLevel fromLevel, final Entity entity, final BlockPos fromPos) { + public TeleportTransition getPortalDestination(final ServerLevel fromLevel, final Entity entity, final BlockPos fromPos) { final var spongeEntity = (org.spongepowered.api.entity.Entity) entity; // Calculate desired portal location // Then find existing portal or generate if not found @@ -70,14 +70,14 @@ public DimensionTransition getPortalDestination(final ServerLevel fromLevel, fin ).orElse(null); } - private static DimensionTransition generateTransition(final Entity entity, final ServerLocation finalExit) { - return new DimensionTransition( + private static TeleportTransition generateTransition(final Entity entity, final ServerLocation finalExit) { + return new TeleportTransition( (ServerLevel) finalExit.world(), VecHelper.toVanillaVector3d(finalExit.position()), entity.getDeltaMovement(), entity.getYRot(), entity.getXRot(), - DimensionTransition.PLACE_PORTAL_TICKET); + TeleportTransition.PLACE_PORTAL_TICKET); } @Override diff --git a/src/main/java/org/spongepowered/common/world/schematic/SchematicTranslator.java b/src/main/java/org/spongepowered/common/world/schematic/SchematicTranslator.java index d3c32a85a77..54b41bbb76d 100644 --- a/src/main/java/org/spongepowered/common/world/schematic/SchematicTranslator.java +++ b/src/main/java/org/spongepowered/common/world/schematic/SchematicTranslator.java @@ -327,7 +327,7 @@ private static void deserializeBiomeContainer( .orElseThrow(() -> new InvalidDataException("Missing BiomePalette as required by the schematic spec")); final Set biomeKeys = biomeMap.keys(false); - final Registry biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(SpongeCommon.server().registryAccess().registryOrThrow(Registries.BIOME)); + final Registry biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(SpongeCommon.server().registryAccess().lookupOrThrow(Registries.BIOME)); biomePalette = new MutableBimapPalette<>( PaletteTypes.BIOME_PALETTE.get(), biomeRegistry, @@ -454,7 +454,7 @@ public DataView addTo(final Schematic schematic, final DataView data) { final Registry blockRegistry = VolumeStreamUtils.nativeToSpongeRegistry( - SpongeCommon.server().registryAccess().registryOrThrow(Registries.BLOCK)); + SpongeCommon.server().registryAccess().lookupOrThrow(Registries.BLOCK)); SchematicTranslator.writePaletteToView( blockData, palette, blockRegistry, Constants.Sponge.Schematic.BLOCK_PALETTE, BlockState::type, @@ -506,7 +506,7 @@ public DataView addTo(final Schematic schematic, final DataView data) { // Should never reach here. } - final Registry biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(SpongeCommon.server().registryAccess().registryOrThrow(Registries.BIOME)); + final Registry biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(SpongeCommon.server().registryAccess().lookupOrThrow(Registries.BIOME)); SchematicTranslator.writePaletteToView( biomeContainer, biomePalette, biomeRegistry, Constants.Sponge.Schematic.BIOME_PALETTE, diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java index 332f4d325c2..2ded515fb9b 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java @@ -279,7 +279,7 @@ public CompletableFuture loadWorld(final ResourceKey key) { // First find a loaded level-stem / To load based on a datapack load using the WorldTemplate instead final net.minecraft.resources.ResourceKey rKey = net.minecraft.resources.ResourceKey.create(Registries.LEVEL_STEM, (ResourceLocation) (Object) key); - final LevelStem levelStem = SpongeCommon.vanillaRegistry(Registries.LEVEL_STEM).get(rKey); + final LevelStem levelStem = SpongeCommon.vanillaRegistry(Registries.LEVEL_STEM).getValue(rKey); if (levelStem != null) { return this.loadWorld0(registryKey, levelStem); } @@ -337,7 +337,7 @@ private LevelSettings createLevelSettings(final PrimaryLevelData defaultLevelDat hardcore == null ? defaultLevelData.isHardcore() : hardcore, difficulty == null ? defaultLevelData.getDifficulty() : difficulty, allowCommands == null ? defaultLevelData.isAllowCommands() : allowCommands, - defaultLevelData.getGameRules().copy(), + defaultLevelData.getGameRules().copy(defaultLevelData.enabledFeatures()), defaultLevelData.getDataConfiguration()); } @@ -795,7 +795,7 @@ private PrimaryLevelData getOrCreateLevelData(@Nullable final Dynamic dynamic } private PrimaryLevelData loadLevelData(final RegistryAccess.Frozen access, final WorldDataConfiguration datapackConfig, final Dynamic dataTag) { - final LevelDataAndDimensions levelData = LevelStorageSource.getLevelDataAndDimensions(dataTag, datapackConfig, access.registryOrThrow(Registries.LEVEL_STEM), access); + final LevelDataAndDimensions levelData = LevelStorageSource.getLevelDataAndDimensions(dataTag, datapackConfig, access.lookupOrThrow(Registries.LEVEL_STEM), access); return (PrimaryLevelData) levelData.worldData(); } @@ -888,7 +888,7 @@ private ServerLevel prepareWorld(final ServerLevel world) { } } else if (levelData.worldGenOptions().generateBonusChest()) { final BlockPos pos = levelData.getSpawnPos(); - final ConfiguredFeature bonusChestFeature = SpongeCommon.vanillaRegistry(Registries.CONFIGURED_FEATURE).get(MiscOverworldFeatures.BONUS_CHEST); + final ConfiguredFeature bonusChestFeature = SpongeCommon.vanillaRegistry(Registries.CONFIGURED_FEATURE).getValue(MiscOverworldFeatures.BONUS_CHEST); bonusChestFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos); } levelData.setInitialized(true); diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java index 96183174218..05a87b59d10 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java @@ -289,12 +289,12 @@ protected WorldTemplate build0() { @NonNull private static Holder dimensionTypeHolder(final WorldType worldType) { - final Registry dimensionTypeRegistry = SpongeCommon.server().registryAccess().registryOrThrow(Registries.DIMENSION_TYPE); + final Registry dimensionTypeRegistry = SpongeCommon.server().registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE); final ResourceLocation key = dimensionTypeRegistry.getKey((DimensionType) (Object) worldType); if (key == null) { return Holder.direct((DimensionType) (Object) worldType); } - return dimensionTypeRegistry.getHolderOrThrow(net.minecraft.resources.ResourceKey.create(Registries.DIMENSION_TYPE, key)); + return dimensionTypeRegistry.getOrThrow(net.minecraft.resources.ResourceKey.create(Registries.DIMENSION_TYPE, key)); } } diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java index b5ae4af961c..586e9d4380d 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java @@ -139,7 +139,7 @@ public Builder reset() { this.data = DataManipulator.mutableOf(); this.key = null; this.pack = DataPacks.WORLD_TYPE; - final DimensionType defaultOverworld = SpongeCommon.vanillaRegistry(Registries.DIMENSION_TYPE).get(BuiltinDimensionTypes.OVERWORLD); + final DimensionType defaultOverworld = SpongeCommon.vanillaRegistry(Registries.DIMENSION_TYPE).getValue(BuiltinDimensionTypes.OVERWORLD); this.fromValue((WorldType) (Object) defaultOverworld); return this; } diff --git a/src/main/java/org/spongepowered/common/world/teleport/ConfigTeleportHelperFilter.java b/src/main/java/org/spongepowered/common/world/teleport/ConfigTeleportHelperFilter.java index 8349954ede6..ee6f96040e5 100644 --- a/src/main/java/org/spongepowered/common/world/teleport/ConfigTeleportHelperFilter.java +++ b/src/main/java/org/spongepowered/common/world/teleport/ConfigTeleportHelperFilter.java @@ -66,7 +66,7 @@ private static void updateCacheIfNecessary() { final TeleportHelperCategory teleportHelperCat = SpongeConfigs.getCommon().get().teleportHelper; ConfigTeleportHelperFilter.floorBlockTypes = teleportHelperCat.unsafeFloorBlocks.stream() .map(x -> ResourceKey.resolve(x.toLowerCase(Locale.ENGLISH))) - .map(x -> (BlockType) blockRegistry.get((ResourceLocation) (Object) x)) + .map(x -> (BlockType) blockRegistry.getValue((ResourceLocation) (Object) x)) .filter(Objects::nonNull) .collect(Collectors.toList()); @@ -79,7 +79,7 @@ private static void updateCacheIfNecessary() { ConfigTeleportHelperFilter.bodyBlockTypes = teleportHelperCat.unsafeBlockBlocks.stream() .map(x -> ResourceKey.resolve(x.toLowerCase(Locale.ENGLISH))) - .map(x -> (BlockType) blockRegistry.get((ResourceLocation) (Object) x)) + .map(x -> (BlockType) blockRegistry.getValue((ResourceLocation) (Object) x)) .filter(Objects::nonNull) .collect(Collectors.toList()); diff --git a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java index 60b6d5a4af7..b6f2f0b20dd 100644 --- a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java +++ b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java @@ -34,6 +34,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Tuple; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; @@ -242,7 +243,7 @@ public static BiConsumer getOrCloneEnti return shouldCarbonCopy ? (pos, entity) -> { final CompoundTag nbt = new CompoundTag(); entity.save(nbt); - final net.minecraft.world.entity.@Nullable Entity cloned = entity.getType().create(level); + final net.minecraft.world.entity.@Nullable Entity cloned = entity.getType().create(level, EntitySpawnReason.COMMAND); Objects.requireNonNull( cloned, () -> String.format( @@ -320,7 +321,7 @@ public static boolean setBiome(final ChunkAccess chunk, final int x, final int y ) { final boolean result = VolumeStreamUtils.setBiome(chunk.getSection(chunk.getSectionIndex(y)), x, y, z, biome); if (result) { - chunk.setUnsaved(true); + chunk.markUnsaved(); } return result; } @@ -508,7 +509,7 @@ public static > VolumeStream biomeRegistry = reader.registryAccess().registryOrThrow(Registries.BIOME); + final Registry biomeRegistry = reader.registryAccess().lookupOrThrow(Registries.BIOME); backingVolume = new ObjectArrayMutableBiomeBuffer(min, size, VolumeStreamUtils.nativeToSpongeRegistry(biomeRegistry)); } else { backingVolume = null; diff --git a/src/main/resources/common.accesswidener b/src/main/resources/common.accesswidener index 215cc24aa91..c370b151d43 100644 --- a/src/main/resources/common.accesswidener +++ b/src/main/resources/common.accesswidener @@ -12,9 +12,8 @@ accessible class net/minecraft/server/network/ServerLoginPacketListenerImpl$Stat extendable method net/minecraft/server/players/IpBanList getIpFromAddress (Ljava/net/SocketAddress;)Ljava/lang/String; accessible class net/minecraft/server/commands/TeleportCommand$LookAt extendable class net/minecraft/world/item/crafting/Ingredient -extendable method net/minecraft/world/item/crafting/Ingredient (Ljava/util/stream/Stream;)V -accessible field net/minecraft/world/item/crafting/Ingredient values [Lnet/minecraft/world/item/crafting/Ingredient$Value; -accessible class net/minecraft/world/item/crafting/Ingredient$Value +extendable method net/minecraft/world/item/crafting/Ingredient (Lnet/minecraft/core/HolderSet;)V +accessible field net/minecraft/world/item/crafting/Ingredient values Lnet/minecraft/core/HolderSet; accessible method net/minecraft/world/level/biome/Biome getTemperature (Lnet/minecraft/core/BlockPos;)F accessible class net/minecraft/server/level/ServerLevel$EntityCallbacks accessible class net/minecraft/network/protocol/game/ServerboundInteractPacket$Action diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/event/cause/entity/damage/DamageModifier_BuilderMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/event/cause/entity/damage/DamageModifier_BuilderMixin_ItemStackLike.java deleted file mode 100644 index 651609ec6ac..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/event/cause/entity/damage/DamageModifier_BuilderMixin_ItemStackLike.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.event.cause.entity.damage; - -import org.spongepowered.api.event.cause.entity.damage.DamageModifier; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = DamageModifier.Builder.class, remap = false) -public abstract class DamageModifier_BuilderMixin_ItemStackLike { - - public DamageModifier.Builder item(ItemStack itemStack) { - return ((DamageModifier.Builder) (Object) this).item(itemStack); - } - - public DamageModifier.Builder item(ItemStackSnapshot snapshot) { - return ((DamageModifier.Builder) (Object) this).item(snapshot); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/enchantment/EnchantmentTypeMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/enchantment/EnchantmentTypeMixin_ItemStackLike.java deleted file mode 100644 index 64fbebeb6ca..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/enchantment/EnchantmentTypeMixin_ItemStackLike.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.enchantment; - -import org.spongepowered.api.item.enchantment.EnchantmentType; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = EnchantmentType.class, remap = false) -public interface EnchantmentTypeMixin_ItemStackLike { - - default boolean canBeAppliedToStack(ItemStack stack) { - return ((EnchantmentType) this).canBeAppliedToStack(stack); - } - - default boolean canBeAppliedByTable(ItemStack stack) { - return ((EnchantmentType) this).canBeAppliedByTable(stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ArmorEquipableMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ArmorEquipableMixin_ItemStackLike.java deleted file mode 100644 index 364cfa752b8..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ArmorEquipableMixin_ItemStackLike.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory; - -import org.spongepowered.api.data.type.HandType; -import org.spongepowered.api.item.inventory.ArmorEquipable; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Supplier; - -@Mixin(value = ArmorEquipable.class, remap = false) -public interface ArmorEquipableMixin_ItemStackLike { - - default void setHead(ItemStack head) { - ((ArmorEquipable) this).setHead(head); - } - - default void setChest(ItemStack chest) { - ((ArmorEquipable) this).setChest(chest); - } - - default void setLegs(ItemStack legs) { - ((ArmorEquipable) this).setLegs(legs); - } - - default void setFeet(ItemStack feet) { - ((ArmorEquipable) this).setFeet(feet); - } - - default void setItemInHand(Supplier handType, ItemStack itemInHand) { - ((ArmorEquipable) this).setItemInHand(handType, itemInHand); - } - - default void setItemInHand(HandType handType, ItemStack itemInHand) { - ((ArmorEquipable) this).setItemInHand(handType, itemInHand); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ContainerMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ContainerMixin_ItemStackLike.java deleted file mode 100644 index 41d156060d8..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/ContainerMixin_ItemStackLike.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory; - -import org.spongepowered.api.item.inventory.Container; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = Container.class, remap = false) -public interface ContainerMixin_ItemStackLike { - - default boolean setCursor(ItemStack item) { - return ((Container) this).setCursor(item); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/InventoryMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/InventoryMixin_ItemStackLike.java deleted file mode 100644 index 1c3e2e1d5b3..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/InventoryMixin_ItemStackLike.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory; - -import org.spongepowered.api.item.inventory.Inventory; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = Inventory.class, remap = false) -public interface InventoryMixin_ItemStackLike { - - default InventoryTransactionResult offer(ItemStack... stacks) { - return ((Inventory) this).offer(stacks); - } - - default boolean canFit(ItemStack stack) { - return ((Inventory) this).canFit(stack); - } - - default InventoryTransactionResult offer(int index, ItemStack stack) { - return ((Inventory) this).offer(index, stack); - } - - default InventoryTransactionResult set(int index, ItemStack stack) { - return ((Inventory) this).set(index, stack); - } - - default boolean contains(ItemStack stack) { - return ((Inventory) this).contains(stack); - } - - default boolean containsAny(ItemStack stack) { - return ((Inventory) this).containsAny(stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/SlotMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/SlotMixin_ItemStackLike.java deleted file mode 100644 index aa7d328d3bb..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/SlotMixin_ItemStackLike.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.Slot; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = Slot.class, remap = false) -public interface SlotMixin_ItemStackLike { - - default InventoryTransactionResult set(ItemStack stack) { - return ((Slot) this).set(stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/equipment/EquipmentInventoryMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/equipment/EquipmentInventoryMixin_ItemStackLike.java deleted file mode 100644 index 87611017b43..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/equipment/EquipmentInventoryMixin_ItemStackLike.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.equipment; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.equipment.EquipmentInventory; -import org.spongepowered.api.item.inventory.equipment.EquipmentType; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Supplier; - -@Mixin(value = EquipmentInventory.class, remap = false) -public interface EquipmentInventoryMixin_ItemStackLike { - - default InventoryTransactionResult set(EquipmentType equipmentType, ItemStack stack) { - return ((EquipmentInventory) this).set(equipmentType, stack); - } - - default InventoryTransactionResult set(Supplier equipmentType, ItemStack stack) { - return ((EquipmentInventory) this).set(equipmentType, stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/FilteringSlotMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/FilteringSlotMixin_ItemStackLike.java deleted file mode 100644 index 47ad0ab29f4..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/slot/FilteringSlotMixin_ItemStackLike.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.slot; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.slot.FilteringSlot; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = FilteringSlot.class, remap = false) -public interface FilteringSlotMixin_ItemStackLike { - - default boolean isValidItem(ItemStack stack) { - return ((FilteringSlot) this).isValidItem(stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/InventoryTransactionResult_BuilderMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/InventoryTransactionResult_BuilderMixin_ItemStackLike.java deleted file mode 100644 index 51c5d822d0d..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/InventoryTransactionResult_BuilderMixin_ItemStackLike.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.transaction; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = InventoryTransactionResult.Builder.class, remap = false) -public interface InventoryTransactionResult_BuilderMixin_ItemStackLike { - - default InventoryTransactionResult.Builder reject(ItemStack... itemStacks) { - return ((InventoryTransactionResult.Builder) this).reject(itemStacks); - } - - default InventoryTransactionResult.Builder.PollBuilder poll(ItemStackSnapshot itemStack) { - return ((InventoryTransactionResult.Builder) this).poll(itemStack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/SlotTransactionMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/SlotTransactionMixin_ItemStackLike.java deleted file mode 100644 index 90faa9215ae..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/transaction/SlotTransactionMixin_ItemStackLike.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.transaction; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.transaction.SlotTransaction; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = SlotTransaction.class, remap = false) -public abstract class SlotTransactionMixin_ItemStackLike { - - public void setCustom(ItemStack stack) { - ((SlotTransaction) (Object) this).setCustom(stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/GridInventoryMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/GridInventoryMixin_ItemStackLike.java deleted file mode 100644 index 54ece4cfa91..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/GridInventoryMixin_ItemStackLike.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.type; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.api.item.inventory.type.GridInventory; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = GridInventory.class, remap = false) -public interface GridInventoryMixin_ItemStackLike { - - default InventoryTransactionResult set(int x, int y, ItemStack stack) { - return ((GridInventory) this).set(x, y, stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/Inventory2DMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/Inventory2DMixin_ItemStackLike.java deleted file mode 100644 index 58dbb68f0d2..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/Inventory2DMixin_ItemStackLike.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.type; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; -import org.spongepowered.api.item.inventory.type.Inventory2D; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.math.vector.Vector2i; - -@Mixin(value = Inventory2D.class, remap = false) -public interface Inventory2DMixin_ItemStackLike { - - default InventoryTransactionResult set(Vector2i pos, ItemStack stack) { - return ((Inventory2D) this).set(pos, stack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/ViewableInventory_Builder_DummyStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/ViewableInventory_Builder_DummyStepMixin_ItemStackLike.java deleted file mode 100644 index 7044bb40170..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/inventory/type/ViewableInventory_Builder_DummyStepMixin_ItemStackLike.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.inventory.type; - -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.inventory.type.ViewableInventory; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = ViewableInventory.Builder.DummyStep.class, remap = false) -public interface ViewableInventory_Builder_DummyStepMixin_ItemStackLike { - - default ViewableInventory.Builder.BuildingStep item(ItemStackSnapshot item) { - return ((ViewableInventory.Builder.DummyStep) this).item(item); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/merchant/TradeOffer_BuilderMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/merchant/TradeOffer_BuilderMixin_ItemStackLike.java deleted file mode 100644 index 44317b114a9..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/merchant/TradeOffer_BuilderMixin_ItemStackLike.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.merchant; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.merchant.TradeOffer; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = TradeOffer.Builder.class, remap = false) -public interface TradeOffer_BuilderMixin_ItemStackLike { - - default TradeOffer.Builder firstBuyingItem(ItemStack item) { - return ((TradeOffer.Builder) this).firstBuyingItem(item); - } - - default TradeOffer.Builder secondBuyingItem(ItemStack item) { - return ((TradeOffer.Builder) this).secondBuyingItem(item); - } - - default TradeOffer.Builder sellingItem(ItemStack item) { - return ((TradeOffer.Builder) this).sellingItem(item); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/RecipeManagerMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/RecipeManagerMixin_ItemStackLike.java deleted file mode 100644 index 7fa4d9312c2..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/RecipeManagerMixin_ItemStackLike.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe; - -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.Recipe; -import org.spongepowered.api.item.recipe.RecipeManager; -import org.spongepowered.api.item.recipe.RecipeType; -import org.spongepowered.api.item.recipe.cooking.CookingRecipe; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.Collection; -import java.util.Optional; -import java.util.function.Supplier; - -@Mixin(value = RecipeManager.class, remap = false) -public interface RecipeManagerMixin_ItemStackLike { - - default > Collection findByResult(RecipeType type, ItemStackSnapshot result) { - return ((RecipeManager) this).findByResult(type, result); - } - - default > Collection findByResult(Supplier> supplier, ItemStackSnapshot result) { - return ((RecipeManager) this).findByResult(supplier, result); - } - - default Optional findCookingRecipe(RecipeType type, ItemStackSnapshot ingredient) { - return ((RecipeManager) this).findCookingRecipe(type, ingredient); - } - - default Optional findCookingRecipe(Supplier> supplier, ItemStackSnapshot ingredient) { - return ((RecipeManager) this).findCookingRecipe(supplier, ingredient); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipeMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipeMixin_ItemStackLike.java deleted file mode 100644 index fd50a0ed82d..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipeMixin_ItemStackLike.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.cooking; - -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.cooking.CookingRecipe; -import org.spongepowered.api.item.recipe.cooking.CookingResult; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.Optional; - -@Mixin(value = CookingRecipe.class, remap = false) -public interface CookingRecipeMixin_ItemStackLike { - - default boolean isValid(ItemStackSnapshot ingredient) { - return ((CookingRecipe) this).isValid(ingredient); - } - - default Optional result(ItemStackSnapshot ingredient) { - return ((CookingRecipe) this).result(ingredient); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index 2a214b60a64..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/cooking/CookingRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.cooking; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.cooking.CookingRecipe; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Function; - -@Mixin(value = CookingRecipe.Builder.ResultStep.class, remap = false) -public interface CookingRecipe_Builder_ResultStepMixin_ItemStackLike { - - default CookingRecipe.Builder.EndStep result(ItemStack result) { - return ((CookingRecipe.Builder.ResultStep) this).result(result); - } - - default CookingRecipe.Builder.EndStep result(ItemStackSnapshot result) { - return ((CookingRecipe.Builder.ResultStep) this).result(result); - } - - default CookingRecipe.Builder.EndStep result(Function resultFunction, ItemStack exemplaryResult) { - return ((CookingRecipe.Builder.ResultStep) this).result(resultFunction, exemplaryResult); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/IngredientMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/IngredientMixin_ItemStackLike.java deleted file mode 100644 index 9fa21b80a57..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/IngredientMixin_ItemStackLike.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.recipe.crafting.Ingredient; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = Ingredient.class, remap = false) -public interface IngredientMixin_ItemStackLike { - - default boolean test(ItemStack itemStack) { - return ((Ingredient) this).test(itemStack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/Ingredient_BuilderMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/Ingredient_BuilderMixin_ItemStackLike.java deleted file mode 100644 index 459f8203986..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/Ingredient_BuilderMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.crafting.Ingredient; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Predicate; - -@Mixin(value = Ingredient.Builder.class, remap = false) -public interface Ingredient_BuilderMixin_ItemStackLike { - - default Ingredient.Builder with(ItemStack... types) { - return ((Ingredient.Builder) this).with(types); - } - - default Ingredient.Builder with(ResourceKey resourceKey, Predicate predicate, ItemStack... exemplaryTypes) { - return ((Ingredient.Builder) this).with(resourceKey, itemStack -> predicate.test(itemStack.asMutable()), exemplaryTypes); - } - - default Ingredient.Builder with(ItemStackSnapshot... types) { - return ((Ingredient.Builder) this).with(types); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/RecipeInput_FactoryMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/RecipeInput_FactoryMixin_ItemStackLike.java deleted file mode 100644 index e5bf505f383..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/RecipeInput_FactoryMixin_ItemStackLike.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = RecipeInput.Factory.class, remap = false) -public interface RecipeInput_FactoryMixin_ItemStackLike { - - default RecipeInput.Single single(ItemStack stack) { - return ((RecipeInput.Factory) this).single(stack); - } - - default RecipeInput.Smithing smithing(ItemStack templateStack, ItemStack baseStack, ItemStack additionStack) { - return ((RecipeInput.Factory) this).smithing(templateStack, baseStack, additionStack); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapedCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapedCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index d02c9ae6dd1..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapedCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.api.item.recipe.crafting.ShapedCraftingRecipe; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Function; - -@Mixin(value = ShapedCraftingRecipe.Builder.ResultStep.class, remap = false) -public interface ShapedCraftingRecipe_Builder_ResultStepMixin_ItemStackLike { - - default ShapedCraftingRecipe.Builder.EndStep result(ItemStackSnapshot result) { - return ((ShapedCraftingRecipe.Builder.ResultStep) this).result(result); - } - - default ShapedCraftingRecipe.Builder.EndStep result(ItemStack result) { - return ((ShapedCraftingRecipe.Builder.ResultStep) this).result(result); - } - - default ShapedCraftingRecipe.Builder.EndStep result(Function resultFunction, ItemStack exemplaryResult) { - return ((ShapedCraftingRecipe.Builder.ResultStep) this).result(resultFunction, exemplaryResult); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapelessCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapelessCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index c0cee571a57..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/ShapelessCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.api.item.recipe.crafting.ShapelessCraftingRecipe; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Function; - -@Mixin(value = ShapelessCraftingRecipe.Builder.ResultStep.class, remap = false) -public interface ShapelessCraftingRecipe_Builder_ResultStepMixin_ItemStackLike { - - default ShapelessCraftingRecipe.Builder.EndStep result(ItemStackSnapshot result) { - return ((ShapelessCraftingRecipe.Builder.ResultStep) this).result(result); - } - - default ShapelessCraftingRecipe.Builder.EndStep result(ItemStack result) { - return ((ShapelessCraftingRecipe.Builder.ResultStep) this).result(result); - } - - default ShapelessCraftingRecipe.Builder.EndStep result(Function resultFunction, ItemStack exemplaryResult) { - return ((ShapelessCraftingRecipe.Builder.ResultStep) this).result(resultFunction, exemplaryResult); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/SpecialCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/SpecialCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index 9678264a3c2..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/crafting/SpecialCraftingRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.crafting; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.recipe.crafting.SpecialCraftingRecipe; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(value = SpecialCraftingRecipe.Builder.ResultStep.class, remap = false) -public interface SpecialCraftingRecipe_Builder_ResultStepMixin_ItemStackLike { - - default SpecialCraftingRecipe.Builder.EndStep result(ItemStack result) { - return ((SpecialCraftingRecipe.Builder.ResultStep) this).result(result); - } - - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/single/StoneCutterRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/single/StoneCutterRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index 00ff09262bd..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/single/StoneCutterRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.single; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.api.item.recipe.single.StoneCutterRecipe; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Function; - -@Mixin(value = StoneCutterRecipe.Builder.ResultStep.class, remap = false) -public interface StoneCutterRecipe_Builder_ResultStepMixin_ItemStackLike { - - default StoneCutterRecipe.Builder.EndStep result(ItemStackSnapshot result) { - return ((StoneCutterRecipe.Builder.ResultStep) this).result(result); - } - - default StoneCutterRecipe.Builder.EndStep result(ItemStack result) { - return ((StoneCutterRecipe.Builder.ResultStep) this).result(result); - } - - default StoneCutterRecipe.Builder.EndStep result(Function resultFunction, ItemStack exemplaryResult) { - return ((StoneCutterRecipe.Builder.ResultStep) this).result(resultFunction, exemplaryResult); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/smithing/SmithingRecipe_Builder_ResultStepMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/smithing/SmithingRecipe_Builder_ResultStepMixin_ItemStackLike.java deleted file mode 100644 index 29d7ced7021..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/item/recipe/smithing/SmithingRecipe_Builder_ResultStepMixin_ItemStackLike.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.itemstacklike.item.recipe.smithing; - -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.recipe.crafting.RecipeInput; -import org.spongepowered.api.item.recipe.smithing.SmithingRecipe; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Function; - -@Mixin(value = SmithingRecipe.Builder.ResultStep.class, remap = false) -public interface SmithingRecipe_Builder_ResultStepMixin_ItemStackLike { - - default SmithingRecipe.Builder.EndStep result(ItemStackSnapshot result) { - return ((SmithingRecipe.Builder.ResultStep) this).result(result); - } - - default SmithingRecipe.Builder.EndStep result(ItemStack result) { - return ((SmithingRecipe.Builder.ResultStep) this).result(result); - } - - default SmithingRecipe.Builder.EndStep result(Function resultFunction, ItemStack exemplaryResult) { - return ((SmithingRecipe.Builder.ResultStep) this).result(resultFunction, exemplaryResult); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/AbstractBlockMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockBehaviourMixin_API.java similarity index 94% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/AbstractBlockMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockBehaviourMixin_API.java index 9de7530be58..d1282ec8124 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/AbstractBlockMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockBehaviourMixin_API.java @@ -35,12 +35,14 @@ import org.spongepowered.asm.mixin.Shadow; @Mixin(value = BlockBehaviour.class) -public abstract class AbstractBlockMixin_API implements BlockType { +public abstract class BlockBehaviourMixin_API implements BlockType { // @formatter:off @Shadow @Final @org.spongepowered.asm.mixin.Mutable protected boolean isRandomlyTicking; @Shadow public abstract Item shadow$asItem(); @Shadow @Final protected SoundType soundType; + @Shadow public abstract String shadow$getDescriptionId(); + // @formatter:on @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockMixin_API.java index 3ad68ef92b5..a308240cd85 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockMixin_API.java @@ -51,13 +51,12 @@ import java.util.stream.Collectors; @Mixin(value = Block.class, priority = 999) -public abstract class BlockMixin_API extends AbstractBlockMixin_API implements SpongeImmutableDataHolder { +public abstract class BlockMixin_API extends BlockBehaviourMixin_API implements SpongeImmutableDataHolder { // @formatter:off @Shadow @Final protected StateDefinition stateDefinition; @Shadow @Final private Holder.Reference builtInRegistryHolder; - @Shadow public abstract String shadow$getDescriptionId(); @Shadow public abstract net.minecraft.world.level.block.state.BlockState shadow$defaultBlockState(); // @formatter:on diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockSoundGroupMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockSoundGroupMixin_API.java index 69aa244b41b..8c72f740ca9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockSoundGroupMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/block/BlockSoundGroupMixin_API.java @@ -56,26 +56,26 @@ public double pitch() { @Override public org.spongepowered.api.effect.sound.SoundType breakSound() { - return (org.spongepowered.api.effect.sound.SoundType) this.breakSound; + return (org.spongepowered.api.effect.sound.SoundType) (Object) this.breakSound; } @Override public org.spongepowered.api.effect.sound.SoundType stepSound() { - return (org.spongepowered.api.effect.sound.SoundType) this.stepSound; + return (org.spongepowered.api.effect.sound.SoundType) (Object) this.stepSound; } @Override public org.spongepowered.api.effect.sound.SoundType placeSound() { - return (org.spongepowered.api.effect.sound.SoundType) this.placeSound; + return (org.spongepowered.api.effect.sound.SoundType) (Object) this.placeSound; } @Override public org.spongepowered.api.effect.sound.SoundType hitSound() { - return (org.spongepowered.api.effect.sound.SoundType) this.hitSound; + return (org.spongepowered.api.effect.sound.SoundType) (Object) this.hitSound; } @Override public org.spongepowered.api.effect.sound.SoundType fallSound() { - return (org.spongepowered.api.effect.sound.SoundType) this.fallSound; + return (org.spongepowered.api.effect.sound.SoundType) (Object) this.fallSound; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientLevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientLevelMixin_API.java index 12f66296e46..2750caf8ca2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientLevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientLevelMixin_API.java @@ -70,7 +70,7 @@ public boolean isLoaded() { public ChunkLayout chunkLayout() { if (this.api$chunkLayout == null) { final var height = ((ClientLevel) (Object) this).getHeight(); - final var min = ((ClientLevel) (Object) this).getMinBuildHeight(); + final var min = ((ClientLevel) (Object) this).getMinY(); this.api$chunkLayout = new SpongeChunkLayout(min, height); } return this.api$chunkLayout; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/commands/arguments/selector/EntitySelectorMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/commands/arguments/selector/EntitySelectorMixin_API.java index 245d0d91b4f..c4c927d18ff 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/commands/arguments/selector/EntitySelectorMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/commands/arguments/selector/EntitySelectorMixin_API.java @@ -28,6 +28,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.selector.EntitySelector; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandCause; @@ -63,7 +64,7 @@ public Collection select(@NonNull final ServerLocation location) throws @Override @NonNull public Collection select(@NonNull final Entity entity) throws IllegalStateException { - return this.api$select(((net.minecraft.world.entity.Entity) entity).createCommandSourceStack()); + return this.api$select(((net.minecraft.world.entity.Entity) entity).createCommandSourceStackForNameResolution(((ServerLevel) ((net.minecraft.world.entity.Entity) entity).level()))); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java index b6f870bd4a5..b1ff4f5c63e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java @@ -58,7 +58,7 @@ public abstract class MappedRegistryMixin_API implements Registry { @Shadow public abstract Holder.Reference shadow$register(final net.minecraft.resources.ResourceKey $$0, final T $$1, final RegistrationInfo $$2); @Shadow public abstract net.minecraft.resources.ResourceKey> shadow$key(); - @Shadow @Nullable public abstract T shadow$get(@Nullable ResourceLocation var1); + @Shadow @Nullable public abstract T shadow$getValue(@Nullable ResourceLocation var1); private ResourceLocation impl$getKey(final T value) { return ((net.minecraft.core.Registry) this).getKey(value); @@ -69,11 +69,11 @@ public abstract class MappedRegistryMixin_API implements Registry { } private Optional> impl$getTag(TagKey var1) { - return ((net.minecraft.core.Registry) this).getTag(var1); + return ((net.minecraft.core.Registry) this).get(var1); } private Stream> impl$getTagNames() { - return ((net.minecraft.core.Registry) this).getTagNames(); + return ((net.minecraft.core.Registry) this).getTags().map(HolderSet.Named::key); } @Override @@ -114,7 +114,7 @@ public Optional findValue(final ResourceKey key) { @Override public V value(final ResourceKey key) { - final V value = (V) this.shadow$get((ResourceLocation) (Object) Objects.requireNonNull(key, "key")); + final V value = (V) this.shadow$getValue((ResourceLocation) (Object) Objects.requireNonNull(key, "key")); if (value != null) { return value; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/MinecraftServerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/MinecraftServerMixin_API.java index f6a97235086..513fa1cd3bd 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/MinecraftServerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/MinecraftServerMixin_API.java @@ -118,7 +118,7 @@ public abstract class MinecraftServerMixin_API implements SpongeServer, SpongeRegistryHolder { // @formatter:off - @Shadow @Final public long[] tickTimesNanos; + @Shadow @Final private long[] tickTimesNanos; @Shadow @Final protected WorldData worldData; @Shadow public abstract net.minecraft.world.item.crafting.RecipeManager shadow$getRecipeManager(); @@ -133,7 +133,6 @@ public abstract class MinecraftServerMixin_API implements SpongeServer, SpongeRe @Shadow public abstract boolean shadow$isPvpAllowed(); @Shadow public abstract boolean shadow$isCommandBlockEnabled(); @Shadow public abstract boolean shadow$isSpawningMonsters(); - @Shadow public abstract boolean shadow$isSpawningAnimals(); @Shadow public abstract Commands shadow$getCommands(); @Shadow public abstract PackRepository shadow$getPackRepository(); @Shadow public abstract net.minecraft.server.packs.resources.ResourceManager shadow$getResourceManager(); @@ -270,7 +269,7 @@ public boolean isMonsterSpawnsEnabled() { @Override public boolean isAnimalSpawnsEnabled() { - return this.shadow$isSpawningAnimals(); + return true; } /** @@ -286,7 +285,7 @@ public WorldGenerationConfig worldGenerationConfig() { final WorldData overworldData = this.shadow$getWorldData(); final WorldGenSettings settings = new WorldGenSettings(overworldData.worldGenOptions(), - new WorldDimensions(this.registryAccess().registryOrThrow(Registries.LEVEL_STEM))); + new WorldDimensions(this.registryAccess().lookupOrThrow(Registries.LEVEL_STEM))); return (WorldGenerationConfig) (Object) settings; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java index 03c3ef4ca14..b84aa8eede6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java @@ -331,7 +331,7 @@ public void setWeather(final WeatherType type, final Ticks ticks) { public ChunkLayout chunkLayout() { if (this.api$chunkLayout == null) { final var height = ((ServerLevel) (Object) this).getHeight(); - final var min = ((ServerLevel) (Object) this).getMinBuildHeight(); + final var min = ((ServerLevel) (Object) this).getMinY(); this.api$chunkLayout = new SpongeChunkLayout(min, height); } return this.api$chunkLayout; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/sounds/MusicMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/sounds/MusicMixin_API.java index 102078cbe50..55c04b7c5d3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/sounds/MusicMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/sounds/MusicMixin_API.java @@ -45,7 +45,7 @@ public abstract class MusicMixin_API implements SoundConfig.BackgroundMusic { @Override public SoundType sound() { - return (SoundType) this.event.value(); + return (SoundType) (Object) this.event.value(); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/state/PropertyMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/state/PropertyMixin_API.java index 49224e9717c..b9c2e3f1044 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/state/PropertyMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/state/PropertyMixin_API.java @@ -30,6 +30,7 @@ import org.spongepowered.asm.mixin.Shadow; import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.function.Predicate; @@ -44,7 +45,7 @@ public abstract class PropertyMixin_API> implements Stat // @formatter:off @Shadow public abstract Class shadow$getValueClass(); - @Shadow public abstract Collection shadow$getPossibleValues(); + @Shadow public abstract List shadow$getPossibleValues(); @Shadow public abstract String shadow$getName(); // @formatter:on diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/EntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/EntityMixin_API.java index d662b1576c2..cfe05e7ba24 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/EntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/EntityMixin_API.java @@ -35,7 +35,9 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.RelativeMovement; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.Relative; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import org.checkerframework.checker.nullness.qual.Nullable; @@ -81,6 +83,7 @@ public abstract class EntityMixin_API implements org.spongepowered.api.entity.Entity { // @formatter:off + @Shadow private Vec3 position; @Shadow private float yRot; @Shadow private float xRot; @Shadow @Final protected net.minecraft.util.RandomSource random; @@ -95,7 +98,7 @@ public abstract class EntityMixin_API implements org.spongepowered.api.entity.En @Shadow @Nullable public abstract MinecraftServer shadow$getServer(); @Shadow public abstract boolean shadow$isRemoved(); @Shadow public abstract UUID shadow$getUUID(); - @Shadow public abstract boolean shadow$hurt(DamageSource source, float amount); + @Shadow public abstract boolean shadow$hurtOrSimulate(DamageSource source, float amount); @Shadow protected abstract void shadow$setRot(float yaw, float pitch); @Shadow public abstract net.minecraft.world.phys.AABB shadow$getBoundingBox(); @Shadow public abstract void shadow$setRemoved(Entity.RemovalReason var1); @@ -103,6 +106,7 @@ public abstract class EntityMixin_API implements org.spongepowered.api.entity.En @Shadow public abstract void shadow$lookAt(EntityAnchorArgument.Anchor param0, Vec3 param1); @Shadow public abstract CompoundTag shadow$saveWithoutId(CompoundTag $$0); @Shadow public abstract Level shadow$level(); + @Shadow public abstract Vec3 shadow$position(); // @formatter:on @Override @@ -196,8 +200,7 @@ public void setRotation(final Vector3d rotation) { } if (((Entity) (Object) this) instanceof ServerPlayer && ((ServerPlayer) (Object) this).connection != null) { // Force an update, this also set the rotation in this entity - ((ServerPlayer) (Object) this).connection.teleport(this.position().x(), this.position().y(), - this.position().z(), (float) rotation.y(), (float) rotation.x(), EnumSet.noneOf(RelativeMovement.class)); + ((ServerPlayer) (Object) this).connection.teleport(new PositionMoveRotation(this.position, Vec3.ZERO, (float) rotation.y(), (float) rotation.x()), EnumSet.noneOf(Relative.class)); } else { // Let the entity tracker do its job, this just updates the variables this.shadow$setRot((float) rotation.y(), (float) rotation.x()); @@ -234,6 +237,8 @@ public boolean isLoaded() { this.shadow$setRemoved(Entity.RemovalReason.DISCARDED); } + + @Override public boolean damage(final double damage, final org.spongepowered.api.event.cause.entity.damage.source.DamageSource damageSource) { if (!(damageSource instanceof DamageSource)) { @@ -241,7 +246,7 @@ public boolean damage(final double damage, final org.spongepowered.api.event.cau return false; } // Causes at this point should already be pushed from plugins before this point with the cause system. - return this.shadow$hurt((DamageSource) damageSource, (float) damage); + return this.shadow$hurtOrSimulate((DamageSource) damageSource, (float) damage); } @Override @@ -300,10 +305,11 @@ public org.spongepowered.api.entity.Entity copy() { final CompoundTag compound = new CompoundTag(); compound.putString("id", entityTypeRegistry.getKey((net.minecraft.world.entity.EntityType) this.type()).toString()); this.shadow$saveWithoutId(compound); - final Entity entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(compound, this.shadow$getCommandSenderWorld(), (createdEntity) -> { - createdEntity.setUUID(UUID.randomUUID()); - return createdEntity; - }); + final Entity entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(compound, this.shadow$getCommandSenderWorld(), EntitySpawnReason.COMMAND, + (createdEntity) -> { + createdEntity.setUUID(UUID.randomUUID()); + return createdEntity; + }); return (org.spongepowered.api.entity.Entity) entity; } catch (final Exception e) { throw new IllegalArgumentException("Could not copy the entity:", e); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/AvoidEntityGoalMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/AvoidEntityGoalMixin_API.java index 6b54348d93e..48acc27bbe2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/AvoidEntityGoalMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/AvoidEntityGoalMixin_API.java @@ -24,24 +24,24 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.ai.goal; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import org.spongepowered.api.entity.ai.goal.builtin.creature.AvoidLivingGoal; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.PathfinderAgent; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.accessor.world.entity.ai.targeting.TargetingConditionsAccessor; -import java.util.function.Predicate; +import java.util.function.BiPredicate; @SuppressWarnings({"unchecked"}) @Mixin(net.minecraft.world.entity.ai.goal.AvoidEntityGoal.class) public abstract class AvoidEntityGoalMixin_API extends GoalMixin_API implements AvoidLivingGoal { - private static final Predicate ALWAYS_TRUE = e -> true; + private static final BiPredicate ALWAYS_TRUE = (e, l) -> true; // @formatter:off @Shadow @Final @Mutable private double walkSpeedModifier; @@ -51,14 +51,14 @@ public abstract class AvoidEntityGoalMixin_API extends GoalMixin_API targetSelector() { - final Predicate predicate = ((TargetingConditionsAccessor) this.avoidEntityTargeting).accessor$selector(); - return (Predicate) (Object) (predicate == null ? AvoidEntityGoalMixin_API.ALWAYS_TRUE : predicate); + public BiPredicate targetSelector() { + final TargetingConditions.Selector predicate = ((TargetingConditionsAccessor) this.avoidEntityTargeting).accessor$selector(); + return (BiPredicate) (Object) (predicate == null ? AvoidEntityGoalMixin_API.ALWAYS_TRUE : predicate); } @Override - public AvoidLivingGoal setTargetSelector(Predicate predicate) { - this.avoidEntityTargeting.selector((Predicate) (Object) predicate); + public AvoidLivingGoal setTargetSelector(BiPredicate predicate) { + this.avoidEntityTargeting.selector((TargetingConditions.Selector) predicate); return this; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/target/NearestAttackableTargetGoalMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/target/NearestAttackableTargetGoalMixin_API.java index ed9aa85e4b6..00f45740062 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/target/NearestAttackableTargetGoalMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/goal/target/NearestAttackableTargetGoalMixin_API.java @@ -74,13 +74,13 @@ public FindNearestAttackableTargetGoal setChance(int chance) { @Override public FindNearestAttackableTargetGoal filter(Predicate predicate) { - this.targetConditions.selector(((Predicate) (Object) predicate)); + this.targetConditions.selector((e, l) -> predicate.test((Living) l)); return this; } @Override public Predicate filter() { - final Predicate predicate = ((TargetingConditionsAccessor) this.targetConditions).accessor$selector(); + final TargetingConditions.Selector predicate = ((TargetingConditionsAccessor) this.targetConditions).accessor$selector(); return (Predicate) (Object) (predicate == null ? NearestAttackableTargetGoalMixin_API.ALWAYS_TRUE : predicate); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/AgeableWaterCreatureMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/AgeableWaterCreatureMixin_API.java new file mode 100644 index 00000000000..cb0730af804 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/AgeableWaterCreatureMixin_API.java @@ -0,0 +1,36 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.world.entity.animal; + +import net.minecraft.world.entity.animal.AgeableWaterCreature; +import org.spongepowered.api.entity.Ageable; +import org.spongepowered.api.entity.living.aquatic.Aquatic; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.common.mixin.api.minecraft.world.entity.MobMixin_API; + +@Mixin(AgeableWaterCreature.class) +public abstract class AgeableWaterCreatureMixin_API extends MobMixin_API implements Aquatic, Ageable { + +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/DolphinMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/DolphinMixin_API.java index fb794fbe8c7..2cd310baace 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/DolphinMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/DolphinMixin_API.java @@ -32,7 +32,7 @@ import java.util.Set; @Mixin(net.minecraft.world.entity.animal.Dolphin.class) -public abstract class DolphinMixin_API extends WaterAnimalMixin_API implements Dolphin { +public abstract class DolphinMixin_API extends AgeableWaterCreatureMixin_API implements Dolphin { @Override protected Set> api$getVanillaValues() { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_TypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_VariantMixin_API.java similarity index 94% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_TypeMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_VariantMixin_API.java index 3e25a5d44d2..b7af53b114c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_TypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/Fox_VariantMixin_API.java @@ -28,6 +28,6 @@ import org.spongepowered.api.data.type.FoxType; import org.spongepowered.asm.mixin.Mixin; -@Mixin(Fox.Type.class) -public abstract class Fox_TypeMixin_API implements FoxType { +@Mixin(Fox.Variant.class) +public abstract class Fox_VariantMixin_API implements FoxType { } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/MushroomCow_MushroomTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/MushroomCow_MushroomTypeMixin_API.java index 87d51f488d7..d9c14c85fb8 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/MushroomCow_MushroomTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/MushroomCow_MushroomTypeMixin_API.java @@ -28,6 +28,6 @@ import org.spongepowered.api.data.type.MooshroomType; import org.spongepowered.asm.mixin.Mixin; -@Mixin(MushroomCow.MushroomType.class) +@Mixin(MushroomCow.Variant.class) public abstract class MushroomCow_MushroomTypeMixin_API implements MooshroomType { } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/SquidMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/SquidMixin_API.java index 09582809680..91950d3f8bd 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/SquidMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/animal/SquidMixin_API.java @@ -28,6 +28,6 @@ import org.spongepowered.asm.mixin.Mixin; @Mixin(net.minecraft.world.entity.animal.Squid.class) -public abstract class SquidMixin_API extends WaterAnimalMixin_API implements Squid { +public abstract class SquidMixin_API extends AgeableWaterCreatureMixin_API implements Squid { } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/boss/enderdragon/EndCrystalMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/boss/enderdragon/EndCrystalMixin_API.java index 7f4490eef6a..0d9c4860db7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/boss/enderdragon/EndCrystalMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/boss/enderdragon/EndCrystalMixin_API.java @@ -39,8 +39,7 @@ public abstract class EndCrystalMixin_API extends EntityMixin_API implements End @Override public void detonate() { this.shadow$discard(); - ((EndCrystalBridge) this).bridge$throwExplosionEventAndExplode(this.shadow$getCommandSenderWorld(), null, this.shadow$getX(), - this.shadow$getY(), this.shadow$getZ(), true, null); + ((EndCrystalBridge) this).bridge$wrappedExplode(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ(), null, null); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/FireworkRocketEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/FireworkRocketEntityMixin_API.java index 304d79b2767..316e2ef64f9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/FireworkRocketEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/FireworkRocketEntityMixin_API.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.projectile; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.projectile.FireworkRocketEntity; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.value.Value; @@ -37,12 +38,14 @@ public abstract class FireworkRocketEntityMixin_API extends ProjectileMixin_API implements FireworkRocket { // @formatter:off - @Shadow protected abstract void shadow$explode(); + @Shadow protected abstract void shadow$explode(ServerLevel level); // @formatter:on @Override public void detonate() { - this.shadow$explode(); + if (this.shadow$level() instanceof ServerLevel sl) { + this.shadow$explode(sl); + } } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/LargeFireballMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/LargeFireballMixin_API.java index 1956c863015..9fdae239297 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/LargeFireballMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/LargeFireballMixin_API.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.projectile; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.projectile.LargeFireball; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; @@ -39,14 +40,13 @@ @Mixin(LargeFireball.class) public abstract class LargeFireballMixin_API extends FireballMixin_API implements ExplosiveFireball { - @Shadow public int explosionPower; + @Shadow private int explosionPower; @Override public void detonate() { - final boolean flag = this.shadow$getCommandSenderWorld().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); - final Level.ExplosionInteraction mode = flag ? Level.ExplosionInteraction.MOB : Level.ExplosionInteraction.NONE; - ((LargeFireballBridge) this).bridge$throwExplosionEventAndExplode(this.shadow$getCommandSenderWorld(), null, this.shadow$getX(), - this.shadow$getY(), this.shadow$getZ(), this.explosionPower, flag, mode); + if (this.shadow$level() instanceof ServerLevel sl && sl.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { + ((LargeFireballBridge) this).bridge$wrappedExplode(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ(), this.explosionPower, true, Level.ExplosionInteraction.MOB); + } this.shadow$discard(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WitherSkullMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WitherSkullMixin_API.java index 387579d5e62..72742b09d19 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WitherSkullMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WitherSkullMixin_API.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.projectile; -import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.value.Value; @@ -39,9 +38,7 @@ public abstract class WitherSkullMixin_API extends AbstractHurtingProjectileMixi @Override public void detonate() { - final Level.ExplosionInteraction mode = this.shadow$getCommandSenderWorld().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) ? Level.ExplosionInteraction.MOB : Level.ExplosionInteraction.NONE; - ((WitherSkullBridge) this).bridge$throwExplosionEventAndExplosde(this.shadow$getCommandSenderWorld(), (net.minecraft.world.entity.projectile.WitherSkull) (Object) this, - this.shadow$getX(), this.shadow$getY(), this.shadow$getZ(), 1.0F, false, mode); + ((WitherSkullBridge) this).bridge$wrappedExplode(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ(), 1.0F, false, Level.ExplosionInteraction.MOB); this.shadow$discard(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/windcharge/AbstractWindChargeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/windcharge/AbstractWindChargeMixin_API.java index 360b9e610a0..863d312b601 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/windcharge/AbstractWindChargeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/windcharge/AbstractWindChargeMixin_API.java @@ -25,9 +25,20 @@ package org.spongepowered.common.mixin.api.minecraft.world.entity.projectile.windcharge; import net.minecraft.world.entity.projectile.windcharge.AbstractWindCharge; +import net.minecraft.world.phys.Vec3; +import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.entity.projectile.windcharge.WindChargeLike; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.mixin.api.minecraft.world.entity.EntityMixin_API; @Mixin(AbstractWindCharge.class) -public abstract class AbstractWindChargeMixin_API implements WindChargeLike { +public abstract class AbstractWindChargeMixin_API extends EntityMixin_API implements WindChargeLike, Explosive { + + @Shadow protected abstract void shadow$explode(Vec3 var1); + + @Override + public void detonate() { + this.shadow$explode(this.shadow$position()); + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/BoatMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractBoatMixin_API.java similarity index 92% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/BoatMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractBoatMixin_API.java index 2b7e87f7f52..a3c3c926942 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/BoatMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractBoatMixin_API.java @@ -34,15 +34,14 @@ import java.util.Set; -@Mixin(net.minecraft.world.entity.vehicle.Boat.class) +@Mixin(net.minecraft.world.entity.vehicle.AbstractBoat.class) @Implements(@Interface(iface = Boat.class, prefix = "apiBoat$")) -public abstract class BoatMixin_API extends EntityMixin_API implements Boat { +public abstract class AbstractBoatMixin_API extends EntityMixin_API implements Boat { @Override protected Set> api$getVanillaValues() { final Set> values = super.api$getVanillaValues(); - values.add(this.requireValue(Keys.BOAT_TYPE).asImmutable()); values.add(this.requireValue(Keys.CAN_MOVE_ON_LAND).asImmutable()); values.add(this.requireValue(Keys.IS_IN_WATER).asImmutable()); values.add(this.requireValue(Keys.MAX_SPEED).asImmutable()); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/ChestBoatMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractChestBoatMixin_API.java similarity index 90% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/ChestBoatMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractChestBoatMixin_API.java index 1f1abb933dd..ee842169990 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/ChestBoatMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/AbstractChestBoatMixin_API.java @@ -30,8 +30,8 @@ import java.util.Set; -@Mixin(net.minecraft.world.entity.vehicle.ChestBoat.class) -public abstract class ChestBoatMixin_API extends BoatMixin_API implements ChestBoat { +@Mixin(net.minecraft.world.entity.vehicle.AbstractChestBoat.class) +public abstract class AbstractChestBoatMixin_API extends AbstractBoatMixin_API implements ChestBoat { @Override protected Set> api$getVanillaValues() { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java index 4a003b8b2b3..144190b7a3b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java @@ -24,30 +24,30 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; import org.spongepowered.api.data.type.ArmorMaterial; -import org.spongepowered.api.item.recipe.crafting.Ingredient; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.common.item.util.ItemStackUtil; -import java.util.Optional; -import java.util.function.Supplier; +import java.util.function.Predicate; -@Mixin(net.minecraft.world.item.ArmorMaterial.class) +@Mixin(net.minecraft.world.item.equipment.ArmorMaterial.class) @Implements(@Interface(iface = ArmorMaterial.class, prefix = "armorMaterial$")) public abstract class ArmorMaterialMixin_API implements ArmorMaterial { // @formatter:off - @Shadow @Final private Supplier repairIngredient; - + @Shadow @Final private TagKey repairIngredient; // @formatter:on - @Override - public Optional repairIngredient() { - final net.minecraft.world.item.crafting.Ingredient repairMaterial = this.repairIngredient.get(); - return Optional.ofNullable(((Ingredient) (Object) repairMaterial)); + @Unique + public Predicate armorMaterial$repairIngredient() { + return (spongeStack) -> ItemStackUtil.toNative(spongeStack).is(this.repairIngredient); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemCooldownsMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemCooldownsMixin_API.java index 023fb869015..6296ba85737 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemCooldownsMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemCooldownsMixin_API.java @@ -25,15 +25,18 @@ package org.spongepowered.common.mixin.api.minecraft.world.item; -import net.minecraft.world.item.Item; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.Mth; import net.minecraft.world.item.ItemCooldowns; -import org.spongepowered.api.item.ItemType; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.api.ResourceKey; import org.spongepowered.api.util.Ticks; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.accessor.world.item.ItemCooldowns_CooldownInstanceAccessor; import org.spongepowered.common.bridge.world.item.ItemCooldownsBridge; +import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.util.SpongeTicks; import java.util.Map; @@ -45,25 +48,55 @@ public abstract class ItemCooldownsMixin_API implements org.spongepowered.api.entity.living.player.CooldownTracker { // @formatter:off - @Shadow @Final private Map cooldowns; @Shadow private int tickCount; - @Shadow public abstract boolean shadow$isOnCooldown(Item itemIn); - @Shadow public abstract float shadow$getCooldownPercent(Item itemIn, float partialTicks); - @Shadow public abstract void shadow$addCooldown(final Item item, final int ticks); + @Shadow public abstract boolean shadow$isOnCooldown(ItemStack stack); + @Shadow public abstract float shadow$getCooldownPercent(ItemStack stack, float partialTicks); + @Shadow public abstract void shadow$addCooldown(final ItemStack stack, final int ticks); + @Shadow public abstract void shadow$addCooldown(final ResourceLocation group, final int ticks); + @Shadow @Final private Map cooldowns; + // @formatter:on + + @Shadow public abstract ResourceLocation getCooldownGroup(final ItemStack $$0); + + @Override + public boolean hasCooldown(final org.spongepowered.api.item.inventory.ItemStack stack) { + Objects.requireNonNull(stack, "ItemStack cannot be null!"); + return this.shadow$isOnCooldown(ItemStackUtil.toNative(stack)); + } + + /** + * see {@link ItemCooldowns#getCooldownPercent(ItemStack, float)} + */ @Override - public boolean hasCooldown(final ItemType type) { - Objects.requireNonNull(type, "Item type cannot be null!"); - return this.shadow$isOnCooldown((Item) type); + public boolean hasCooldown(final ResourceKey group) { + Objects.requireNonNull(group, "group cannot be null!"); + return impl$getCooldownPercent((Object) group) > 0; + } + + private float impl$getCooldownPercent(final Object group) { + final var cooldown = this.cooldowns.get((ResourceLocation) group); + if (cooldown != null) { + float $$4 = (float)(cooldown.accessor$endTime() - cooldown.accessor$startTime()); + float $$5 = (float)cooldown.accessor$endTime() - ((float)this.tickCount); + return Mth.clamp($$5 / $$4, 0.0F, 1.0F); + } + return 0; } @Override - public Optional cooldown(final ItemType type) { - Objects.requireNonNull(type, "Item type cannot be null!"); + public Optional cooldown(final org.spongepowered.api.item.inventory.ItemStack stack) { + Objects.requireNonNull(stack, "ItemStack cannot be null!"); + final var group = this.getCooldownGroup(ItemStackUtil.toNative(stack)); + return this.cooldown((ResourceKey) (Object) group); + } - final ItemCooldowns_CooldownInstanceAccessor cooldown = (ItemCooldowns_CooldownInstanceAccessor) this.cooldowns.get((Item) type); + @Override + public Optional cooldown(final ResourceKey group) { + Objects.requireNonNull(group, "group cannot be null!"); + final var cooldown = this.cooldowns.get(group); if (cooldown != null) { final int remainingCooldown = cooldown.accessor$endTime() - this.tickCount; @@ -75,22 +108,32 @@ public Optional cooldown(final ItemType type) { } @Override - public boolean setCooldown(final ItemType type, final Ticks ticks) { - Objects.requireNonNull(type, "Item type cannot be null!"); - this.shadow$addCooldown((Item) type, SpongeTicks.toSaturatedIntOrInfinite(ticks)); + public boolean setCooldown(final org.spongepowered.api.item.inventory.ItemStack stack, final Ticks ticks) { + Objects.requireNonNull(stack, "ItemStack cannot be null!"); + this.shadow$addCooldown(ItemStackUtil.toNative(stack), SpongeTicks.toSaturatedIntOrInfinite(ticks)); return ((ItemCooldownsBridge) this).bridge$getSetCooldownResult(); } + @Override + public boolean setCooldown(final ResourceKey group, final Ticks ticks) { + Objects.requireNonNull(group, "group cannot be null!"); + this.shadow$addCooldown((ResourceLocation) (Object) group, SpongeTicks.toSaturatedIntOrInfinite(ticks)); + return ((ItemCooldownsBridge) this).bridge$getSetCooldownResult(); + } + @Override + public boolean resetCooldown(final org.spongepowered.api.item.inventory.ItemStack stack) { + return this.setCooldown(stack, Ticks.zero()); + } @Override - public boolean resetCooldown(final ItemType type) { - return this.setCooldown(type, Ticks.zero()); + public boolean resetCooldown(final ResourceKey group) { + return this.setCooldown(group, Ticks.zero()); } @Override - public OptionalDouble fractionRemaining(final ItemType type) { - Objects.requireNonNull(type, "Item type cannot be null!"); - final float cooldown = this.shadow$getCooldownPercent((Item) type, 0); + public OptionalDouble fractionRemaining(final org.spongepowered.api.item.inventory.ItemStack stack) { + Objects.requireNonNull(stack, "ItemStack cannot be null!"); + final float cooldown = this.shadow$getCooldownPercent(ItemStackUtil.toNative(stack), 0); if (cooldown > 0.0F) { return OptionalDouble.of(cooldown); @@ -98,5 +141,13 @@ public OptionalDouble fractionRemaining(final ItemType type) { return OptionalDouble.empty(); } - + @Override + public OptionalDouble fractionRemaining(final ResourceKey group) { + Objects.requireNonNull(group, "group cannot be null!"); + final float cooldown = this.impl$getCooldownPercent(group); + if (cooldown > 0.0F) { + return OptionalDouble.of(cooldown); + } + return OptionalDouble.empty(); + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java index 557d19c5177..e0e6f7f20c3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java @@ -56,7 +56,7 @@ public abstract class ItemMixin_API implements ItemType, SpongeImmutableDataHold @Shadow @Final private DataComponentMap components; @Shadow public abstract String shadow$getDescriptionId(); - @Shadow @Nullable public abstract Item shadow$getCraftingRemainingItem(); + @Shadow @Final @Nullable private Item craftingRemainingItem; @Shadow public abstract int shadow$getDefaultMaxStackSize(); // @formatter:on @@ -111,7 +111,7 @@ public boolean is(Tag tag) { @Override public Optional container() { - final Item craftingRemainingItem = this.shadow$getCraftingRemainingItem(); + final @Nullable Item craftingRemainingItem = this.craftingRemainingItem; return Optional.ofNullable((ItemType) craftingRemainingItem); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/JukeboxSongMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/JukeboxSongMixin_API.java index 7b7fa4a636a..1ac5dd00437 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/JukeboxSongMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/JukeboxSongMixin_API.java @@ -40,6 +40,6 @@ public abstract class JukeboxSongMixin_API implements MusicDisc { @Override public SoundType sound() { - return (SoundType) this.soundEvent.value(); + return (SoundType) (Object) this.soundEvent.value(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/TiersMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ToolMaterialMixin_API.java similarity index 65% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/TiersMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ToolMaterialMixin_API.java index f737fd964b3..b0394d9d962 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/TiersMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ToolMaterialMixin_API.java @@ -24,20 +24,28 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item; -import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; import org.spongepowered.api.data.type.ItemTier; +import org.spongepowered.api.item.recipe.crafting.Ingredient; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.item.recipe.ingredient.SpongeIngredient; -@Mixin(net.minecraft.world.item.Tiers.class) -public abstract class TiersMixin_API implements ItemTier { +@Mixin(net.minecraft.world.item.ToolMaterial.class) +public abstract class ToolMaterialMixin_API implements ItemTier { // @formatter:off - @Shadow public abstract Ingredient shadow$getRepairIngredient(); + @Shadow @Final private TagKey repairItems; // @formatter:on @Override - public org.spongepowered.api.item.recipe.crafting.Ingredient repairIngredient() { - return (org.spongepowered.api.item.recipe.crafting.Ingredient) (Object) this.shadow$getRepairIngredient(); + public Ingredient repairIngredient() { + HolderGetter holder = BuiltInRegistries.acquireBootstrapRegistrationLookup(BuiltInRegistries.ITEM); + final var items = holder.getOrThrow(this.repairItems); + return (Ingredient) (Object) SpongeIngredient.of(items); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/AbstractCookingRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/AbstractCookingRecipeMixin_API.java index 9075a7f4354..98c6879dd5c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/AbstractCookingRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/AbstractCookingRecipeMixin_API.java @@ -25,12 +25,10 @@ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; import net.minecraft.world.item.crafting.AbstractCookingRecipe; -import net.minecraft.world.item.crafting.Ingredient; import org.spongepowered.api.item.inventory.ItemStackLike; import org.spongepowered.api.item.recipe.cooking.CookingRecipe; import org.spongepowered.api.item.recipe.cooking.CookingResult; import org.spongepowered.api.util.Ticks; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; @@ -40,39 +38,38 @@ import java.util.Optional; @Mixin(AbstractCookingRecipe.class) -public abstract class AbstractCookingRecipeMixin_API implements CookingRecipe { +public abstract class AbstractCookingRecipeMixin_API extends SingleItemRecipeMixin_API implements CookingRecipe { // @formatter:off - @Shadow @Final protected Ingredient ingredient; - @Shadow public abstract float shadow$getExperience(); - @Shadow public abstract int shadow$getCookingTime(); + @Shadow public abstract float shadow$experience(); + @Shadow public abstract int shadow$cookingTime(); // @formatter:on @Override public org.spongepowered.api.item.recipe.crafting.Ingredient ingredient() { - return IngredientUtil.fromNative(this.ingredient); + return IngredientUtil.fromNative(this.shadow$input()); } @Override public boolean isValid(final ItemStackLike ingredient) { - return this.ingredient.test(ItemStackUtil.fromLikeToNative(ingredient)); + return this.shadow$input().test(ItemStackUtil.fromLikeToNative(ingredient)); } @Override public Optional result(final ItemStackLike ingredient) { if (this.isValid(ingredient)) { - return Optional.of(new CookingResult(this.exemplaryResult(), this.shadow$getExperience())); + return Optional.of(new CookingResult((ItemStackLike) this.exemplaryResult(), this.shadow$experience())); } return Optional.empty(); } @Override public Ticks cookingTime() { - return SpongeTicks.ticksOrInfinite(this.shadow$getCookingTime()); + return SpongeTicks.ticksOrInfinite(this.shadow$cookingTime()); } @Override public float experience() { - return this.shadow$getExperience(); + return this.shadow$experience(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/CraftingRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/CraftingRecipeMixin_API.java index c5c25ee36c3..c11308717b6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/CraftingRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/CraftingRecipeMixin_API.java @@ -24,13 +24,20 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; +import net.minecraft.core.NonNullList; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapelessRecipe; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.recipe.RecipeType; import org.spongepowered.api.item.recipe.crafting.CraftingRecipe; +import org.spongepowered.api.item.recipe.crafting.RecipeInput; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.item.util.ItemStackUtil; +import java.util.List; import java.util.Optional; @Mixin(net.minecraft.world.item.crafting.CraftingRecipe.class) @@ -38,8 +45,16 @@ public interface CraftingRecipeMixin_API extends CraftingRecipe { // @formatter:off @Shadow net.minecraft.world.item.crafting.RecipeType shadow$getType(); + @Shadow NonNullList shadow$getRemainingItems(CraftingInput $$0); // @formatter:on + @Override + default List remainingItems(RecipeInput.Crafting inventory) { + return this.shadow$getRemainingItems((CraftingInput) inventory).stream() + .map(ItemStackUtil::snapshotOf) + .toList(); + } + default RecipeType type() { return (RecipeType) this.shadow$getType(); } @@ -47,10 +62,10 @@ default RecipeType type() { default Optional group() { String group = ""; if (this instanceof ShapedRecipe sr) { - group = sr.getGroup(); + group = sr.group(); } if (this instanceof ShapelessRecipe sr) { - group = sr.getGroup(); + group = sr.group(); } if (group.isEmpty()) { return Optional.empty(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/IngredientMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/IngredientMixin_API.java index 34d48fb56a0..9e1b16db4be 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/IngredientMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/IngredientMixin_API.java @@ -24,9 +24,12 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; +import net.minecraft.core.Holder; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.ItemStackLike; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @@ -35,22 +38,19 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.item.util.ItemStackUtil; -import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; @Mixin(Ingredient.class) @Implements(@Interface(iface = org.spongepowered.api.item.recipe.crafting.Ingredient.class, prefix = "ingredient$", remap = Remap.NONE)) public abstract class IngredientMixin_API { // @formatter:off - @Shadow public abstract ItemStack[] shadow$getItems(); @Shadow public abstract boolean shadow$test(@Nullable ItemStack p_test_1_); + @Shadow public abstract List> shadow$items(); // @formatter:on - - public List ingredient$displayedItems() { - return Arrays.stream(this.shadow$getItems()).map(ItemStackUtil::snapshotOf).collect(Collectors.toList()); + public List ingredient$displayedItems() { + return this.shadow$items().stream().map((holder) -> (ItemType) holder.value()).toList(); } public boolean ingredient$test(final ItemStackLike itemStack) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java index 302ab6b23e0..26eb793a627 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java @@ -24,11 +24,12 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Container; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.item.crafting.RecipeManager.CachedCheck; +import net.minecraft.world.item.crafting.RecipeMap; import net.minecraft.world.item.crafting.SingleRecipeInput; import net.minecraft.world.level.Level; import org.spongepowered.api.ResourceKey; @@ -40,6 +41,7 @@ import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.accessor.world.item.crafting.RecipeMapAccessor; import org.spongepowered.common.inventory.util.InventoryUtil; import org.spongepowered.common.item.util.ItemStackUtil; @@ -52,17 +54,24 @@ public abstract class RecipeManagerMixin_API implements RecipeManager { // @formatter:off - @Shadow public abstract Optional> shadow$byKey(ResourceLocation recipeId); - @Shadow protected abstract > Collection> shadow$byType(net.minecraft.world.item.crafting.RecipeType recipeTypeIn); @Shadow public abstract Collection> shadow$getRecipes(); - @Shadow public abstract > Optional shadow$getRecipeFor(net.minecraft.world.item.crafting.RecipeType recipeTypeIn, I inventoryIn, net.minecraft.world.level.Level worldIn); + @Shadow public abstract > Optional shadow$getRecipeFor(net.minecraft.world.item.crafting.RecipeType recipeTypeIn, I inventoryIn, Level worldIn); // @formatter:on + @Shadow + private RecipeMap recipes; + @Override public Optional> byKey(final ResourceKey key) { Objects.requireNonNull(key); - return this.shadow$byKey((ResourceLocation) (Object) key).map(Recipe.class::cast); + // TODO - figure out how to do this better + for (var entry : ((RecipeMapAccessor) this.recipes).accessor$byKey().entrySet()) { + if (entry.getKey().location().equals(key)) { + return Optional.of(entry.getValue()).map(Recipe.class::cast); + } + } + return Optional.empty(); } @Override @@ -75,7 +84,7 @@ public Collection> all() { @SuppressWarnings(value = {"unchecked", "rawtypes"}) public > Collection allOfType(final RecipeType type) { Objects.requireNonNull(type); - return this.shadow$byType((net.minecraft.world.item.crafting.RecipeType)type); + return this.recipes.byType((net.minecraft.world.item.crafting.RecipeType)type); } @Override @@ -99,12 +108,12 @@ public RecipeManagerMixin_API.impl$getRecipe(level, checker, in)); } - private static > Optional> impl$getRecipe(final Level level, final CachedCheck checker, final I input) { + private static > Optional> impl$getRecipe(final ServerLevel level, final CachedCheck checker, final I input) { return checker.getRecipeFor(input, level).map(RecipeHolder::value).map(Recipe.class::cast); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java index af01bd79ede..8b19f11b424 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java @@ -24,69 +24,72 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; -import static org.spongepowered.common.inventory.util.InventoryUtil.toCraftingInputOrThrow; - import net.minecraft.core.HolderLookup; -import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeInput; +import net.minecraft.world.item.crafting.display.RecipeDisplay; +import net.minecraft.world.item.crafting.display.SlotDisplay; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.recipe.Recipe; import org.spongepowered.api.item.recipe.RecipeType; -import org.spongepowered.api.item.recipe.crafting.Ingredient; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; +import org.spongepowered.common.inventory.util.InventoryUtil; +import org.spongepowered.common.item.recipe.crafting.RecipeUtil; import org.spongepowered.common.item.util.ItemStackUtil; import java.util.List; -import java.util.stream.Collectors; +import java.util.function.Predicate; @Mixin(net.minecraft.world.item.crafting.Recipe.class) public interface RecipeMixin_API extends Recipe { // @formatter:off @Shadow ItemStack shadow$assemble(I inv, HolderLookup.Provider registryAccess); - @Shadow net.minecraft.world.item.ItemStack shadow$getResultItem(HolderLookup.Provider registryAccess); @Shadow boolean shadow$isSpecial(); @Shadow boolean shadow$matches(I inv, net.minecraft.world.level.Level worldIn); - @Shadow NonNullList shadow$getRemainingItems(I inv); @Shadow net.minecraft.world.item.crafting.RecipeType shadow$getType(); - @Shadow NonNullList shadow$getIngredients(); - // @formatter:on + @Shadow List shadow$display(); +// @formatter:on @NonNull @Override default ItemStackSnapshot exemplaryResult() { - return ItemStackUtil.snapshotOf(this.shadow$getResultItem(SpongeCommon.server().registryAccess())); + return this.shadow$display().stream() + .map(RecipeDisplay::result) + .map(sd -> sd.resolveForFirstStack(RecipeUtil.serverBasedContextMap())) + .filter(Predicate.not(ItemStack::isEmpty)) + .map(ItemStackUtil::snapshotOf) + .findFirst() + .orElseGet(ItemStackSnapshot::empty); } @Override default boolean isValid(@NonNull final I2 inv, @NonNull final ServerWorld world) { - return this.shadow$matches((I) toCraftingInputOrThrow(inv), (net.minecraft.world.level.Level) world); + return this.shadow$matches((I) InventoryUtil.toCraftingInputOrThrow(inv), (net.minecraft.world.level.Level) world); } @NonNull @Override default ItemStackSnapshot result(@NonNull final I2 inv) { - return ItemStackUtil.snapshotOf(this.shadow$assemble((I) toCraftingInputOrThrow(inv), SpongeCommon.server().registryAccess())); + return ItemStackUtil.snapshotOf(this.shadow$assemble((I) InventoryUtil.toCraftingInputOrThrow(inv), SpongeCommon.server().registryAccess())); } @NonNull @Override default List remainingItems(@NonNull final I2 inv) { - final var nonNullList = this.shadow$getRemainingItems((I) toCraftingInputOrThrow(inv)); - return nonNullList.stream() - .map(ItemStackUtil::snapshotOf) - .collect(Collectors.toList()); - } - - @Override - default List ingredients() { - return this.shadow$getIngredients().stream().map(IngredientUtil::fromNative).collect(Collectors.toList()); + return this.shadow$display().stream() + .map(RecipeDisplay::result) + .filter(sd -> sd instanceof SlotDisplay.WithRemainder) + .map(SlotDisplay.WithRemainder.class::cast) + .map(SlotDisplay.WithRemainder::remainder) + .map(sd -> sd.resolveForFirstStack(RecipeUtil.serverBasedContextMap())) + .filter(Predicate.not(ItemStack::isEmpty)) + .map(ItemStackUtil::snapshotOf) + .toList(); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapedRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapedRecipeMixin_API.java index 595db6d9223..e6d14bab52c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapedRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapedRecipeMixin_API.java @@ -26,10 +26,16 @@ import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapedRecipePattern; +import org.spongepowered.api.item.recipe.crafting.Ingredient; import org.spongepowered.api.item.recipe.crafting.ShapedCraftingRecipe; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; @Mixin(ShapedRecipe.class) public abstract class ShapedRecipeMixin_API implements ShapedCraftingRecipe { @@ -52,6 +58,12 @@ public org.spongepowered.api.item.recipe.crafting.Ingredient ingredient(final in return ((org.spongepowered.api.item.recipe.crafting.Ingredient)(Object) this.pattern.ingredients().get(recipeItemIndex)); } + @Override + public List ingredients() { + return this.pattern.ingredients().stream().filter(Optional::isPresent).map(Optional::get) + .map(IngredientUtil::fromNative).collect(Collectors.toList()); + } + @Override public int width() { return this.pattern.width(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapelessRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapelessRecipeMixin_API.java index 94a417304e9..6414b4aa581 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapelessRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/ShapelessRecipeMixin_API.java @@ -25,10 +25,27 @@ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; import net.minecraft.world.item.crafting.ShapelessRecipe; +import org.spongepowered.api.item.recipe.crafting.Ingredient; import org.spongepowered.api.item.recipe.crafting.ShapelessCraftingRecipe; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; + +import java.util.List; +import java.util.stream.Collectors; @Mixin(ShapelessRecipe.class) public abstract class ShapelessRecipeMixin_API implements ShapelessCraftingRecipe { + // @formatter:off + @Shadow @Final private List ingredients; + // @formatter:on + + @Override + public List ingredients() { + return this.ingredients.stream().map(IngredientUtil::fromNative).collect(Collectors.toList()); + } + + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SingleItemRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SingleItemRecipeMixin_API.java index 72b94a6aa03..d7233ca9379 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SingleItemRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SingleItemRecipeMixin_API.java @@ -24,10 +24,16 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; +import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.SingleItemRecipe; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; @Mixin(SingleItemRecipe.class) public abstract class SingleItemRecipeMixin_API { + // @formatter:off + @Shadow public abstract Ingredient shadow$input(); + // @formatter:on + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SmithingTransformRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SmithingTransformRecipeMixin_API.java index 44c31a04ae4..8ff0d95e645 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SmithingTransformRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/SmithingTransformRecipeMixin_API.java @@ -25,11 +25,36 @@ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; import net.minecraft.world.item.crafting.SmithingTransformRecipe; +import org.spongepowered.api.item.recipe.crafting.Ingredient; import org.spongepowered.api.item.recipe.smithing.SmithingRecipe; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.Optional; @Mixin(SmithingTransformRecipe.class) public abstract class SmithingTransformRecipeMixin_API implements SmithingRecipe { + // @formatter:off + @Shadow @Final Optional addition; + @Shadow @Final Optional template; + @Shadow @Final Optional base; + // @formatter:on + + @Override + public Optional templateIngredient() { + return this.template.map(Ingredient.class::cast); + } + + @Override + public Optional baseIngredient() { + return this.base.map(Ingredient.class::cast); + } + + @Override + public Optional additionalIngredient() { + return this.addition.map(Ingredient.class::cast); + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/StonecutterRecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/StonecutterRecipeMixin_API.java index 5af37c839a3..63a38f12cb6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/StonecutterRecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/StonecutterRecipeMixin_API.java @@ -27,8 +27,15 @@ import net.minecraft.world.item.crafting.StonecutterRecipe; import org.spongepowered.api.item.recipe.single.StoneCutterRecipe; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; @Mixin(StonecutterRecipe.class) public abstract class StonecutterRecipeMixin_API extends SingleItemRecipeMixin_API implements StoneCutterRecipe { + @Override + public org.spongepowered.api.item.recipe.crafting.Ingredient ingredient() { + return IngredientUtil.fromNative(this.shadow$input()); + } + + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/BlockGetterMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/BlockGetterMixin_API.java index c0aa643a6db..c24ffd822ba 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/BlockGetterMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/BlockGetterMixin_API.java @@ -51,14 +51,8 @@ public interface BlockGetterMixin_API extends PrimitiveGameVolume { @Shadow BlockState shadow$getBlockState(BlockPos p_180495_1_); @Shadow net.minecraft.world.level.material.FluidState shadow$getFluidState(BlockPos p_204610_1_); @Shadow int shadow$getLightEmission(BlockPos p_217298_1_); - @Shadow int shadow$getMaxLightLevel(); //@formatter:on - @Override - default int maximumLight() { - return this.shadow$getMaxLightLevel(); - } - @Override default int emittedLight(final Vector3i position) { return this.shadow$getLightEmission(new BlockPos(position.x(), position.y(), position.z())); @@ -71,7 +65,7 @@ default int emittedLight(final int x, final int y, final int z) { @Override default int height() { - return ((LevelHeightAccessor) this).getMaxBuildHeight(); + return ((LevelHeightAccessor) this).getHeight(); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelAccessorMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelAccessorMixin_API.java index 8fbcb34e6c5..8b51058fdbd 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelAccessorMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelAccessorMixin_API.java @@ -82,7 +82,7 @@ default Palette blockPalette( return PaletteWrapper.of( PaletteTypes.BLOCK_STATE_PALETTE.get(), Block.BLOCK_STATE_REGISTRY, - (org.spongepowered.api.registry.Registry) ((LevelAccessor) (Object) this).registryAccess().registryOrThrow(Registries.BLOCK) + (org.spongepowered.api.registry.Registry) ((LevelAccessor) (Object) this).registryAccess().lookupOrThrow(Registries.BLOCK) ); } @@ -98,7 +98,7 @@ default boolean setBiome(final int x, final int y, final int z, final org.sponge return false; } - return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> iChunk.getSection(iChunk.getSectionIndex(y)), () -> iChunk.setUnsaved(true)); + return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> iChunk.getSection(iChunk.getSectionIndex(y)), iChunk::markUnsaved); } // Volume diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index 71e7937a942..446756cfa4f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -222,7 +222,7 @@ public Vector3i size() { private SpongeChunkLayout api$chunkLayout() { if (this.api$chunkLayout == null) { - final var min = ((Level) (Object) this).getMinBuildHeight(); + final var min = ((Level) (Object) this).getMinY(); final var height = ((Level) (Object) this).getHeight(); this.api$chunkLayout = new SpongeChunkLayout(min, height); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java index 236f5c76662..05edacf69d2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java @@ -89,7 +89,7 @@ default Palette blockPalette() { return PaletteWrapper.of( PaletteTypes.BLOCK_STATE_PALETTE.get(), Block.BLOCK_STATE_REGISTRY, - (Registry) this.shadow$registryAccess().registryOrThrow(Registries.BLOCK) + (Registry) this.shadow$registryAccess().lookupOrThrow(Registries.BLOCK) ); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ExplosionMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ServerExplosionMixin_API.java similarity index 86% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ExplosionMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ServerExplosionMixin_API.java index 480737ccfea..ddf60b67eff 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ExplosionMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/ServerExplosionMixin_API.java @@ -24,7 +24,9 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.world.explosion.Explosion; @@ -34,21 +36,22 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.bridge.world.level.ExplosionBridge; +import org.spongepowered.common.util.VecHelper; import java.util.Optional; -@Mixin(net.minecraft.world.level.Explosion.class) -public abstract class ExplosionMixin_API implements Explosion { +@Mixin(net.minecraft.world.level.ServerExplosion.class) +public abstract class ServerExplosionMixin_API implements Explosion { //@formatter:off @Shadow @Final private boolean fire; - @Shadow @Final private net.minecraft.world.level.Level level; - @Shadow @Final private double x; - @Shadow @Final private double y; - @Shadow @Final private double z; + @Shadow @Final private ServerLevel level; + @Shadow @Final private Entity source; @Shadow @Final private float radius; @Shadow @Final private net.minecraft.world.level.Explosion.BlockInteraction blockInteraction; + @Shadow @Final private Vec3 center; + //@formatter:on @Nullable private ServerLocation api$location; @@ -56,7 +59,7 @@ public abstract class ExplosionMixin_API implements Explosion { @Override public ServerLocation location() { if (this.api$location == null) { - this.api$location = ServerLocation.of((ServerWorld) this.level, this.x, this.y, this.z); + this.api$location = ServerLocation.of((ServerWorld) this.level, VecHelper.toVector3d(this.center)); } return this.api$location; } @@ -87,7 +90,10 @@ public boolean shouldPlaySmoke() { @Override public boolean shouldBreakBlocks() { - return ((ExplosionBridge) this).bridge$getShouldDamageBlocks(); + return switch (this.blockInteraction) { + case KEEP, TRIGGER_BLOCK -> false; + case DESTROY, DESTROY_WITH_DECAY -> true; + }; } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientAdditionsSettingsMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientAdditionsSettingsMixin_API.java index d7be89e3af2..5aecb500911 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientAdditionsSettingsMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientAdditionsSettingsMixin_API.java @@ -43,7 +43,7 @@ public abstract class AmbientAdditionsSettingsMixin_API implements SoundConfig.A @Override public SoundType sound() { - return (SoundType) this.soundEvent.value(); + return (SoundType) (Object) this.soundEvent.value(); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientMoodSettingsMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientMoodSettingsMixin_API.java index e047a72155d..4b93d6398b0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientMoodSettingsMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/biome/AmbientMoodSettingsMixin_API.java @@ -45,7 +45,7 @@ public abstract class AmbientMoodSettingsMixin_API implements SoundConfig.Mood { @Override public SoundType sound() { - return (SoundType) this.soundEvent.value(); + return (SoundType) (Object) this.soundEvent.value(); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java index 02911fdedda..a5a0fdfbcdb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java @@ -54,9 +54,10 @@ public abstract class BaseContainerBlockEntityMixin_API extends BlockEntityMixin @Override public DataContainer toContainer() { final DataContainer container = super.toContainer(); - if (this.lockKey != null) { - container.set(Constants.TileEntity.LOCK_CODE, this.lockKey.key()); - } + // TODO - figure out lock code serialization +// if (this.lockKey != null) { +// container.set(Constants.TileEntity.LOCK_CODE, this.lockKey.key()); +// } final List items = Lists.newArrayList(); for (int i = 0; i < ((Container) this).getContainerSize(); i++) { final ItemStack stack = ((Container) this).getItem(i); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/properties/NoteBlockInstrumentMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/properties/NoteBlockInstrumentMixin_API.java index 5686585dcdb..ae1a8fae1be 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/properties/NoteBlockInstrumentMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/properties/NoteBlockInstrumentMixin_API.java @@ -41,6 +41,6 @@ public abstract class NoteBlockInstrumentMixin_API implements InstrumentType { @Override public SoundType sound() { - return (SoundType) this.shadow$getSoundEvent().value(); + return (SoundType) (Object) this.shadow$getSoundEvent().value(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java index 8d124e6d6b5..f1ea1749899 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java @@ -67,7 +67,7 @@ public abstract class ChunkAccessMixin_API

> implements Chunk< @Shadow public abstract ChunkPos shadow$getPos(); @Shadow public abstract int shadow$getHeight(Heightmap.Types var1, int var2, int var3); @Shadow public abstract LevelChunkSection shadow$getSection(int p_187657_); - @Shadow public abstract void shadow$setUnsaved(boolean p_62094_); + @Shadow public abstract void shadow$markUnsaved(); // @formatter:on @SuppressWarnings("unchecked") @Override @@ -96,7 +96,7 @@ public boolean isEmpty() { @Override public boolean setBiome(final int x, final int y, final int z, final Biome biome) { - return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> this.shadow$getSection(this.getSectionIndex(y)), () -> this.shadow$setUnsaved(true)); + return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> this.shadow$getSection(this.getSectionIndex(y)), this::shadow$markUnsaved); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/LevelChunkMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/LevelChunkMixin_API.java index eb2f28f511c..29080211aac 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/LevelChunkMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/LevelChunkMixin_API.java @@ -129,7 +129,7 @@ public Palette blockPalette() { return PaletteWrapper.of( PaletteTypes.BLOCK_STATE_PALETTE.get(), Block.BLOCK_STATE_REGISTRY, - (org.spongepowered.api.registry.Registry) this.level.registryAccess().registry(Registries.BLOCK).get() + (org.spongepowered.api.registry.Registry) this.level.registryAccess().lookupOrThrow(Registries.BLOCK) ); } @@ -143,7 +143,7 @@ public Biome biome(final int x, final int y, final int z) { @Override public boolean setBiome(final int x, final int y, final int z, final Biome biome) { - return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> this.getSection(this.getSectionIndex(y)), () -> this.setUnsaved(true)); + return VolumeStreamUtils.setBiomeOnNativeChunk(x, y, z, biome, () -> this.getSection(this.getSectionIndex(y)), this::markUnsaved); } @Intrinsic @@ -339,7 +339,7 @@ public VolumeStream biomeStream(final Vector3i min, final Vec final Vector3i size = max.sub(min).add(1, 1 ,1); final @MonotonicNonNull ObjectArrayMutableBiomeBuffer backingVolume; if (shouldCarbonCopy) { - final Registry biomeRegistry = this.level.registryAccess().registryOrThrow(Registries.BIOME); + final Registry biomeRegistry = this.level.registryAccess().lookupOrThrow(Registries.BIOME); backingVolume = new ObjectArrayMutableBiomeBuffer(min, size, VolumeStreamUtils.nativeToSpongeRegistry(biomeRegistry)); } else { backingVolume = null; @@ -377,7 +377,7 @@ public int highestYAt(final int x, final int z) { public Vector3i min() { if (this.api$blockMin == null) { if (this.api$chunkLayout == null) { - this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinBuildHeight(), this.level.getHeight()); + this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinY(), this.level.getHeight()); } this.api$blockMin = this.api$chunkLayout.forceToWorld(this.chunkPosition()); } @@ -388,7 +388,7 @@ public Vector3i min() { public Vector3i max() { if (this.api$blockMax == null) { if (this.api$chunkLayout == null) { - this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinBuildHeight(), this.level.getHeight()); + this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinY(), this.level.getHeight()); } this.api$blockMax = this.min().add(this.api$chunkLayout.chunkSize()).sub(1, 1, 1); } @@ -398,7 +398,7 @@ public Vector3i max() { @Override public Vector3i size() { if (this.api$chunkLayout == null) { - this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinBuildHeight(), this.level.getHeight()); + this.api$chunkLayout = new SpongeChunkLayout(this.level.getMinY(), this.level.getHeight()); } return this.api$chunkLayout.chunkSize(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/GenerationStep_CarvingMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/GenerationStep_CarvingMixin_API.java deleted file mode 100644 index cbc9ad223ce..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/GenerationStep_CarvingMixin_API.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.minecraft.world.level.levelgen; - -import net.minecraft.world.level.levelgen.GenerationStep; -import org.spongepowered.api.world.generation.carver.CarvingStep; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(GenerationStep.Carving.class) -public abstract class GenerationStep_CarvingMixin_API implements CarvingStep { - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java index 9e057d9f93d..349ad7f4869 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java @@ -87,7 +87,7 @@ public boolean place(final ServerWorld world, final Vector3i pos) { return false; } ChunkPos.rangeClosed(minPos, maxPos).forEach((chunkPos) -> start.placeInChunk(level, level.structureManager(), chunkSource.getGenerator(), level.getRandom(), - new BoundingBox(chunkPos.getMinBlockX(), level.getMinBuildHeight(), chunkPos.getMinBlockZ(), chunkPos.getMaxBlockX(), level.getMaxBuildHeight(), chunkPos.getMaxBlockZ()), chunkPos)); + new BoundingBox(chunkPos.getMinBlockX(), level.getMinY(), chunkPos.getMinBlockZ(), chunkPos.getMaxBlockX(), level.getMaxY(), chunkPos.getMaxBlockZ()), chunkPos)); return true; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/LevelDataMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/LevelDataMixin_API.java index ce24f3c9beb..cc207d515f5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/LevelDataMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/LevelDataMixin_API.java @@ -24,20 +24,13 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.storage; -import net.minecraft.world.level.GameRules; import net.minecraft.world.level.storage.LevelData; import org.spongepowered.api.util.MinecraftDayTime; -import org.spongepowered.api.world.gamerule.GameRule; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.accessor.world.level.GameRulesAccessor; -import org.spongepowered.common.accessor.world.level.GameRules_ValueAccessor; import org.spongepowered.common.util.SpongeMinecraftDayTime; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; @Mixin(LevelData.class) public interface LevelDataMixin_API extends WorldProperties { @@ -45,7 +38,6 @@ public interface LevelDataMixin_API extends WorldProperties { // @formatter:off @Shadow long shadow$getGameTime(); @Shadow long shadow$getDayTime(); - @Shadow GameRules shadow$getGameRules(); // @formatter:on @Override @@ -58,48 +50,4 @@ default MinecraftDayTime dayTime() { return new SpongeMinecraftDayTime(this.shadow$getDayTime()); } - @Override - default V gameRule(final GameRule gameRule) { - final GameRules.Value value = this.shadow$getGameRules().getRule((GameRules.Key) (Object) Objects.requireNonNull(gameRule, - "gameRule")); - if (value instanceof GameRules.BooleanValue) { - return (V) Boolean.valueOf(((GameRules.BooleanValue) value).get()); - } else if (value instanceof GameRules.IntegerValue) { - return (V) Integer.valueOf(((GameRules.IntegerValue) value).get()); - } - return null; - } - - @Override - default void setGameRule(final GameRule gameRule, final V value) { - Objects.requireNonNull(gameRule, "gameRule"); - Objects.requireNonNull(value, "value"); - - final GameRules.Value mValue = this.shadow$getGameRules().getRule((GameRules.Key) (Object) gameRule); - ((GameRules_ValueAccessor) mValue).invoker$deserialize(value.toString()); - } - - @Override - default Map, ?> gameRules() { - final Map, GameRules.Value> rules = - ((GameRulesAccessor) this.shadow$getGameRules()).accessor$rules(); - - final Map, Object> apiRules = new HashMap<>(); - for (final Map.Entry, GameRules.Value> rule : rules.entrySet()) { - final GameRule key = (GameRule) (Object) rule.getKey(); - final GameRules.Value mValue = rule.getValue(); - Object value = null; - if (mValue instanceof GameRules.BooleanValue) { - value = ((GameRules.BooleanValue) mValue).get(); - } else if (mValue instanceof GameRules.IntegerValue) { - value = ((GameRules.IntegerValue) mValue).get(); - } - - if (value != null) { - apiRules.put(key, value); - } - } - - return apiRules; - } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/ServerLevelDataMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/ServerLevelDataMixin_API.java index b38594bf530..d9238aab2fc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/ServerLevelDataMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/storage/ServerLevelDataMixin_API.java @@ -24,20 +24,26 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.storage; +import net.minecraft.world.level.GameRules; import net.minecraft.world.level.storage.ServerLevelData; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.living.trader.WanderingTrader; import org.spongepowered.api.util.MinecraftDayTime; import org.spongepowered.api.util.Ticks; +import org.spongepowered.api.world.gamerule.GameRule; import org.spongepowered.api.world.server.storage.ServerWorldProperties; import org.spongepowered.api.world.weather.Weather; import org.spongepowered.api.world.weather.WeatherType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.accessor.world.level.GameRulesAccessor; +import org.spongepowered.common.accessor.world.level.GameRules_ValueAccessor; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.SpongeTicks; +import java.util.HashMap; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -54,8 +60,55 @@ public interface ServerLevelDataMixin_API extends ServerWorldProperties { @Shadow void shadow$setWanderingTraderId(UUID p_230394_1_); @Shadow @Nullable UUID shadow$getWanderingTraderId(); @Shadow void shadow$setDayTime(long p_76068_1_); + @Shadow GameRules shadow$getGameRules(); // @formatter:on + + @Override + default V gameRule(GameRule gameRule) { + final GameRules.Value value = this.shadow$getGameRules().getRule((GameRules.Key) (Object) Objects.requireNonNull(gameRule, + "gameRule")); + if (value instanceof GameRules.BooleanValue) { + return (V) Boolean.valueOf(((GameRules.BooleanValue) value).get()); + } else if (value instanceof GameRules.IntegerValue) { + return (V) Integer.valueOf(((GameRules.IntegerValue) value).get()); + } + return null; + } + + @Override + default void setGameRule(final GameRule gameRule, final V value) { + Objects.requireNonNull(gameRule, "gameRule"); + Objects.requireNonNull(value, "value"); + + final GameRules.Value mValue = this.shadow$getGameRules().getRule((GameRules.Key) (Object) gameRule); + ((GameRules_ValueAccessor) mValue).invoker$deserialize(value.toString()); + } + + @Override + default Map, ?> gameRules() { + final Map, GameRules.Value> rules = + ((GameRulesAccessor) this.shadow$getGameRules()).accessor$rules(); + + final Map, Object> apiRules = new HashMap<>(); + for (final Map.Entry, GameRules.Value> rule : rules.entrySet()) { + final GameRule key = (GameRule) (Object) rule.getKey(); + final GameRules.Value mValue = rule.getValue(); + Object value = null; + if (mValue instanceof GameRules.BooleanValue) { + value = ((GameRules.BooleanValue) mValue).get(); + } else if (mValue instanceof GameRules.IntegerValue) { + value = ((GameRules.IntegerValue) mValue).get(); + } + + if (value != null) { + apiRules.put(key, value); + } + } + + return apiRules; + } + @Override default void setDayTime(final MinecraftDayTime dayTime) { this.shadow$setDayTime(dayTime.asTicks().ticks()); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/block/BlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/block/BlockMixin.java index 2427e47a603..ff3e6aae610 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/block/BlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/block/BlockMixin.java @@ -46,16 +46,11 @@ import org.spongepowered.common.bridge.block.DyeColorBlockBridge; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.tracking.PhaseTracker; -import org.spongepowered.common.util.ReflectionUtil; import org.spongepowered.math.vector.Vector3d; @Mixin(value = Block.class) public abstract class BlockMixin implements BlockBridge, TrackableBridge { - private final boolean impl$isVanilla = this.getClass().getName().startsWith("net.minecraft."); - private final boolean impl$hasCollideLogic = ReflectionUtil.isStepOnDeclared(this.getClass()); - private final boolean impl$hasCollideWithStateLogic = ReflectionUtil.isEntityInsideDeclared(this.getClass()); - /** * We captured the dye color when creating the Block.Properties. * As the Properties objects are discarded we transfer it over to the Block itself now. @@ -131,18 +126,4 @@ public abstract class BlockMixin implements BlockBridge, TrackableBridge { } } - @Override - public boolean bridge$isVanilla() { - return this.impl$isVanilla; - } - - @Override - public boolean bridge$hasCollideLogic() { - return this.impl$hasCollideLogic; - } - - @Override - public boolean bridge$hasCollideWithStateLogic() { - return this.impl$hasCollideWithStateLogic; - } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/commands/CommandSourceStackMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/commands/CommandSourceStackMixin.java index bcb20b4169b..7a651e6e2c2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/commands/CommandSourceStackMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/commands/CommandSourceStackMixin.java @@ -54,7 +54,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.accessor.commands.CommandSourceStackAccessor; -import org.spongepowered.common.accessor.world.entity.EntityAccessor; +import org.spongepowered.common.accessor.world.entity.player.PlayerAccessor; import org.spongepowered.common.bridge.commands.CommandSourceBridge; import org.spongepowered.common.bridge.commands.CommandSourceStackBridge; import org.spongepowered.common.event.tracking.PhaseTracker; @@ -116,9 +116,9 @@ public abstract class CommandSourceStackMixin implements CommandSourceStackBridg context.get(EventContextKeys.ROTATION).ifPresent(x -> this.rotation = new Vec2((float) x.x(), (float) x.y())); context.get(EventContextKeys.SUBJECT).ifPresent(x -> { - if (x instanceof EntityAccessor) { - this.permissionLevel = ((EntityAccessor) x).invoker$getPermissionLevel(); - } else if (x instanceof MinecraftServer && !((MinecraftServer) x).isSingleplayer()) { + if (x instanceof PlayerAccessor pa) { + this.permissionLevel = pa.invoker$getPermissionLevel(); + } else if (x instanceof MinecraftServer ms && !ms.isSingleplayer()) { this.permissionLevel = 4; } }); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java index 0ef52cdaf02..410158c665e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java @@ -24,11 +24,13 @@ */ package org.spongepowered.common.mixin.core.core.dispenser; +import net.minecraft.core.Direction; +import net.minecraft.core.Position; import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; import net.minecraft.core.dispenser.ProjectileDispenseBehavior; -import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ProjectileItem; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import org.spongepowered.api.data.Keys; @@ -42,13 +44,17 @@ public abstract class ProjectileDispenseBehaviorMixin extends DefaultDispenseItemBehavior { @Redirect(method = "execute", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z")) - private boolean impl$spawnEntityAndSetShooter(final Level world, final Entity entity, final BlockSource source, final ItemStack stack) { + target = "Lnet/minecraft/world/item/ProjectileItem;asProjectile(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/Position;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/core/Direction;)Lnet/minecraft/world/entity/projectile/Projectile;")) + private net.minecraft.world.entity.projectile.Projectile impl$spawnEntityAndSetShooter(final ProjectileItem instance, final Level level, + final Position position, final ItemStack stack, final Direction direction, final BlockSource source) { + final var entity = instance.asProjectile(level, position, stack, direction); + final BlockEntity tileEntity = source.blockEntity(); if (entity instanceof Projectile && tileEntity instanceof ProjectileSource) { ((Projectile) entity).offer(Keys.SHOOTER, (ProjectileSource) tileEntity); } - return world.addFreshEntity(entity); + + return entity; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java index 9dd8afdc082..2e3c8530884 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java @@ -27,7 +27,7 @@ import com.google.common.collect.Sets; import net.minecraft.core.component.DataComponents; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.InteractionResult; import net.minecraft.world.item.EmptyMapItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -110,11 +110,11 @@ public abstract class EmptyMapItemMixin { private void impl$returnFailResultIfMapWasNotCreated(final Level level, final net.minecraft.world.entity.player.Player playerIn, final InteractionHand handIn, - final CallbackInfoReturnable> cir, + final CallbackInfoReturnable cir, final ItemStack itemstack) { if (itemstack.isEmpty()) { cir.cancel(); - cir.setReturnValue(InteractionResultHolder.fail(playerIn.getItemInHand(handIn))); + cir.setReturnValue(InteractionResult.FAIL); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/nbt/CompoundTagMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/nbt/CompoundTagMixin.java index 5edc7f26754..0ef1e4de132 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/nbt/CompoundTagMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/nbt/CompoundTagMixin.java @@ -24,14 +24,16 @@ */ package org.spongepowered.common.mixin.core.nbt; +import com.google.common.base.Function; +import com.google.common.collect.Maps; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import org.apache.logging.log4j.Level; -import org.checkerframework.checker.nullness.qual.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.ModifyArg; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.util.PrettyPrinter; @@ -54,11 +56,10 @@ public abstract class CompoundTagMixin { @Shadow @Final private Map tags; // @formatter:on - @Redirect(method = "copy()Lnet/minecraft/nbt/CompoundTag;", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/Tag;copy()Lnet/minecraft/nbt/Tag;")) - @Nullable - private Tag impl$checkForOverflowOnCopy(Tag inbt) { - try { - return inbt == null ? null : inbt.copy(); + @Redirect(method = "copy()Lnet/minecraft/nbt/CompoundTag;", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Maps;transformValues(Ljava/util/Map;Lcom/google/common/base/Function;)Ljava/util/Map;")) + private Map impl$checkForOverflowOnCopy(Map fromMap, Function function) { + return Maps.transformValues(fromMap, (tag) -> {try { + return tag == null ? null : tag.copy(); } catch (StackOverflowError e) { final PrettyPrinter printer = new PrettyPrinter(60) .add("StackOverflow from trying to copy this compound") @@ -86,22 +87,22 @@ public abstract class CompoundTagMixin { printer.add(); printer.log(SpongeCommon.logger(), Level.ERROR); return null; - } + }}); } - @Redirect(method = "copy()Lnet/minecraft/nbt/CompoundTag;", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/CompoundTag;put(Ljava/lang/String;Lnet/minecraft/nbt/Tag;)Lnet/minecraft/nbt/Tag;")) - private Tag impl$checkForNullNBTValuesDuringCopy(CompoundTag compound, String key, Tag value) { - if (value == null) { - final IllegalStateException exception = new IllegalStateException("There is a null NBT component in the compound for key: " + key); - SpongeCommon.logger().error("Printing out a stacktrace to catch an exception in performing an NBTTagCompound.copy!\n" - + "If you are seeing this, then Sponge is preventing an exception from being thrown due to unforseen\n" - + "possible bugs in any mods present. Please report this to SpongePowered and/or the relative mod\n" - + "authors for the offending compound data!", exception); - } else { - compound.put(key, value); - } - - return value; + @ModifyArg(method = "copy()Lnet/minecraft/nbt/CompoundTag;", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/CompoundTag;(Ljava/util/Map;)V")) + private Map impl$checkForNullNBTValuesDuringCopy(Map map) { + return Maps.newHashMap(Maps.filterEntries(map, entry -> { + if (entry.getValue() == null) { + final IllegalStateException exception = new IllegalStateException("There is a null NBT component in the compound for key: " + entry.getKey()); + SpongeCommon.logger().error("Printing out a stacktrace to catch an exception in performing an NBTTagCompound.copy!\n" + + "If you are seeing this, then Sponge is preventing an exception from being thrown due to unforseen\n" + + "possible bugs in any mods present. Please report this to SpongePowered and/or the relative mod\n" + + "authors for the offending compound data!", exception); + return false; + } + return true; + })); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/MinecraftServerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/MinecraftServerMixin.java index 135e7757caf..00401bb7d4d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/MinecraftServerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/MinecraftServerMixin.java @@ -128,7 +128,7 @@ public abstract class MinecraftServerMixin implements SpongeServer, MinecraftSer //MinecraftServer Executor to prevent changes in timings. @Override - protected @NonNull Runnable wrapRunnable(@NonNull Runnable runnable) { + public Runnable wrapRunnable(Runnable runnable) { return runnable; } @@ -229,11 +229,13 @@ public String getServerModName() { ci.cancel(); } - @ModifyConstant(method = "tickServer", constant = @Constant(intValue = 0, ordinal = 0, expandZeroConditions = Constant.Condition.LESS_THAN_OR_EQUAL_TO_ZERO), + @ModifyConstant(method = "tickServer", slice = @Slice( - from = @At(value = "FIELD", target = "Lnet/minecraft/server/MinecraftServer;ticksUntilAutosave:I"), - to = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;computeNextAutosaveInterval()I"))) - private int getSaveTickInterval(final int zero) { + to = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;autoSave()V", ordinal = 1), + from = @At(value = "FIELD", target = "Lnet/minecraft/server/MinecraftServer;ticksUntilAutosave:I", ordinal = 0) + ), + constant = @Constant(intValue = 0, ordinal = 0, expandZeroConditions = Constant.Condition.LESS_THAN_OR_EQUAL_TO_ZERO)) + private int impl$getSaveTickInterval(final int zero) { if (!this.shadow$isDedicatedServer()) { return zero; } else if (!this.shadow$isRunning()) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/WorldLoaderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/WorldLoaderMixin.java index 19289d3d438..f5ad465e91c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/WorldLoaderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/WorldLoaderMixin.java @@ -57,4 +57,15 @@ public abstract class WorldLoaderMixin { } + @Redirect(method = "load", at = @At(value = "INVOKE", + target = "Lnet/minecraft/core/LayeredRegistryAccess;replaceFrom(Ljava/lang/Object;[Lnet/minecraft/core/RegistryAccess$Frozen;)Lnet/minecraft/core/LayeredRegistryAccess;")) + private static LayeredRegistryAccess impl$afterLoadDimensionRegistries(final LayeredRegistryAccess instance, + final T $$0, final RegistryAccess.Frozen[] $$1) { + final var lifecycle = Launch.instance().lifecycle(); + lifecycle.establishGlobalRegistries($$1[0], RegistryLayer.DIMENSIONS); + return instance.replaceFrom($$0, $$1); + } + + + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/DifficultyCommandMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/DifficultyCommandMixin.java index d078c048e3a..c54e3ae3e50 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/DifficultyCommandMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/DifficultyCommandMixin.java @@ -58,7 +58,7 @@ public static int setDifficulty(CommandSourceStack source, Difficulty difficulty } else { final LevelData levelData = source.getLevel().getLevelData(); ((ServerWorldProperties) levelData).setDifficulty((org.spongepowered.api.world.difficulty.Difficulty) (Object) difficulty); - source.getLevel().setSpawnSettings(((MinecraftServerAccessor) SpongeCommon.server()).invoker$isSpawningMonsters(), SpongeCommon.server().isSpawningAnimals()); + source.getLevel().setSpawnSettings(((MinecraftServerAccessor) SpongeCommon.server()).invoker$isSpawningMonsters()); source.getLevel().getPlayers(p -> true).forEach(p -> p.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()))); source.sendSuccess(() -> Component.translatable("commands.difficulty.success", difficulty.getDisplayName()), true); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/GameRuleCommandMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/GameRuleCommandMixin.java index c841d31eee9..06440f66c08 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/GameRuleCommandMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/GameRuleCommandMixin.java @@ -38,11 +38,11 @@ public abstract class GameRuleCommandMixin { @Redirect(method = "setRule", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getGameRules()Lnet/minecraft/world/level/GameRules;")) private static GameRules impl$usePerWorldGameRules(final MinecraftServer server, final CommandContext context) { - return context.getSource().getLevel().getLevelData().getGameRules(); + return context.getSource().getLevel().getGameRules(); } @Redirect(method = "queryRule", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getGameRules()Lnet/minecraft/world/level/GameRules;")) private static GameRules impl$usePerWorldGameRules(final MinecraftServer server, final CommandSourceStack source) { - return source.getLevel().getLevelData().getGameRules(); + return source.getLevel().getGameRules(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/TeleportCommandMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/TeleportCommandMixin.java index d8837562c12..1b6676593a7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/TeleportCommandMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/commands/TeleportCommandMixin.java @@ -26,16 +26,20 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; +import net.minecraft.server.commands.LookAt; import net.minecraft.server.commands.TeleportCommand; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.TicketType; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; -import net.minecraft.world.entity.RelativeMovement; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.Relative; import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.phys.Vec3; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.CauseStackManager; @@ -65,8 +69,9 @@ public abstract class TeleportCommandMixin { * @reason Have the teleport command respect our events */ @Overwrite + // TODO check if this is still correct - check if we can get rid of the overwrite private static void performTeleport(CommandSourceStack source, Entity entityIn, ServerLevel worldIn, double x, double y, double z, - Set relativeList, float yaw, float pitch, TeleportCommand.@Nullable LookAt facing) { + Set relativeList, float yaw, float pitch, @Nullable LookAt facing) { double actualX = x; double actualY = y; @@ -110,18 +115,19 @@ private static void performTeleport(CommandSourceStack source, Entity entityIn, actualPitch = rotateEvent.isCancelled() ? entityIn.getXRot() : rotateEvent.toRotation().x(); } - if (entityIn instanceof ServerPlayer) { + if (entityIn instanceof ServerPlayer sp) { ChunkPos chunkpos = new ChunkPos(new BlockPos((int) actualX, (int) actualY, (int) actualZ)); worldIn.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkpos, 1, entityIn.getId()); entityIn.stopRiding(); - if (((ServerPlayer)entityIn).isSleeping()) { - ((ServerPlayer)entityIn).stopSleepInBed(true, true); + if (sp.isSleeping()) { + sp.stopSleepInBed(true, true); } - ((ServerPlayer)entityIn).connection.teleport(actualX, actualY, actualZ, (float) actualYaw, (float) actualPitch, relativeList); + sp.connection.teleport( + new PositionMoveRotation(new Vec3( actualX, actualY, actualZ), Vec3.ZERO, (float) actualYaw, (float) actualPitch), relativeList); } else { entityIn.moveTo(actualX, actualY, actualZ, (float) actualYaw, (float) actualPitch); } @@ -129,12 +135,12 @@ private static void performTeleport(CommandSourceStack source, Entity entityIn, entityIn.setYHeadRot((float) actualYaw); } } else { - if (entityIn instanceof ServerPlayer) { + if (entityIn instanceof ServerPlayer sp) { // To ensure mod code is caught, handling the world change for players happens in teleport // Teleport will create a frame but we want to ensure it'll be the command movement type // TODO check if this is still correct PhaseTracker.getCauseStackManager().addContext(EventContextKeys.MOVEMENT_TYPE, MovementTypes.COMMAND); - ((ServerPlayer) entityIn).teleportTo(worldIn, x, y, z, yaw, pitch); + sp.teleportTo(worldIn, x, y, z, relativeList, yaw, pitch, true); PhaseTracker.getCauseStackManager().removeContext(EventContextKeys.MOVEMENT_TYPE); } else { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { @@ -160,7 +166,7 @@ private static void performTeleport(CommandSourceStack source, Entity entityIn, } entityIn.unRide(); - final Entity result = entityIn.getType().create(worldIn); + final Entity result = entityIn.getType().create(worldIn, EntitySpawnReason.DIMENSION_TRAVEL); if (result == null) { return; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java index 2df47d7beea..4780c5edbcd 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java @@ -33,7 +33,6 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.storage.ChunkSerializer; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.world.chunk.ChunkEvent; @@ -68,6 +67,7 @@ import org.spongepowered.math.vector.Vector3i; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; @Mixin(ChunkMap.class) public abstract class ChunkMapMixin implements ChunkMapBridge { @@ -99,26 +99,15 @@ public abstract class ChunkMapMixin implements ChunkMapBridge { } @Redirect(method = "save", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/chunk/storage/ChunkSerializer;write(Lnet/minecraft/server/level/ServerLevel;" - + "Lnet/minecraft/world/level/chunk/ChunkAccess;)Lnet/minecraft/nbt/CompoundTag;")) - private CompoundTag impl$useSerializationBehaviorForChunkSave(final ServerLevel worldIn, final ChunkAccess chunkIn) { + target = "Lnet/minecraft/server/level/ChunkMap;write(Lnet/minecraft/world/level/ChunkPos;Ljava/util/function/Supplier;)Ljava/util/concurrent/CompletableFuture;")) + private CompletableFuture impl$doNotWriteIfWeHaveNoData(final ChunkMap chunkManager, final ChunkPos pos, final Supplier compound) { final PrimaryLevelDataBridge infoBridge = (PrimaryLevelDataBridge) this.level.getLevelData(); final SerializationBehavior serializationBehavior = infoBridge.bridge$serializationBehavior().orElse(SerializationBehavior.AUTOMATIC); if (serializationBehavior == SerializationBehavior.AUTOMATIC || serializationBehavior == SerializationBehavior.MANUAL) { - return ChunkSerializer.write(worldIn, chunkIn); + return chunkManager.write(pos, compound); } - return null; - } - - @Redirect(method = "save", at = @At(value = "INVOKE", - target = "Lnet/minecraft/server/level/ChunkMap;write(Lnet/minecraft/world/level/ChunkPos;Lnet/minecraft/nbt/CompoundTag;)Ljava/util/concurrent/CompletableFuture;")) - private CompletableFuture impl$doNotWriteIfWeHaveNoData(final ChunkMap chunkManager, final ChunkPos pos, final CompoundTag compound) { - if (compound == null) { - return CompletableFuture.completedFuture(null); - } - - return chunkManager.write(pos, compound); + return CompletableFuture.completedFuture(null); } @Redirect(method = "lambda$scheduleUnload$12", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java index 46a6b89598e..5a96da6bd3c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java @@ -27,14 +27,21 @@ import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.bossevents.CustomBossEvents; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.TicketType; import net.minecraft.server.level.progress.ChunkProgressListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvents; import net.minecraft.util.ProgressListener; import net.minecraft.world.RandomSequences; import net.minecraft.world.entity.ai.village.poi.PoiManager; @@ -43,6 +50,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; +import net.minecraft.world.level.ServerExplosion; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.JukeboxBlockEntity; @@ -132,11 +140,12 @@ public abstract class ServerLevelMixin extends LevelMixin implements ServerLevel @Shadow private int emptyTime; @Shadow @NonNull public abstract MinecraftServer shadow$getServer(); - @Shadow protected abstract void shadow$saveLevelData(); + @Shadow protected abstract void shadow$saveLevelData(final boolean $$0); @Shadow @Final private MinecraftServer server; @Shadow public abstract void levelEvent(@Nullable Player $$0, int $$1, BlockPos $$2, int $$3); @Shadow @Nullable private EndDragonFight dragonFight; + @Shadow @Final private List players; // @formatter:on @@ -229,40 +238,54 @@ public abstract class ServerLevelMixin extends LevelMixin implements ServerLevel @Override public void bridge$triggerExplosion(Explosion explosion) { - // Sponge start // Set up the pre event if (ShouldFire.EXPLOSION_EVENT_PRE) { - final ExplosionEvent.Pre - event = - SpongeEventFactory.createExplosionEventPre(PhaseTracker.getCauseStackManager().currentCause(), - explosion, (org.spongepowered.api.world.server.ServerWorld) this); + final var cause = PhaseTracker.getCauseStackManager().currentCause(); + final ExplosionEvent.Pre event = SpongeEventFactory.createExplosionEventPre(cause, explosion, (ServerWorld) this); if (SpongeCommon.post(event)) { return; } explosion = event.explosion(); } - final net.minecraft.world.level.Explosion mcExplosion = (net.minecraft.world.level.Explosion) explosion; + final ServerExplosion mcExplosion = (ServerExplosion) explosion; try (final PhaseContext ignored = GeneralPhase.State.EXPLOSION.createPhaseContext(PhaseTracker.SERVER) - .explosion((net.minecraft.world.level.Explosion) explosion) + .explosion(mcExplosion) .source(explosion.sourceExplosive().isPresent() ? explosion.sourceExplosive() : this)) { ignored.buildAndSwitch(); - final boolean shouldBreakBlocks = explosion.shouldBreakBlocks(); - // Sponge End mcExplosion.explode(); - mcExplosion.finalizeExplosion(explosion.shouldPlaySmoke()); - if (!shouldBreakBlocks) { - mcExplosion.clearToBlow(); + // see ServerLevel#explode/Level#explode + ParticleOptions particle = mcExplosion.isSmall() ? ParticleTypes.EXPLOSION : ParticleTypes.EXPLOSION_EMITTER; + var sound = SoundEvents.GENERIC_EXPLODE; + for (ServerPlayer player : this.players) { + if (player.distanceToSqr(mcExplosion.center()) < 4096.0) { + Optional kb = Optional.ofNullable(mcExplosion.getHitPlayers().get(player)); + final var packet = new ClientboundExplodePacket(mcExplosion.center(), kb, particle, sound); + this.bridge$handleExplosionPacket(player.connection, explosion, packet); + player.connection.send(packet); + } } - - // Sponge Start - end processing } - // Sponge End } + @Override + public void bridge$handleExplosionPacket(final ServerGamePacketListenerImpl instance, Explosion apiExplosion, + final ClientboundExplodePacket packet) { + if (apiExplosion.shouldPlaySmoke()) { + // TODO no sound? + // TODO control which particle is used (API) + // TODO control sound? (ViewerPacketUtil.resolveEvent) + var newPacket = new ClientboundExplodePacket(packet.center(), packet.playerKnockback(), packet.explosionParticle(), packet.explosionSound()); + instance.send(newPacket); + } + else { + packet.playerKnockback().ifPresent(kb -> instance.send(new ClientboundSetEntityMotionPacket(instance.player.getId(), kb))); + // TODO play sound? + } + } @Override public void bridge$setManualSave(final boolean state) { this.impl$isManualSave = state; @@ -350,7 +373,7 @@ public void save(@Nullable final ProgressListener progress, final boolean flush, // We always save the metadata unless it is NONE if (behavior != SerializationBehavior.NONE) { - this.shadow$saveLevelData(); + this.shadow$saveLevelData(flush); // Sponge Start - We do per-world WorldInfo/WorldBorders/BossBars @@ -492,7 +515,7 @@ public void save(@Nullable final ProgressListener progress, final boolean flush, } } - @Redirect(method = "lambda$onBlockStateChange$13", + @Redirect(method = "lambda$onBlockStateChange$14", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/entity/ai/village/poi/PoiManager;add(Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/Holder;)V" @@ -531,7 +554,7 @@ public void save(@Nullable final ProgressListener progress, final boolean flush, @Override public String toString() { - final Optional worldTypeKey = Optional.ofNullable(this.server.registryAccess().registryOrThrow(Registries.DIMENSION_TYPE).getKey(this.shadow$dimensionType())).map(ResourceKey.class::cast); + final Optional worldTypeKey = Optional.ofNullable(this.server.registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE).getKey(this.shadow$dimensionType())).map(ResourceKey.class::cast); return new StringJoiner(",", ServerLevel.class.getSimpleName() + "[", "]") .add("key=" + this.shadow$dimension()) .add("worldType=" + worldTypeKey.map(ResourceKey::toString).orElse("inline")) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java index 73fcb2a228c..7f5bb335570 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java @@ -56,12 +56,16 @@ import net.minecraft.stats.Stat; import net.minecraft.stats.Stats; import net.minecraft.util.Unit; +import net.minecraft.util.profiling.Profiler; +import net.minecraft.util.profiling.ProfilerFiller; 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.LivingEntity; import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.Relative; import net.minecraft.world.entity.animal.AbstractFish; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -71,7 +75,7 @@ import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.level.border.WorldBorder; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import net.minecraft.world.level.storage.LevelData; import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.PlayerTeam; @@ -148,6 +152,7 @@ import org.spongepowered.common.world.border.PlayerOwnBorderListener; import org.spongepowered.math.vector.Vector3d; +import java.util.EnumSet; import java.util.HashSet; import java.util.Locale; import java.util.Objects; @@ -175,6 +180,7 @@ public abstract class ServerPlayerMixin extends PlayerMixin implements SubjectBr @Shadow protected abstract void shadow$triggerDimensionChangeTriggers(ServerLevel serverworld); @Shadow public abstract void shadow$doCloseContainer(); @Shadow public abstract boolean shadow$setGameMode(GameType param0); + @Shadow public abstract void shadow$setCamera(@org.jetbrains.annotations.Nullable final Entity $$0); // @formatter:on private net.minecraft.network.chat.@Nullable Component impl$connectionMessage; @@ -229,11 +235,11 @@ public abstract class ServerPlayerMixin extends PlayerMixin implements SubjectBr } if (!isChangeOfWorld) { - this.connection.teleport(pos.x(), pos.y(), pos.z(), this.shadow$getYRot(), this.shadow$getXRot(), new HashSet<>()); + this.connection.teleport(new PositionMoveRotation(VecHelper.toVanillaVector3d(pos), Vec3.ZERO, this.shadow$getYRot(), this.shadow$getXRot()), new HashSet<>()); this.connection.resetPosition(); } else { - this.bridge$changeDimension(new DimensionTransition(level, VecHelper.toVanillaVector3d(pos), thisPlayer.getKnownMovement(), - this.shadow$getYRot(), this.shadow$getXRot(), DimensionTransition.DO_NOTHING)); + this.bridge$changeDimension(new TeleportTransition(level, VecHelper.toVanillaVector3d(pos), thisPlayer.getKnownMovement(), + this.shadow$getYRot(), this.shadow$getXRot(), TeleportTransition.DO_NOTHING)); } return true; } @@ -315,7 +321,7 @@ public abstract class ServerPlayerMixin extends PlayerMixin implements SubjectBr @Override public boolean bridge$keepInventory() { if (this.impl$keepInventory == null) { - return this.shadow$level().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY); + return this.shadow$serverLevel().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY); } return this.impl$keepInventory; } @@ -400,7 +406,17 @@ public abstract class ServerPlayerMixin extends PlayerMixin implements SubjectBr * @reason Redirect all teleports through {@link #bridge$changeDimension} to fire our move/rotate/teleport events */ @Overwrite - public void teleportTo(final ServerLevel world, final double x, final double y, final double z, final float yaw, final float pitch) { + public boolean teleportTo(final ServerLevel world, + final double x, + final double y, + final double z, + Set relative, + final float yaw, + final float pitch, + final boolean setCamera) { + if (setCamera) { + this.shadow$setCamera((net.minecraft.server.level.ServerPlayer) (Object) this); + } final boolean hasMovementContext = PhaseTracker.getCauseStackManager().currentContext().containsKey(EventContextKeys.MOVEMENT_TYPE); try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { if (!hasMovementContext) { @@ -408,8 +424,8 @@ public void teleportTo(final ServerLevel world, final double x, final double y, } final var thisPlayer = (net.minecraft.server.level.ServerPlayer) (Object) this; - this.bridge$changeDimension(new DimensionTransition(world, new Vec3(x, y, z), Vec3.ZERO, yaw, pitch, - e -> world.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, e.chunkPosition(), 1, thisPlayer.getId()))); + return this.bridge$changeDimension(new TeleportTransition(world, new Vec3(x, y, z), Vec3.ZERO, yaw, pitch, relative, + e -> world.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, e.chunkPosition(), 1, thisPlayer.getId()))) != null; } } @@ -423,7 +439,7 @@ public void teleportTo(final ServerLevel world, final double x, final double y, * @return The {@link Entity} that is either this one, or replaces this one */ @Override - public @Nullable Entity bridge$changeDimension(final DimensionTransition originalTransition) { + public @Nullable Entity bridge$changeDimension(final TeleportTransition originalTransition) { if (this.shadow$isRemoved()) { return null; } @@ -446,9 +462,9 @@ public void teleportTo(final ServerLevel world, final double x, final double y, // Sponge End if (newLevel.dimension() == oldLevel.dimension()) { // actually no dimension change - this.connection.teleport(transition.pos().x, transition.pos().y, transition.pos().z, transition.yRot(), transition.xRot()); + this.connection.teleport(transition.position().x, transition.position().y, transition.position().z, transition.yRot(), transition.xRot()); this.connection.resetPosition(); - transition.postDimensionTransition().onTransition(thisPlayer); + transition.postTeleportTransition().onTransition(thisPlayer); // TODO setYHeadRot after would rotate event result return thisPlayer; } @@ -461,25 +477,26 @@ public void teleportTo(final ServerLevel world, final double x, final double y, oldLevel.removePlayerImmediately(thisPlayer, Entity.RemovalReason.CHANGED_DIMENSION); this.shadow$unsetRemoved(); - oldLevel.getProfiler().push("moving"); + final ProfilerFiller filler = Profiler.get(); + filler.push("moving"); if (oldLevel.dimension() == Level.OVERWORLD && newLevel.dimension() == Level.NETHER) { this.enteredNetherPosition = thisPlayer.position(); } - oldLevel.getProfiler().pop(); + filler.pop(); - oldLevel.getProfiler().push("placing"); + filler.push("placing"); thisPlayer.setServerLevel(newLevel); - this.connection.teleport(transition.pos().x, transition.pos().y, transition.pos().z, transition.yRot(), transition.xRot()); + this.connection.teleport(transition.position().x, transition.position().y, transition.position().z, transition.yRot(), transition.xRot()); this.connection.resetPosition(); newLevel.addDuringTeleport(thisPlayer); - oldLevel.getProfiler().pop(); + filler.pop(); this.shadow$triggerDimensionChangeTriggers(oldLevel); // TODO old sponge EntityUtil#performPostChangePlayerWorldLogic this was only done when using a portal this.connection.send(new ClientboundPlayerAbilitiesPacket(thisPlayer.getAbilities())); playerList.sendLevelInfo(thisPlayer, newLevel); playerList.sendAllPlayerInfo(thisPlayer); playerList.sendActivePlayerEffects(thisPlayer); - transition.postDimensionTransition().onTransition(thisPlayer); + transition.postTeleportTransition().onTransition(thisPlayer); // TODO old sponge EntityUtil#performPostChangePlayerWorldLogic called bridge$getBossBarManager().onPlayerDisconnect(player); on both worlds // TODO old sponge EntityUtil#performPostChangePlayerWorldLogic closed player.closeContainer(); when open this.lastSentExp = -1; @@ -500,7 +517,7 @@ public void teleportTo(final ServerLevel world, final double x, final double y, } @Nullable - private DimensionTransition impl$fireDimensionTransitionEvents(final DimensionTransition originalTransition, + private TeleportTransition impl$fireDimensionTransitionEvents(final TeleportTransition originalTransition, final net.minecraft.server.level.ServerPlayer thisPlayer) { var transition = originalTransition; var isDimensionChange = transition.newLevel() != thisPlayer.serverLevel(); @@ -518,7 +535,7 @@ public void teleportTo(final ServerLevel world, final double x, final double y, frame.addContext(EventContextKeys.MOVEMENT_TYPE, MovementTypes.PLUGIN); } - final var originalDest = VecHelper.toVector3d(transition.pos()); + final var originalDest = VecHelper.toVector3d(transition.position()); final @Nullable Vector3d newDest; if (isDimensionChange) { @@ -528,12 +545,14 @@ public void teleportTo(final ServerLevel world, final double x, final double y, return null; } if (preEvent.destinationWorld() != preEvent.originalDestinationWorld()) { - transition = new DimensionTransition((ServerLevel) preEvent.destinationWorld(), - transition.pos(), - transition.speed(), + transition = new TeleportTransition((ServerLevel) preEvent.destinationWorld(), + transition.position(), + transition.deltaMovement(), transition.yRot(), transition.xRot(), transition.missingRespawnBlock(), - transition.postDimensionTransition()); + transition.asPassenger(), + EnumSet.noneOf(Relative.class), + transition.postTeleportTransition()); } } @@ -554,12 +573,14 @@ public void teleportTo(final ServerLevel world, final double x, final double y, } if (newDest != originalDest) { // if changed override the DimensionTransition - transition = new DimensionTransition(transition.newLevel(), + transition = new TeleportTransition(transition.newLevel(), VecHelper.toVanillaVector3d(newDest), - transition.speed(), + transition.deltaMovement(), transition.yRot(), transition.xRot(), transition.missingRespawnBlock(), - transition.postDimensionTransition()); + transition.asPassenger(), + EnumSet.noneOf(Relative.class), + transition.postTeleportTransition()); } final Vector3d toRot = new Vector3d(transition.xRot(), transition.yRot(), 0); @@ -570,12 +591,14 @@ public void teleportTo(final ServerLevel world, final double x, final double y, newToRot = fromRot; // Cancelled Rotate - Reset to original rotation } if (toRot != newToRot) { - transition = new DimensionTransition(transition.newLevel(), - transition.pos(), - transition.speed(), + transition = new TeleportTransition(transition.newLevel(), + transition.position(), + transition.deltaMovement(), (float) newToRot.y(), (float) newToRot.x(), transition.missingRespawnBlock(), - transition.postDimensionTransition()); + transition.asPassenger(), + EnumSet.noneOf(Relative.class), + transition.postTeleportTransition()); } } @@ -618,7 +641,7 @@ public void die(final DamageSource cause) { } // Sponge end - final var level = this.shadow$level(); + final var level = this.shadow$serverLevel(); final boolean flag = level.getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES) && !event.isMessageCancelled(); if (flag) { final net.minecraft.network.chat.Component component = this.shadow$getCombatTracker().getDeathMessage(); @@ -909,8 +932,12 @@ private boolean isPvpAllowed() { return ((ServerWorld) this.shadow$serverLevel()).properties().pvp(); } + /** + * @author gabizou - 1.21.2-pre1 + * @reason We route all teleportation through sponge's bridge for handling events + */ @Overwrite - public Entity changeDimension(final DimensionTransition transition) { + public @Nullable Entity teleport(final TeleportTransition transition) { return this.bridge$changeDimension(transition); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java index 9b17229b8f5..58c4741603f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java @@ -55,7 +55,8 @@ import net.minecraft.util.StringUtil; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.RelativeMovement; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.Relative; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ClipContext; @@ -127,9 +128,8 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack @Shadow private double vehicleFirstGoodX; @Shadow private double vehicleFirstGoodY; @Shadow private double vehicleFirstGoodZ; - @Shadow private int chatSpamTickCount; - @Shadow public abstract void shadow$teleport(double x, double y, double z, float yaw, float pitch, Set relativeArguments); + @Shadow public abstract void shadow$teleport(PositionMoveRotation pitch, Set relativeArguments); @Shadow protected abstract CompletableFuture> shadow$filterTextPacket(final List $$0); @Shadow protected abstract void shadow$performUnsignedChatCommand(final String $$0); @Shadow protected abstract void shadow$performSignedChatCommand(ServerboundChatCommandSignedPacket $$0, LastSeenMessages $$1); @@ -258,9 +258,13 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack this.player.absMoveTo(fromPosition.x(), fromPosition.y(), fromPosition.z()); this.player.setXRot((float) originalToRotation.x()); this.player.setYRot((float) originalToRotation.y()); - this.shadow$teleport(fromPosition.x(), fromPosition.y(), fromPosition.z(), - (float) toRotation.y(), (float) toRotation.x(), - EnumSet.of(RelativeMovement.X_ROT, RelativeMovement.Y_ROT)); + this.shadow$teleport(new PositionMoveRotation( + VecHelper.toVanillaVector3d(fromPosition), + Vec3.ZERO, + (float) toRotation.y(), (float) toRotation.x() + ), + EnumSet.of(Relative.X_ROT, Relative.Y_ROT) + ); ci.cancel(); return; } @@ -274,9 +278,11 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack this.player.absMoveTo(originalToPosition.x(), originalToPosition.y(), originalToPosition.z()); this.player.setXRot((float) originalToRotation.x()); this.player.setYRot((float) originalToRotation.y()); - this.shadow$teleport(toPosition.x(), toPosition.y(), toPosition.z(), - (float) toRotation.y(), (float) toRotation.x(), - EnumSet.allOf(RelativeMovement.class)); + this.shadow$teleport(new PositionMoveRotation( + VecHelper.toVanillaVector3d(toPosition), + Vec3.ZERO, + (float) toRotation.y(), (float) toRotation.x()), + EnumSet.allOf(Relative.class)); ci.cancel(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java index 76d5070d026..a0a538b1aa2 100755 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java @@ -490,10 +490,9 @@ public abstract class PlayerListMixin implements PlayerListBridge { ((ServerPlayer) entity).offer(Keys.LAST_DATE_PLAYED, Instant.now()); } - @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Inject(method = "respawn", at = @At(value = "INVOKE", - target = "Lnet/minecraft/server/level/ServerPlayer;findRespawnPositionAndUseSpawnBlock(ZLnet/minecraft/world/level/portal/DimensionTransition$PostDimensionTransition;)Lnet/minecraft/world/level/portal/DimensionTransition;" + target = "Lnet/minecraft/server/level/ServerPlayer;findRespawnPositionAndUseSpawnBlock(ZLnet/minecraft/world/level/portal/TeleportTransition$PostTeleportTransition;)Lnet/minecraft/world/level/portal/TeleportTransition;" ) ) private void impl$flagIfRespawnPositionIsGameMechanic(final net.minecraft.server.level.ServerPlayer $$0, final boolean $$1, diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/damagesource/DamageSourcesMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/damagesource/DamageSourcesMixin.java index 097b90cd9c2..9d4bc671a77 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/damagesource/DamageSourcesMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/damagesource/DamageSourcesMixin.java @@ -31,7 +31,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.common.accessor.world.level.ExplosionAccessor; +import org.spongepowered.common.accessor.world.level.ServerExplosionAccessor; import org.spongepowered.common.bridge.CreatorTrackedBridge; import org.spongepowered.common.bridge.world.level.LevelBridge; @@ -45,7 +45,7 @@ private LivingEntity onSetExplosionSource(final Explosion explosion) { // When indirect source is not set if (explosion.getIndirectSourceEntity() == null && explosion.getDirectSourceEntity() instanceof CreatorTrackedBridge creatorBridge - && !((LevelBridge) ((ExplosionAccessor) explosion).accessor$level()).bridge$isFake()) { + && !((LevelBridge) ((ServerExplosionAccessor) explosion).accessor$level()).bridge$isFake()) { // check creator var indirectSource = creatorBridge.tracker$getCreatorUUID().flatMap(x -> Sponge.server().player(x)); if (indirectSource.isPresent()) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java index 62911ab93fe..971e4b85784 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java @@ -32,17 +32,22 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; +import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerPlayerConnection; import net.minecraft.sounds.SoundEvent; import net.minecraft.util.RandomSource; +import net.minecraft.util.profiling.Profiler; +import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.entity.MoverType; import net.minecraft.world.entity.PortalProcessor; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; @@ -53,7 +58,7 @@ import net.minecraft.world.level.block.Portal; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; @@ -159,9 +164,9 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, @Shadow public abstract void shadow$setInvisible(boolean invisible); @Shadow public abstract EntityType shadow$getType(); @Shadow public abstract void shadow$teleportTo(double x, double y, double z); - @Shadow public abstract CommandSourceStack shadow$createCommandSourceStack(); + @Shadow public abstract CommandSourceStack shadow$createCommandSourceStackForNameResolution(ServerLevel level); @Shadow public abstract net.minecraft.world.phys.Vec3 shadow$position(); - @Shadow @Nullable public abstract ItemEntity shadow$spawnAtLocation(ItemStack stack, float offsetY); + @Shadow @Nullable public abstract ItemEntity shadow$spawnAtLocation(ServerLevel $$0, ItemStack stack, float offsetY); @Shadow @Nullable public abstract Entity shadow$getVehicle(); @Shadow public abstract AABB shadow$getBoundingBox(); @Shadow @Nullable public abstract PlayerTeam shadow$getTeam(); @@ -172,7 +177,6 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, @Shadow public abstract void shadow$setDeltaMovement(net.minecraft.world.phys.Vec3 motion); @Shadow public abstract void shadow$unRide(); @Shadow protected abstract void shadow$removeAfterChangingDimensions(); - @Shadow protected abstract int shadow$getPermissionLevel(); @Shadow public abstract float shadow$getYRot(); @Shadow public abstract float shadow$getXRot(); @Shadow public abstract void shadow$setYRot(final float param0); @@ -183,6 +187,16 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, @Shadow @javax.annotation.Nullable public PortalProcessor portalProcess; // @formatter:on + @Shadow public abstract void move(final MoverType $$0, final Vec3 $$1); + + @Shadow public abstract boolean save(final CompoundTag $$0); + + @Shadow public abstract Vec3 calculateViewVector(final float $$0, final float $$1); + + @Shadow public abstract Level level(); + + @Shadow public abstract boolean startRiding(final Entity $$0); + private boolean impl$isConstructing = true; private VanishState impl$vanishState = VanishState.unvanished(); protected boolean impl$transient = false; @@ -291,7 +305,7 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, this.bridge$revive(); level.addDuringTeleport((Entity) (Object) this); */ - var entity = this.shadow$getType().create(level); + var entity = this.shadow$getType().create(level, EntitySpawnReason.DIMENSION_TRAVEL); if (entity == null) { return false; } @@ -406,7 +420,7 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, @Override public CommandSourceStack bridge$getCommandSource(final Cause cause) { - return this.shadow$createCommandSourceStack(); + return this.shadow$createCommandSourceStackForNameResolution((ServerLevel) this.shadow$level()); } /** @@ -416,7 +430,7 @@ public abstract class EntityMixin implements EntityBridge, PlatformEntityBridge, * TODO we may need to separate into Vanilla and Forge again */ @Overwrite - public Entity changeDimension(final DimensionTransition transition) { + public Entity teleport(final TeleportTransition transition) { return this.bridge$changeDimension(transition); } @@ -457,8 +471,8 @@ public Entity changeDimension(final DimensionTransition transition) { * See {@link PortalProcessorMixin#impl$onGetPortalDestination} for portal events */ @Redirect(method = "handlePortal", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;changeDimension(Lnet/minecraft/world/level/portal/DimensionTransition;)Lnet/minecraft/world/entity/Entity;")) - public Entity impl$onChangeDimension(final Entity instance, final DimensionTransition transition) { + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;teleport(Lnet/minecraft/world/level/portal/TeleportTransition;)Lnet/minecraft/world/entity/Entity;")) + public Entity impl$onChangeDimension(final Entity instance, final TeleportTransition transition) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); var be = this.shadow$level().getBlockEntity(this.portalProcess.getEntryPosition()); @@ -473,7 +487,7 @@ public Entity changeDimension(final DimensionTransition transition) { // TODO frame.addContext(EventContextKeys.PORTAL, transition); // TODO 2-dim portal? this.impl$moveEventsFired = true; - return instance.changeDimension(transition); + return instance.teleport(transition); } finally { this.impl$moveEventsFired = false; } @@ -486,7 +500,7 @@ public Entity changeDimension(final DimensionTransition transition) { */ @SuppressWarnings("ConstantConditions") @Nullable - public Entity bridge$changeDimension(final DimensionTransition transition) { + public Entity bridge$changeDimension(final TeleportTransition transition) { final Entity thisEntity = (Entity) (Object) this; if (!(thisEntity.level() instanceof ServerLevel oldLevel) || this.shadow$isRemoved()) { // Sponge inverted check return null; @@ -498,23 +512,24 @@ public Entity changeDimension(final DimensionTransition transition) { List recreatedPassengers = new ArrayList<>(); this.shadow$unRide(); for (final Entity passenger : passengers) { - var recreatedPassenger = passenger.changeDimension(transition); + var recreatedPassenger = passenger.teleport(transition); if (recreatedPassenger != null) { recreatedPassengers.add(recreatedPassenger); } } - oldLevel.getProfiler().push("changeDimension"); + ProfilerFiller filler = Profiler.get(); + filler.push("changeDimension"); - var newEntity = oldLevel.dimension() == newLevel.dimension() ? thisEntity : thisEntity.getType().create(newLevel); + var newEntity = oldLevel.dimension() == newLevel.dimension() ? thisEntity : thisEntity.getType().create(newLevel, EntitySpawnReason.DIMENSION_TRAVEL); if (newEntity != null) { if (thisEntity != newEntity) { newEntity.restoreFrom(thisEntity); this.shadow$removeAfterChangingDimensions(); } - newEntity.moveTo(transition.pos().x, transition.pos().y, transition.pos().z, transition.yRot(), newEntity.getXRot()); - newEntity.setDeltaMovement(transition.speed()); + newEntity.moveTo(transition.position().x, transition.position().y, transition.position().z, transition.yRot(), newEntity.getXRot()); + newEntity.setDeltaMovement(transition.deltaMovement()); if (thisEntity != newEntity) { newLevel.addDuringTeleport(newEntity); } @@ -525,13 +540,13 @@ public Entity changeDimension(final DimensionTransition transition) { oldLevel.resetEmptyTime(); newLevel.resetEmptyTime(); - transition.postDimensionTransition().onTransition(newEntity); + transition.postTeleportTransition().onTransition(newEntity); } // TODO impl$fireMoveEvent when not changing dimensions (e.g. EndGateways) - oldLevel.getProfiler().pop(); + filler.pop(); return newEntity; } @@ -644,23 +659,20 @@ public void stopRiding() { @Redirect(method = "lavaHurt", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z" + target = "Lnet/minecraft/world/entity/Entity;hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z" ) ) - private boolean impl$createLavaBlockDamageSource(final Entity entity, final DamageSource source, final float damage) { - if (this.shadow$level().isClientSide) { // Short circuit - return entity.hurt(source, damage); - } + private boolean impl$createLavaBlockDamageSource(final Entity instance, ServerLevel serverLevel, DamageSource source, float damage) { final AABB bb = this.shadow$getBoundingBox().inflate(-0.10000000149011612D, -0.4000000059604645D, -0.10000000149011612D); - final ServerLocation location = DamageEventUtil.findFirstMatchingBlock((Entity) (Object) this, bb, block -> + final ServerLocation location = DamageEventUtil.findFirstMatchingBlock(instance, bb, block -> block.is(Blocks.LAVA) || block.getBlock() instanceof LavaCauldronBlock); if (location != null) { var blockSource = org.spongepowered.api.event.cause.entity.damage.source.DamageSource.builder() .from((org.spongepowered.api.event.cause.entity.damage.source.DamageSource) source).block(location) .block(location.createSnapshot()).build(); - return entity.hurt((DamageSource) blockSource, damage); + return instance.hurtServer(serverLevel, (DamageSource) blockSource, damage); } - return entity.hurt(source, damage); + return instance.hurtServer(serverLevel, source, damage); } @Redirect(method = "move", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;collide(Lnet/minecraft/world/phys/Vec3;)Lnet/minecraft/world/phys/Vec3;")) @@ -711,7 +723,7 @@ public void stopRiding() { } @Redirect( - method = "move", + method = "applyEffectsFromBlocks(Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/phys/Vec3;)V", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/level/block/Block;stepOn(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/Entity;)V" @@ -731,7 +743,7 @@ public void stopRiding() { } - @Redirect(method = "checkInsideBlocks", + @Redirect(method = "checkInsideBlocks(Ljava/util/List;Ljava/util/Set;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;entityInside(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/Entity;)V" ) @@ -750,18 +762,12 @@ public void stopRiding() { } - /** - * @author gabizou - January 4th, 2016 - * @reason gabizou - January 27th, 2016 - Rewrite to a redirect - *

- * This prevents sounds from being sent to the server by entities that are vanished - */ - - @Redirect(method = "playSound", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;isSilent()Z")) - private boolean impl$checkIsSilentOrInvis(final Entity entity) { - return entity.isSilent() || !this.bridge$vanishState().createsSounds(); + @Redirect(method = "isSilent", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/network/syncher/SynchedEntityData;get(Lnet/minecraft/network/syncher/EntityDataAccessor;)Ljava/lang/Object;" + )) + private Object impl$checkIsSilentOrInvis(final SynchedEntityData data, final EntityDataAccessor key) { + return data.get(key) || !this.bridge$vanishState().createsSounds(); } @Redirect(method = "push(Lnet/minecraft/world/entity/Entity;)V", @@ -811,18 +817,18 @@ public void stopRiding() { */ @Inject( - method = "spawnAtLocation(Lnet/minecraft/world/item/ItemStack;F)Lnet/minecraft/world/entity/item/ItemEntity;", + method = "spawnAtLocation(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;F)Lnet/minecraft/world/entity/item/ItemEntity;", at = @At("HEAD"), cancellable = true ) public void impl$throwDropItemConstructEvent( - final ItemStack stack, final float offsetY, final CallbackInfoReturnable cir + final ServerLevel serverLevel, ItemStack stack, float offsetY, CallbackInfoReturnable cir ) { if (stack.isEmpty()) { cir.setReturnValue(null); return; } - if (((LevelBridge) this.shadow$level()).bridge$isFake()) { + if (((LevelBridge) serverLevel).bridge$isFake()) { return; } // Now the real fun begins. @@ -848,7 +854,7 @@ public void stopRiding() { } final ItemEntity entityitem = new ItemEntity(this.shadow$level(), posX, posY, posZ, item); entityitem.setDefaultPickUpDelay(); - this.shadow$level().addFreshEntity(entityitem); + serverLevel.addFreshEntity(entityitem); cir.setReturnValue(entityitem); } } @@ -931,16 +937,13 @@ public void stopRiding() { @Redirect(method = "thunderHit", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + target = "Lnet/minecraft/world/entity/Entity;hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z")) private boolean impl$ThrowDamageEventWithLightingSource( - final Entity entity, final DamageSource source, final float damage, + final Entity entity, final ServerLevel serverLevel, final DamageSource source, final float damage, final ServerLevel level, final LightningBolt lightningBolt ) { - if (!this.shadow$level().isClientSide) { - return entity.hurt(source, damage); - } var entitySource = new DamageSource(source.typeHolder(), lightningBolt); - return entity.hurt(entitySource, damage); + return entity.hurtServer(serverLevel, entitySource, damage); } @Inject(method = "getFireImmuneTicks", at = @At(value = "HEAD"), cancellable = true) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ExperienceOrbMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ExperienceOrbMixin.java index 0a56467684a..451d8b72663 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ExperienceOrbMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ExperienceOrbMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.ExperienceOrb; @@ -45,9 +46,9 @@ public abstract class ExperienceOrbMixin extends EntityMixin { this.impl$callExpireEntityEvent(); } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/ExperienceOrb;markHurt()V")) - private void attackImpl$onAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$onAttackEntityFrom(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java index c36f90a02f7..fff8bd381fb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java @@ -29,8 +29,6 @@ import net.minecraft.core.particles.ParticleOptions; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.CombatTracker; import net.minecraft.world.damagesource.DamageSource; @@ -105,12 +103,12 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt @Shadow public abstract int shadow$getUseItemRemainingTicks(); @Shadow public abstract float shadow$getHealth(); @Shadow public abstract CombatTracker shadow$getCombatTracker(); - @Shadow public void shadow$kill() { } + @Shadow public void shadow$kill(ServerLevel level) { } @Shadow public abstract InteractionHand shadow$getUsedItemHand(); @Shadow public abstract Optional shadow$getSleepingPos(); @Shadow protected abstract void shadow$spawnItemParticles(ItemStack stack, int count); @Shadow public abstract ItemStack shadow$getItemInHand(InteractionHand hand); - @Shadow protected abstract void shadow$dropEquipment(); + @Shadow protected abstract void shadow$dropEquipment(ServerLevel level); @Shadow protected abstract void shadow$dropAllDeathLoot(ServerLevel level, DamageSource damageSourceIn); @Shadow @Nullable public abstract LivingEntity shadow$getKillCredit(); @Shadow protected abstract void shadow$createWitherRose(@Nullable LivingEntity p_226298_1_); @@ -173,14 +171,14 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt @Redirect(method = "dropAllDeathLoot", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/LivingEntity;dropEquipment()V" + target = "Lnet/minecraft/world/entity/LivingEntity;dropEquipment(Lnet/minecraft/server/level/ServerLevel;)V" ) ) - private void tracker$dropInventory(final LivingEntity thisEntity) { + private void tracker$dropInventory(final LivingEntity thisEntity, final ServerLevel level) { if (thisEntity instanceof PlayerBridge && ((PlayerBridge) thisEntity).bridge$keepInventory()) { return; } - this.shadow$dropEquipment(); + this.shadow$dropEquipment(level); } @Inject(method = "pushEntities", at = @At("HEAD"), cancellable = true) @@ -190,14 +188,7 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt } } - @Redirect(method = "triggerItemUseEffects", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/LivingEntity;spawnItemParticles(Lnet/minecraft/world/item/ItemStack;I)V")) - private void impl$hideItemParticlesIfVanished(final LivingEntity livingEntity, final ItemStack stack, final int count) { - if (this.bridge$vanishState().createsParticles()) { - this.shadow$spawnItemParticles(stack, count); - } - } + @Inject(method = "randomTeleport", at = @At("HEAD")) private void impl$snapshotPositionBeforeVanillaTeleportLogic(final double x, final double y, final double z, final boolean changeState, @@ -248,23 +239,6 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt } } - @Redirect( - method = "eat(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/food/FoodProperties;)Lnet/minecraft/world/item/ItemStack;", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;playSound(Lnet/minecraft/world/entity/player/Player;DDDLnet/minecraft/sounds/SoundEvent;Lnet/minecraft/sounds/SoundSource;FF)V" - ) - ) - private void impl$ignoreExperienceLevelSoundsWhileVanished(final net.minecraft.world.level.Level world, - final net.minecraft.world.entity.player.Player player, final double x, final double y, final double z, - final SoundEvent sound, final SoundSource category, final float volume, final float pitch - ) { - if (!this.bridge$vanishState().createsSounds()) { - return; - } - world.playSound(player, x, y, z, sound, category, volume, pitch); - } - @Redirect(method = "checkFallDamage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;sendParticles(Lnet/minecraft/core/particles/ParticleOptions;DDDIDDDD)I")) @@ -399,7 +373,7 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt @Inject(method = "completeUsingItem", cancellable = true, at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/LivingEntity;triggerItemUseEffects(Lnet/minecraft/world/item/ItemStack;I)V")) + target = "Lnet/minecraft/world/item/ItemStack;finishUsingItem(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/LivingEntity;)Lnet/minecraft/world/item/ItemStack;")) private void impl$onUpdateItemUse(final CallbackInfo ci) { if (this.shadow$level().isClientSide) { return; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java index 945960567fd..dd36c767846 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvent; import net.minecraft.stats.Stats; @@ -83,8 +84,8 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Forge onLivingAttack Hook */ - @Inject(method = "hurt", at = @At("HEAD"), cancellable = true) - private void attackImpl$beforeHurt(final DamageSource source, final float damageTaken, final CallbackInfoReturnable cir) { + @Inject(method = "hurtServer", at = @At("HEAD"), cancellable = true) + private void attackImpl$beforeHurt(final ServerLevel level, final DamageSource source, final float damageTaken, final CallbackInfoReturnable cir) { if (source == null) { new PrettyPrinter(60).centre().add("Null DamageSource").hr() .addWrapped("Sponge has found a null damage source! This should NEVER happen " @@ -102,8 +103,8 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Prepare {@link org.spongepowered.common.util.DamageEventUtil.Hurt} for damage event */ - @Inject(method = "hurt", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/LivingEntity;noActionTime:I")) - private void attackImpl$preventEarlyBlock1(final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { + @Inject(method = "hurtServer", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/LivingEntity;noActionTime:I")) + private void attackImpl$preventEarlyBlock1(final ServerLevel level, final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { this.attackImpl$hurt = new DamageEventUtil.Hurt($$0, new ArrayList<>()); } @@ -111,7 +112,7 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen * Prevents shield usage before event * Captures the blocked damage as a function */ - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurtCurrentlyUsedShield(F)V")) + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurtCurrentlyUsedShield(F)V")) private void attackImpl$preventEarlyBlock1(final LivingEntity instance, final float damageToShield) { // this.hurtCurrentlyUsedShield(damageToShield); this.attackImpl$hurt.functions().add(DamageEventUtil.createShieldFunction(instance)); @@ -120,7 +121,7 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Prevents shield usage before event */ - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;blockUsingShield(Lnet/minecraft/world/entity/LivingEntity;)V")) + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;blockUsingShield(Lnet/minecraft/world/entity/LivingEntity;)V")) private void attackImpl$preventEarlyBlock2(final LivingEntity instance, final LivingEntity livingDamageSource) { // this.blockUsingShield(livingDamageSource); } @@ -128,8 +129,8 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Capture the bonus freezing damage as a function */ - @Inject(method = "hurt", at = @At(value = "CONSTANT", args = "floatValue=5.0F")) - private void attackImpl$freezingBonus(final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { + @Inject(method = "hurtServer", at = @At(value = "CONSTANT", args = "floatValue=5.0F")) + private void attackImpl$freezingBonus(final ServerLevel level, final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { this.attackImpl$hurt.functions().add(DamageEventUtil.createFreezingBonus((LivingEntity) (Object) this, $$0, 5.0F)); } @@ -137,7 +138,7 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen * Prevents {@link #shadow$hurtHelmet} before the event * Captures the hard hat damage reduction as a function */ - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurtHelmet(Lnet/minecraft/world/damagesource/DamageSource;F)V")) + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurtHelmet(Lnet/minecraft/world/damagesource/DamageSource;F)V")) private void attackImpl$hardHat(final LivingEntity instance, final DamageSource $$0, final float $$1) { // this.hurtHelmet($$0, $$1); this.attackImpl$hurt.functions().add(DamageEventUtil.createHardHatModifier(instance.getItemBySlot(EquipmentSlot.HEAD), 0.75F)); @@ -146,21 +147,21 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Capture the old values to reset if we end up cancelling or blocking. */ - @Inject(method = "hurt", at = @At(value = "FIELD", + @Inject(method = "hurtServer", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/LivingEntity;walkAnimation:Lnet/minecraft/world/entity/WalkAnimationState;")) - private void attackImpl$beforeActuallyHurt(final DamageSource source, final float damageTaken, final CallbackInfoReturnable cir) { + private void attackImpl$beforeActuallyHurt(final ServerLevel level, final DamageSource source, final float damageTaken, final CallbackInfoReturnable cir) { // Save old values this.attackImpl$lastHurt = this.lastHurt; this.attackImpl$InvulnerableTime = this.invulnerableTime; this.attackImpl$actuallyHurtCancelled = false; } - @ModifyArg(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/world/damagesource/DamageSource;F)V", ordinal = 0)) + @ModifyArg(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V", ordinal = 0)) private float attackImp$useBaseDamage1(final float $$0) { return this.attackImpl$baseDamage - this.attackImpl$lastHurt; } - @ModifyArg(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/world/damagesource/DamageSource;F)V", ordinal = 1)) + @ModifyArg(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V", ordinal = 1)) private float attackImp$useBaseDamage2(final float $$0) { return this.attackImpl$baseDamage; } @@ -169,14 +170,13 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen * After calling #actuallyHurt (even when invulnerable), if cancelled return early or is still invulnerable * and reset {@link #lastHurt} and {@link #invulnerableTime} */ - @Inject(method = "hurt", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, + @Inject(method = "hurtServer", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At(value = "INVOKE", shift = At.Shift.AFTER, ordinal = 0, - target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/world/damagesource/DamageSource;F)V")) - private void attackImpl$afterActuallyHurt1(final DamageSource $$0, - final float damageTaken, - final CallbackInfoReturnable cir, - final float dealtDamage, - final boolean isBlocked + target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V")) + private void attackImpl$afterActuallyHurt1( + final ServerLevel level, final DamageSource source, final float damageTaken, + final CallbackInfoReturnable cir, final float dealtDamage, final boolean isBlocked, + float $$5, boolean wasHurt ) { if (this.attackImpl$actuallyHurtCancelled || damageTaken <= this.lastHurt) { this.invulnerableTime = this.attackImpl$InvulnerableTime; @@ -189,15 +189,10 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen * After calling #actuallyHurt, if cancelled return early * Also reset values */ - @Inject(method = "hurt", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, + @Inject(method = "hurtServer",cancellable = true, at = @At(value = "INVOKE", shift = At.Shift.AFTER, ordinal = 1, - target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/world/damagesource/DamageSource;F)V")) - private void attackImpl$afterActuallyHurt2(final DamageSource $$0, - final float damageTaken, - final CallbackInfoReturnable cir, - final float dealtDamage, - final boolean isBlocked - ) { + target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V")) + private void attackImpl$afterActuallyHurt2(ServerLevel $$0, DamageSource $$1, float $$2, CallbackInfoReturnable cir) { if (this.attackImpl$actuallyHurtCancelled) { this.invulnerableTime = this.attackImpl$InvulnerableTime; cir.setReturnValue(false); @@ -208,10 +203,10 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Set final damage after #actuallyHurt and lastHurt has been set. */ - @ModifyVariable(method = "hurt", argsOnly = true, + @ModifyVariable(method = "hurtServer", argsOnly = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/damagesource/DamageSource;getEntity()Lnet/minecraft/world/entity/Entity;"), slice = @Slice( - from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/world/damagesource/DamageSource;F)V"), + from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;actuallyHurt(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V"), to = @At(value = "INVOKE", target = "Lnet/minecraft/world/damagesource/DamageSource;getEntity()Lnet/minecraft/world/entity/Entity;"))) private float attackImpl$modifyDamageTaken(float damageTaken) { return this.attackImpl$actuallyHurtFinalDamage; @@ -220,7 +215,7 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen /** * Sets blocked damage after #actuallyHurt */ - @ModifyVariable(method = "hurt", ordinal = 2, + @ModifyVariable(method = "hurtServer", ordinal = 2, at = @At(value = "INVOKE", target = "Lnet/minecraft/advancements/critereon/EntityHurtPlayerTrigger;trigger(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/damagesource/DamageSource;FFZ)V", shift = At.Shift.AFTER)) @@ -228,14 +223,14 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen return this.attackImpl$actuallyHurtBlockedDamage; } - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;playHurtSound(Lnet/minecraft/world/damagesource/DamageSource;)V")) + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;playHurtSound(Lnet/minecraft/world/damagesource/DamageSource;)V")) private void attackImpl$onHurtSound(final LivingEntity instance, final DamageSource $$0) { if (this.bridge$vanishState().createsSounds()) { this.shadow$playHurtSound($$0); } } - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;makeSound(Lnet/minecraft/sounds/SoundEvent;)V")) + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;makeSound(Lnet/minecraft/sounds/SoundEvent;)V")) private void attackImpl$onMakeSound(final LivingEntity instance, final SoundEvent $$0) { if (this.bridge$vanishState().createsSounds()) { instance.makeSound($$0); @@ -243,7 +238,8 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen } @Inject(method = "actuallyHurt", at = @At(value = "INVOKE",target = "Lnet/minecraft/world/entity/LivingEntity;getDamageAfterArmorAbsorb(Lnet/minecraft/world/damagesource/DamageSource;F)F")) - public void attackImpl$startActuallyHurt(DamageSource damageSource, float originalDamage, CallbackInfo ci) { + public void attackImpl$startActuallyHurt(final ServerLevel level, final DamageSource damageSource, + final float originalDamage, final CallbackInfo ci) { // TODO check for direct call? this.attackImpl$actuallyHurt = new DamageEventUtil.ActuallyHurt((LivingEntity) (Object) this, new ArrayList<>(), damageSource, originalDamage); } @@ -388,7 +384,7 @@ public abstract class LivingEntityMixin_Attack_Impl extends EntityMixin implemen * also reverts {@link #attackImpl$beforeActuallyHurt} */ @Inject(method = "actuallyHurt", at = @At("RETURN")) - public void attackImpl$cleanupActuallyHurt(final DamageSource $$0, final float $$1, final CallbackInfo ci) { + public void attackImpl$cleanupActuallyHurt(final ServerLevel level, final DamageSource $$0, final float $$1, final CallbackInfo ci) { this.attackImpl$handlePostDamage(); this.attackImpl$actuallyHurt = null; this.attackImpl$actuallyHurtResult = null; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java index 1e00bcd8358..530c2f8de59 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java @@ -67,7 +67,6 @@ public abstract class MobMixin extends LivingEntityMixin { @Shadow protected abstract void shadow$registerGoals(); // @formatter:on - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Mob;registerGoals()V")) private void impl$registerGoals(final Mob this$0) { this.impl$setupGoalSelectors(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin_Attack_Impl.java index 4142c751fad..9de678c164e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin_Attack_Impl.java @@ -50,8 +50,8 @@ public abstract class MobMixin_Attack_Impl extends LivingEntityMixin_Attack_Impl } @Redirect(method = "doHurtTarget", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) - private boolean attackImpl$onCanGrief(final net.minecraft.world.entity.Entity targetEntity, final DamageSource damageSource, final float mcFinalDamage) { + target = "Lnet/minecraft/world/entity/Entity;hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + private boolean attackImpl$onCanGrief(final net.minecraft.world.entity.Entity targetEntity, final ServerLevel level, final DamageSource damageSource, final float mcFinalDamage) { final var thisEntity = (Mob) (Object) this; float knockbackModifier = this.shadow$getKnockback(targetEntity, damageSource); @@ -65,7 +65,7 @@ public abstract class MobMixin_Attack_Impl extends LivingEntityMixin_Attack_Impl final var event = DamageEventUtil.callMobAttackEvent(attack, knockbackModifier); this.impl$knockbackModifier = event.knockbackModifier(); - return targetEntity.hurt(damageSource, (float) event.finalOutputDamage()); + return targetEntity.hurtServer(level, damageSource, (float) event.finalOutputDamage()); } @Redirect(method = "doHurtTarget", at = @At(value = "INVOKE", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/PortalProcessorMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/PortalProcessorMixin.java index a9050b50ec6..c04a1bdf73d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/PortalProcessorMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/PortalProcessorMixin.java @@ -29,10 +29,11 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.PortalProcessor; +import net.minecraft.world.entity.Relative; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Portal; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.SpongeEventFactory; @@ -52,6 +53,8 @@ import org.spongepowered.common.util.VecHelper; import org.spongepowered.math.vector.Vector3d; +import java.util.EnumSet; + @Mixin(PortalProcessor.class) public abstract class PortalProcessorMixin implements PortalProcessorBridge { // @formatter:off @@ -73,8 +76,8 @@ public abstract class PortalProcessorMixin implements PortalProcessorBridge { @Redirect(method = "getPortalDestination", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/Portal;getPortalDestination(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/portal/DimensionTransition;")) - public DimensionTransition impl$onGetPortalDestination(final Portal instance, final ServerLevel serverLevel, final Entity entity, final BlockPos blockPos) { + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/Portal;getPortalDestination(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/portal/TeleportTransition;")) + public TeleportTransition impl$onGetPortalDestination(final Portal instance, final ServerLevel serverLevel, final Entity entity, final BlockPos blockPos) { final var spongEntity = (org.spongepowered.api.entity.Entity) entity; var finalPortal = instance; @@ -128,10 +131,10 @@ public abstract class PortalProcessorMixin implements PortalProcessorBridge { spongEntity.position(), spongEntity.rotation(), (ServerWorld) transition.newLevel(), - VecHelper.toVector3d(transition.pos()), - VecHelper.toVector3d(transition.pos()), + VecHelper.toVector3d(transition.position()), + VecHelper.toVector3d(transition.position()), preWorldChangeEvent.destinationWorld(), // with modified preWorldChangeEvent destination world - VecHelper.toVector3d(transition.speed()), + VecHelper.toVector3d(transition.deltaMovement()), (PortalLogic) finalPortal); if (SpongeCommon.post(tpEvent)) { wrapperTransaction.markCancelled(); @@ -139,13 +142,15 @@ public abstract class PortalProcessorMixin implements PortalProcessorBridge { } // modify transition after event - return new DimensionTransition((ServerLevel) tpEvent.destinationWorld(), + return new TeleportTransition((ServerLevel) tpEvent.destinationWorld(), VecHelper.toVanillaVector3d(tpEvent.destinationPosition()), VecHelper.toVanillaVector3d(tpEvent.exitSpeed()), (float) tpEvent.toRotation().y(), (float) tpEvent.toRotation().x(), transition.missingRespawnBlock(), - transition.postDimensionTransition()); + transition.asPassenger(), + EnumSet.noneOf(Relative.class), + transition.postTeleportTransition()); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ai/sensing/SensorMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ai/sensing/SensorMixin.java index dbcf9ecd5af..8c032e63cea 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ai/sensing/SensorMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/ai/sensing/SensorMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.ai.sensing; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.sensing.Sensor; import org.spongepowered.asm.mixin.Mixin; @@ -40,12 +41,12 @@ public class SensorMixin { "isEntityAttackable", "isEntityAttackableIgnoringLineOfSight" }, at = @At("HEAD"), cancellable = true) - private static void impl$cancelForVanishedEntities(LivingEntity $$0, LivingEntity $$1, CallbackInfoReturnable cir) { - final var vs = ((VanishableBridge) $$0).bridge$vanishState(); + private static void impl$cancelForVanishedEntities(ServerLevel $$0, LivingEntity $$1, LivingEntity $$2, CallbackInfoReturnable cir) { + final var vs = ((VanishableBridge) $$1).bridge$vanishState(); if (vs.invisible() && vs.untargetable()) { cir.setReturnValue(false); } - final var vsOther = ((VanishableBridge) $$1).bridge$vanishState(); + final var vsOther = ((VanishableBridge) $$2).bridge$vanishState(); if (vsOther.invisible() && vsOther.untargetable()) { cir.setReturnValue(false); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/SnowGolemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/SnowGolemMixin.java index 0bd8e652526..2cd0432ea5e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/SnowGolemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/SnowGolemMixin.java @@ -28,19 +28,16 @@ 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.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.mixin.core.world.entity.MobMixin; @Mixin(SnowGolem.class) public abstract class SnowGolemMixin extends MobMixin { - @Inject(method = "aiStep()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Mth;floor(D)I", ordinal = 3), - cancellable = true) - private void impl$onCanGrief(CallbackInfo ci) { - if (!this.shadow$level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) || !((GrieferBridge) this).bridge$canGrief()) { - ci.cancel(); - } + @Redirect(method = "aiStep()V", at = @At( + value = "INVOKE", target = "Lnet/minecraft/world/level/GameRules;getBoolean(Lnet/minecraft/world/level/GameRules$Key;)Z")) + private boolean impl$checkCanGrief(final GameRules gameRules, final GameRules.Key key) { + return gameRules.getBoolean(key) && ((GrieferBridge) this).bridge$canGrief(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EndCrystalMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EndCrystalMixin.java index 358c4ebdd50..353999a85f9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EndCrystalMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EndCrystalMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.boss.enderdragon; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; @@ -31,9 +32,6 @@ import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.event.CauseStackManager; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -41,7 +39,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.world.entity.boss.enderdragon.EndCrystalBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.mixin.core.world.entity.EntityMixin; import org.spongepowered.common.util.Constants; @@ -52,55 +49,50 @@ @Mixin(EndCrystal.class) public abstract class EndCrystalMixin extends EntityMixin implements ExplosiveBridge, EndCrystalBridge { - private int impl$explosionStrength = Constants.Entity.EnderCrystal.DEFAULT_EXPLOSION_STRENGTH; + private float impl$explosionRadius = Constants.Entity.EnderCrystal.DEFAULT_EXPLOSION_STRENGTH; // Explosive Impl @Override - public Optional bridge$getExplosionRadius() { - return Optional.of(this.impl$explosionStrength); + public Optional bridge$getExplosionRadius() { + return Optional.of(this.impl$explosionRadius); } @Override - public void bridge$setExplosionRadius(@Nullable final Integer radius) { - this.impl$explosionStrength = radius == null ? Constants.Entity.EnderCrystal.DEFAULT_EXPLOSION_STRENGTH : radius; + public void bridge$setExplosionRadius(final @Nullable Float radius) { + this.impl$explosionRadius = radius == null ? Constants.Entity.EnderCrystal.DEFAULT_EXPLOSION_STRENGTH : radius; } - @Redirect(method = "hurt", + @Redirect(method = "hurtServer", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;" + target = "Lnet/minecraft/server/level/ServerLevel;explode(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)V" ) ) - private net.minecraft.world.level.@Nullable Explosion impl$throwEventWithEntity(final net.minecraft.world.level.Level world, - final Entity entityIn, final DamageSource damageSource, final ExplosionDamageCalculator exDamageCalc, final double xIn, final double yIn, final double zIn, final float explosionRadius, - final boolean fire, final Level.ExplosionInteraction modeIn) { - // TODO fire? - // TODO smoking value correct? - return this.bridge$throwExplosionEventAndExplode(world, entityIn, xIn, yIn, zIn, modeIn.compareTo(Level.ExplosionInteraction.TNT) <= 0, damageSource); + private void impl$onHurtExplode( + final ServerLevel instance, final Entity entity, final DamageSource damageSource, + final ExplosionDamageCalculator explosionDamageCalculator, final double xIn, double yIn, double zIn, + float v, boolean b, Level.ExplosionInteraction explosionInteraction, final ServerLevel level, + final DamageSource source, final float amount) { + this.bridge$wrappedExplode(xIn, yIn, zIn, damageSource, source); } @Override - public net.minecraft.world.level.@Nullable Explosion bridge$throwExplosionEventAndExplode(final net.minecraft.world.level.Level world, - @Nullable final Entity nil, final double x, final double y, final double z, final boolean smoking, - @Nullable final DamageSource source) { + public void bridge$wrappedExplode(final double x, final double y, final double z, + @Nullable final DamageSource source, final DamageSource causeSource) { final CauseStackManager causeStackManager = PhaseTracker.getCauseStackManager(); try (final CauseStackManager.StackFrame frame = causeStackManager.pushCauseFrame()) { frame.pushCause(this); if (source != null) { - frame.pushCause(source); + frame.pushCause(causeSource); } - return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) world, x, y, z)) - .radius(this.impl$explosionStrength) - .shouldPlaySmoke(smoking)) - .orElse(null); + this.level().explode( (Entity) (Object) this, source, null, x, y, z, this.impl$explosionRadius, false, Level.ExplosionInteraction.BLOCK); } } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/boss/enderdragon/EndCrystal;remove(Lnet/minecraft/world/entity/Entity$RemovalReason;)V")) - private void attackImpl$onAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$onAttackEntityFrom(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EnderDragonMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EnderDragonMixin.java index 6c0da06f9dc..3661568aab3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EnderDragonMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/boss/enderdragon/EnderDragonMixin.java @@ -24,11 +24,11 @@ */ package org.spongepowered.common.mixin.core.world.entity.boss.enderdragon; +import net.minecraft.tags.TagKey; import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.entity.boss.enderdragon.phases.DragonHoverPhase; import net.minecraft.world.entity.boss.enderdragon.phases.DragonPhaseInstance; 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.phys.Vec3; import org.checkerframework.checker.nullness.qual.Nullable; @@ -53,23 +53,23 @@ public abstract class EnderDragonMixin extends MobMixin { method = "checkWalls", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;getBlock()Lnet/minecraft/world/level/block/Block;" + target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/tags/TagKey;)Z" ), slice = @Slice( from = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;getBlockState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState;" + value = "FIELD", + target = "Lnet/minecraft/world/level/GameRules;RULE_MOBGRIEFING:Lnet/minecraft/world/level/GameRules$Key;" ), to = @At( - value = "FIELD", - target = "Lnet/minecraft/world/level/material/Material;FIRE:Lnet/minecraft/world/level/material/Material;", + value = "INVOKE", + target = "Lnet/minecraft/server/level/ServerLevel;removeBlock(Lnet/minecraft/core/BlockPos;Z)Z", opcode = Opcodes.GETSTATIC ) ), require = 0 // Forge rewrites the material request to block.isAir ) - private Block impl$onCanGrief(final BlockState state) { - return ((GrieferBridge) this).bridge$canGrief() ? state.getBlock() : Blocks.AIR; + private boolean impl$onCanGrief(final BlockState state, final TagKey tag) { + return ((GrieferBridge) this).bridge$canGrief() && state.is(tag); } /** diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ArmorStandMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ArmorStandMixin.java index 9e419a6e1e2..d377bb6d48e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ArmorStandMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ArmorStandMixin.java @@ -75,20 +75,20 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { /** * BYPASSES_INVULNERABILITY */ - @Inject(method = "hurt", cancellable = true, + @Inject(method = "hurtServer", cancellable = true, slice = @Slice(from = @At(value = "FIELD", target = "Lnet/minecraft/tags/DamageTypeTags;BYPASSES_INVULNERABILITY:Lnet/minecraft/tags/TagKey;")), - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill()V", ordinal = 0)) - private void impl$fireDamageEventOutOfWorld(final DamageSource source, final float $$1, final CallbackInfoReturnable cir) { + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill(Lnet/minecraft/server/level/ServerLevel;)V", ordinal = 0)) + private void impl$fireDamageEventOutOfWorld(final ServerLevel level, final DamageSource source, final float $$1, final CallbackInfoReturnable cir) { this.impl$callDamageBeforeKill(source, cir); } /** * IS_EXPLOSION */ - @Inject(method = "hurt", cancellable = true, + @Inject(method = "hurtServer", cancellable = true, slice = @Slice(from = @At(value = "FIELD", target = "Lnet/minecraft/tags/DamageTypeTags;IS_EXPLOSION:Lnet/minecraft/tags/TagKey;")), at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;brokenByAnything(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;)V")) - private void impl$fireDamageEventExplosion(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void impl$fireDamageEventExplosion(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { this.impl$callDamageBeforeKill(source, cir); } @@ -97,7 +97,7 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { * IGNITES_ARMOR_STANDS + isOnFire * BURNS_ARMOR_STANDS + health > 0.5 */ - @Redirect(method = "hurt", + @Redirect(method = "hurtServer", slice = @Slice(from = @At(value = "FIELD", target = "Lnet/minecraft/tags/DamageTypeTags;IGNITES_ARMOR_STANDS:Lnet/minecraft/tags/TagKey;")), at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;causeDamage(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)V")) private void impl$fireDamageEventDamage(final ArmorStand self, final ServerLevel level, final DamageSource source, final float amount) { @@ -110,20 +110,20 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { /** * {@link DamageSource#isCreativePlayer()} */ - @Inject(method = "hurt", + @Inject(method = "hurtServer", slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/damagesource/DamageSource;isCreativePlayer()Z")), at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;playBrokenSound()V"), cancellable = true) - private void impl$fireDamageEventCreativePunch(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void impl$fireDamageEventCreativePunch(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { this.impl$callDamageBeforeKill(source, cir); } /** * {@link ArmorStand#lastHit} was not recently */ - @Inject(method = "hurt", cancellable = true, + @Inject(method = "hurtServer", cancellable = true, slice = @Slice(from = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;lastHit:J", opcode = Opcodes.GETFIELD)), at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;broadcastEntityEvent(Lnet/minecraft/world/entity/Entity;B)V")) - private void impl$fireDamageEventFirstPunch(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void impl$fireDamageEventFirstPunch(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { // While this doesn't technically "damage" the armor stand, it feels like damage in other respects, so fire an event. var event = DamageEventUtil.callSimpleDamageEntityEvent(source, (ArmorStand) (Object) this, 0); if (event.isCancelled()) { @@ -131,9 +131,9 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { } } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;brokenByPlayer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;)V")) - private void impl$beforeBrokenByPlayer(final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { + private void impl$beforeBrokenByPlayer(final ServerLevel level, final DamageSource $$0, final float $$1, final CallbackInfoReturnable cir) { if (ShouldFire.DESTRUCT_ENTITY_EVENT && !((LevelBridge) this.shadow$level()).bridge$isFake()) { final var event = SpongeCommonEventFactory.callDestructEntityEventDeath((ArmorStand) (Object) this, null); if (event.isCancelled()) { @@ -143,7 +143,7 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { } } - @Redirect(method = "hurt", at = @At(value = "INVOKE", + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;brokenByPlayer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;)V")) public void impl$onBrokenByPlayer(final ArmorStand instance, final ServerLevel $$0, final DamageSource $$1) { @@ -155,9 +155,9 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { /** * {@link ArmorStand#lastHit} was recently */ - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;brokenByPlayer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;)V")) - private void impl$fireDamageEventSecondPunch(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void impl$fireDamageEventSecondPunch(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { this.impl$callDamageBeforeKill(source, cir); } @@ -168,8 +168,8 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { * * @param target the killed stand */ - @Redirect(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill()V")) - private void impl$actuallyKill(final ArmorStand target) { + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill(Lnet/minecraft/server/level/ServerLevel;)V")) + private void impl$actuallyKill(final ArmorStand target, final ServerLevel level) { target.remove(RemovalReason.KILLED); target.gameEvent(GameEvent.ENTITY_DIE); } @@ -181,8 +181,8 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { * * @param target the killed stand */ - @Redirect(method = "causeDamage", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill()V")) - private void impl$actuallyKill2(final ArmorStand target) { + @Redirect(method = "causeDamage", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/decoration/ArmorStand;kill(Lnet/minecraft/server/level/ServerLevel;)V")) + private void impl$actuallyKill2(final ArmorStand target, final ServerLevel level) { target.remove(RemovalReason.KILLED); target.gameEvent(GameEvent.ENTITY_DIE); } @@ -197,7 +197,7 @@ public abstract class ArmorStandMixin extends LivingEntityMixin { * This needs to be reimplemented in {@link #impl$actuallyKill}! */ @Overwrite - public void kill() { - super.shadow$kill(); + public void kill(final ServerLevel level) { + super.shadow$kill(level); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/BlockAttachedEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/BlockAttachedEntityMixin.java index 03a8ad46608..763e0ad5bc9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/BlockAttachedEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/BlockAttachedEntityMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.decoration; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.decoration.BlockAttachedEntity; @@ -54,9 +55,9 @@ public abstract class BlockAttachedEntityMixin extends EntityMixin { return this.shadow$survives() && !this.impl$ignorePhysics; } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/decoration/BlockAttachedEntity;kill()V")) - private void attackImpl$postEventOnAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/decoration/BlockAttachedEntity;kill(Lnet/minecraft/server/level/ServerLevel;)V")) + private void attackImpl$postEventOnAttackEntityFrom(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ItemFrameMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ItemFrameMixin.java index f84c4d54c9b..c09f61c3b90 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ItemFrameMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/decoration/ItemFrameMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.decoration; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import org.spongepowered.asm.mixin.Mixin; @@ -35,9 +36,10 @@ @Mixin(net.minecraft.world.entity.decoration.ItemFrame.class) public abstract class ItemFrameMixin extends HangingEntityMixin { - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/decoration/ItemFrame;dropItem(Lnet/minecraft/world/entity/Entity;Z)V")) - private void attackImpl$onAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/decoration/ItemFrame;dropItem(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/Entity;Z)V")) + private void attackImpl$onAttackEntityFrom(final ServerLevel level, final DamageSource source, + final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/ItemEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/ItemEntityMixin.java index e80443443f2..0dd2ca7b6ad 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/ItemEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/ItemEntityMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.item; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.item.ItemEntity; @@ -144,9 +145,10 @@ public abstract class ItemEntityMixin extends EntityMixin implements ItemEntityB } } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/item/ItemEntity;markHurt()V")) - private void attackImpl$onAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$onAttackEntityFrom(final ServerLevel level, final DamageSource source, + final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/PrimedTntMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/PrimedTntMixin.java index 0a0552dc566..5c546a72d7a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/PrimedTntMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/item/PrimedTntMixin.java @@ -24,30 +24,18 @@ */ package org.spongepowered.common.mixin.core.world.entity.item; -import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.PrimedTnt; -import net.minecraft.world.level.Explosion.BlockInteraction; -import net.minecraft.world.level.ExplosionDamageCalculator; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.entity.explosive.fused.PrimedTNT; import org.spongepowered.api.event.CauseStackManager; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.explosives.FusedExplosiveBridge; import org.spongepowered.common.bridge.world.entity.item.PrimedTntBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.mixin.core.world.entity.EntityMixin; import org.spongepowered.common.util.Constants; @@ -60,10 +48,11 @@ public abstract class PrimedTntMixin extends EntityMixin implements PrimedTntBri // @formatter:off @Shadow public abstract int shadow$getFuse(); @Shadow public abstract void shadow$setFuse(int var1); + @Shadow private float explosionPower; + // @formatter:on @Nullable private LivingEntity impl$detonator; - private int bridge$explosionRadius = Constants.Entity.PrimedTNT.DEFAULT_EXPLOSION_RADIUS; private int bridge$fuseDuration = Constants.Entity.PrimedTNT.DEFAULT_FUSE_DURATION; private boolean impl$postPrimeTriggered = false; @@ -78,13 +67,13 @@ public abstract class PrimedTntMixin extends EntityMixin implements PrimedTntBri } @Override - public Optional bridge$getExplosionRadius() { - return Optional.of(this.bridge$explosionRadius); + public Optional bridge$getExplosionRadius() { + return Optional.of(this.explosionPower); } @Override - public void bridge$setExplosionRadius(@Nullable final Integer radius) { - this.bridge$explosionRadius = radius == null ? Constants.Entity.PrimedTNT.DEFAULT_EXPLOSION_RADIUS : radius; + public void bridge$setExplosionRadius(final @Nullable Float radius) { + this.explosionPower = radius == null ? Constants.Entity.PrimedTNT.DEFAULT_EXPLOSION_RADIUS : radius; } @Override @@ -113,34 +102,6 @@ public abstract class PrimedTntMixin extends EntityMixin implements PrimedTntBri this.shadow$setFuse(fuseTicks); } - @Redirect( - method = "explode", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;" - ) - ) - private net.minecraft.world.level.@Nullable Explosion impl$useSpongeExplosion(final Level world, - final Entity entityIn, - final DamageSource damageSource, - final ExplosionDamageCalculator explosionDamageCalculator, - final double xIn, final double yIn, final double zIn, final - float explosionRadius, - final boolean falseValue, - final Level.ExplosionInteraction modeIn) { - return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) world, xIn, yIn, zIn)) - .sourceExplosive((PrimedTNT) this) - .radius(this.bridge$explosionRadius) - .shouldPlaySmoke(modeIn.ordinal() > BlockInteraction.KEEP.ordinal()) - .shouldBreakBlocks(modeIn.ordinal() > BlockInteraction.KEEP.ordinal())) - .orElseGet(() -> { - ((PrimedTNT) this).offer(Keys.IS_PRIMED, false); - return null; - }); - } - - @Inject(method = "tick()V", at = @At("RETURN")) private void impl$updateTNTPushPrime(final CallbackInfo ci) { if (!this.impl$postPrimeTriggered && !this.shadow$level().isClientSide) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java index d836d7e70dc..3eacbbbc617 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java @@ -24,16 +24,10 @@ */ package org.spongepowered.common.mixin.core.world.entity.monster; -import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.entity.living.monster.Creeper; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -42,8 +36,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.explosives.FusedExplosiveBridge; -import org.spongepowered.common.bridge.world.entity.GrieferBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.util.Constants; import java.util.Optional; @@ -68,13 +60,13 @@ public abstract class CreeperMixin extends MonsterMixin implements FusedExplosiv // FusedExplosive Impl @Override - public Optional bridge$getExplosionRadius() { - return Optional.of(this.explosionRadius); + public Optional bridge$getExplosionRadius() { + return Optional.of((float) this.explosionRadius); } @Override - public void bridge$setExplosionRadius(@Nullable final Integer radius) { - this.explosionRadius = radius == null ? Constants.Entity.Creeper.DEFAULT_EXPLOSION_RADIUS : radius; + public void bridge$setExplosionRadius(final @Nullable Float radius) { + this.explosionRadius = radius == null ? Constants.Entity.Creeper.DEFAULT_EXPLOSION_RADIUS : radius.intValue(); } @Override @@ -140,25 +132,16 @@ public abstract class CreeperMixin extends MonsterMixin implements FusedExplosiv } } - @Redirect(method = "explodeCreeper", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;")) - private net.minecraft.world.level.@Nullable Explosion impl$useSpongeExplosion(final net.minecraft.world.level.Level world, final Entity self, final double x, - final double y, final double z, final float strength, final Level.ExplosionInteraction mode) { - return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) world, x, y, z)) - .sourceExplosive(((Creeper) this)) - .radius(strength) - .shouldPlaySmoke(mode != Level.ExplosionInteraction.NONE) - .shouldBreakBlocks(mode != Level.ExplosionInteraction.NONE && ((GrieferBridge) this).bridge$canGrief())) - .orElseGet(() -> { - this.impl$detonationCancelled = true; - return null; - }); + @Override + public void bridge$cancelExplosion() { + this.impl$detonationCancelled = true; } @Inject(method = "explodeCreeper", at = @At("RETURN")) private void impl$postExplode(final CallbackInfo ci) { if (this.impl$detonationCancelled) { this.impl$detonationCancelled = this.dead = false; + this.shadow$unsetRemoved(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java index 59860310fb6..976768bf6d5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java @@ -102,6 +102,7 @@ public abstract class PlayerMixin extends LivingEntityMixin implements PlayerBri @Shadow @Final public InventoryMenu inventoryMenu; @Shadow @Final private GameProfile gameProfile; @Shadow public abstract boolean shadow$isSpectator(); + @Shadow protected abstract int shadow$getPermissionLevel(); @Shadow public abstract int shadow$getXpNeededForNextLevel(); @Shadow @Nullable public abstract ItemEntity shadow$drop(final ItemStack droppedItem, final boolean dropAround, final boolean traceItem); @Shadow public abstract FoodData shadow$getFoodData(); @@ -227,7 +228,6 @@ public abstract class PlayerMixin extends LivingEntityMixin implements PlayerBri method = { "playSound(Lnet/minecraft/sounds/SoundEvent;FF)V", "giveExperienceLevels(I)V", - "eat(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/item/ItemStack;" }, at = @At( value = "INVOKE", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java index cb4c42b6ce1..07a49e1163f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.player; +import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; @@ -171,7 +172,7 @@ public abstract class PlayerMixin_Attack_Impl extends LivingEntityMixin_Attack_I @Redirect(method = "attack", slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;getDeltaMovement()Lnet/minecraft/world/phys/Vec3;"), to = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;getKnockback(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;)F")), - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurtOrSimulate(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) public boolean attackImpl$onHurt(final Entity targetEntity, final DamageSource damageSource, final float mcDamage) { float knockbackModifier = this.shadow$getKnockback(targetEntity, damageSource) + (this.attackImpl$isStrongSprintAttack ? 1.0F : 0.0F); @@ -190,14 +191,18 @@ public abstract class PlayerMixin_Attack_Impl extends LivingEntityMixin_Attack_I this.impl$playAttackSound((Player) (Object) this, SoundEvents.PLAYER_ATTACK_KNOCKBACK); } - return targetEntity.hurt(damageSource, (float) this.attackImpl$attackEvent.finalOutputDamage()); + if (targetEntity.level() instanceof ServerLevel sl) { + return targetEntity.hurtServer(sl, damageSource, (float) this.attackImpl$attackEvent.finalOutputDamage()); + } + + return targetEntity.hurtClient(damageSource); } /** * Set enchantment damage with value from event */ @ModifyVariable(method = "attack", ordinal = 1, - slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurtOrSimulate(Lnet/minecraft/world/damagesource/DamageSource;F)Z"), to = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;knockback(DDD)V", ordinal = 0)), at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;getKnockback(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;)F")) public float attackImpl$enchentmentDamageFromEvent(final float enchDmg) { @@ -271,7 +276,7 @@ public abstract class PlayerMixin_Attack_Impl extends LivingEntityMixin_Attack_I */ @Redirect(method = "attack", slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;getEntitiesOfClass(Ljava/lang/Class;Lnet/minecraft/world/phys/AABB;)Ljava/util/List;"), - to = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")), + to = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)V")), at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;knockback(DDD)V")) public void attackImpl$modifyKnockback(final LivingEntity instance, final double $$0, final double $$1, final double $$2) { instance.knockback($$0 * this.attackImpl$attackEvent.knockbackModifier(), $$1, $$2); @@ -293,7 +298,7 @@ public abstract class PlayerMixin_Attack_Impl extends LivingEntityMixin_Attack_I } @Inject(method = "actuallyHurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;getDamageAfterArmorAbsorb(Lnet/minecraft/world/damagesource/DamageSource;F)F")) - public void attackImpl$startActuallyHurt(DamageSource damageSource, float originalDamage, CallbackInfo ci) { + public void attackImpl$startActuallyHurt(final ServerLevel level, DamageSource damageSource, float originalDamage, CallbackInfo ci) { // TODO check for direct call? this.attackImpl$actuallyHurt = new DamageEventUtil.ActuallyHurt((LivingEntity) (Object) this, new ArrayList<>(), damageSource, originalDamage); } @@ -317,7 +322,7 @@ public abstract class PlayerMixin_Attack_Impl extends LivingEntityMixin_Attack_I * Cleanup */ @Inject(method = "actuallyHurt", at = @At("RETURN")) - public void attackImpl$afterActuallyHurt(final DamageSource $$0, final float $$1, final CallbackInfo ci) { + public void attackImpl$afterActuallyHurt(final ServerLevel level, final DamageSource $$0, final float $$1, final CallbackInfo ci) { this.attackImpl$handlePostDamage(); this.attackImpl$actuallyHurt = null; this.attackImpl$actuallyHurtResult = null; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractArrowMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractArrowMixin.java index 6f91c80b19a..7dde827bfc2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractArrowMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractArrowMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.projectile; +import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.LivingEntity; @@ -50,7 +51,6 @@ public abstract class AbstractArrowMixin extends ProjectileMixin implements Abst // @formatter:off @Shadow private int life; - @Shadow protected boolean inGround; @Shadow public int shakeTime; @Shadow public AbstractArrow.Pickup pickup; @Shadow @Nullable private BlockState lastState; @@ -59,9 +59,10 @@ public abstract class AbstractArrowMixin extends ProjectileMixin implements Abst @Shadow public abstract void shadow$setPierceLevel(byte level); @Shadow protected abstract ItemStack shadow$getPickupItem(); @Shadow protected abstract void resetPiercedEntities(); - + @Shadow protected abstract void shadow$setInGround(boolean $$0); // @formatter:on + @Nullable private Double impl$customKnockback; // Not all ProjectileSources are entities (e.g. BlockProjectileSource). @@ -91,14 +92,12 @@ private void onProjectileHit(final BlockHitResult hitResult, final CallbackInfo this.impl$getProjectileSource(), hitResult)) { this.shadow$playSound(SoundEvents.ARROW_HIT, 1.0F, 1.2F / (this.random.nextFloat() * 0.2F + 0.9F)); // Make it almost look like it collided with something - final BlockHitResult blockraytraceresult = (BlockHitResult)hitResult; - final BlockState blockstate = this.shadow$level().getBlockState(blockraytraceresult.getBlockPos()); - this.lastState = blockstate; - final Vec3 vec3d = blockraytraceresult.getLocation().subtract(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ()); + this.lastState = this.shadow$level().getBlockState(hitResult.getBlockPos()); + final Vec3 vec3d = hitResult.getLocation().subtract(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ()); this.shadow$setDeltaMovement(vec3d); final Vec3 vec3d1 = vec3d.normalize().scale(0.05F); this.shadow$setPos(this.shadow$getX() - vec3d1.x, this.shadow$getY() - vec3d1.y, this.shadow$getZ() - vec3d1.z); - this.inGround = true; + this.shadow$setInGround(true); this.shakeTime = 7; this.shadow$setCritArrow(false); this.shadow$setPierceLevel((byte)0); @@ -138,7 +137,7 @@ private void onProjectileHit(final EntityHitResult hitResult, final CallbackInfo this.life = 0; if (!this.shadow$level().isClientSide && this.shadow$getDeltaMovement().lengthSqr() < 1.0E-7D) { if (this.pickup == AbstractArrow.Pickup.ALLOWED) { - this.shadow$spawnAtLocation(this.shadow$getPickupItem(), 0.1F); + this.shadow$spawnAtLocation((ServerLevel) this.shadow$level(), this.shadow$getPickupItem(), 0.1F); } this.shadow$discard(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FireworkRocketEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FireworkRocketEntityMixin.java index 9fb3c57f3c8..b265059141c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FireworkRocketEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FireworkRocketEntityMixin.java @@ -24,13 +24,15 @@ */ package org.spongepowered.common.mixin.core.world.entity.projectile; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.projectile.explosive.FireworkRocket; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; +import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -40,7 +42,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.explosives.FusedExplosiveBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; @@ -54,7 +55,7 @@ public abstract class FireworkRocketEntityMixin extends ProjectileMixin implemen @Shadow private int lifetime; // @formatter:on - private int impl$explosionRadius = Constants.Entity.Firework.DEFAULT_EXPLOSION_RADIUS; + private float impl$explosionRadius = Constants.Entity.Firework.DEFAULT_EXPLOSION_RADIUS; @Override public boolean bridge$isPrimed() { @@ -83,35 +84,37 @@ public abstract class FireworkRocketEntityMixin extends ProjectileMixin implemen } @Override - public Optional bridge$getExplosionRadius() { + public Optional bridge$getExplosionRadius() { return Optional.of(this.impl$explosionRadius); } @Override - public void bridge$setExplosionRadius(final @Nullable Integer radius) { + public void bridge$setExplosionRadius(final @Nullable Float radius) { this.impl$explosionRadius = radius == null ? Constants.Entity.Firework.DEFAULT_EXPLOSION_RADIUS : radius; } - @Redirect(method = "explode()V", + @Redirect(method = "explode(Lnet/minecraft/server/level/ServerLevel;)V", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;broadcastEntityEvent(Lnet/minecraft/world/entity/Entity;B)V") + target = "Lnet/minecraft/server/level/ServerLevel;broadcastEntityEvent(Lnet/minecraft/world/entity/Entity;B)V") ) - private void impl$useSpongeExplosion(final Level world, final Entity self, final byte state) { - if (this.shadow$level().isClientSide) { - world.broadcastEntityEvent(self, state); - return; - } + private void impl$useSpongeExplosion(final ServerLevel world, final Entity self, final byte state) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { // Fireworks don't typically explode like other explosives, but we'll // post an event regardless and if the radius is zero the explosion // won't be triggered (the default behavior). frame.pushCause(this); frame.addContext(EventContextKeys.PROJECTILE_SOURCE, this.impl$getProjectileSource()); - SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() + final var explosionBuilder = Explosion.builder() .sourceExplosive(((FireworkRocket) this)) .location(((FireworkRocket) this).serverLocation()) - .radius(this.impl$explosionRadius)) - .ifPresent(explosion -> world.broadcastEntityEvent(self, state)); + .radius(this.impl$explosionRadius); + + final var detonateEvent = SpongeEventFactory.createDetonateExplosiveEvent(PhaseTracker.getCauseStackManager().currentCause(), + explosionBuilder, (FireworkRocket) this, explosionBuilder.build()); + if (Sponge.eventManager().post(detonateEvent)) { + return; + } + world.broadcastEntityEvent(self, state); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin_Shared.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin_Shared.java index 7ae55d5b57e..9f19f6ca213 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin_Shared.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin_Shared.java @@ -47,6 +47,6 @@ public abstract class FishingHookMixin_Shared extends ProjectileMixin { this.shadow$discard(); return ProjectileDeflection.NONE; } - return this.hitTargetOrDeflectSelf(hitResult); + return this.shadow$hitTargetOrDeflectSelf(hitResult); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/LargeFireballMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/LargeFireballMixin.java index ed564bd5957..8accd786833 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/LargeFireballMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/LargeFireballMixin.java @@ -30,20 +30,14 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.projectile.Projectile; -import org.spongepowered.api.entity.projectile.explosive.fireball.ExplosiveFireball; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; 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 org.spongepowered.common.bridge.explosives.ExplosiveBridge; -import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.bridge.world.entity.projectile.LargeFireballBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; @@ -53,54 +47,38 @@ public abstract class LargeFireballMixin extends AbstractHurtingProjectileMixin implements LargeFireballBridge, ExplosiveBridge { // @formatter:off - @Shadow public int explosionPower; + @Shadow private int explosionPower; // @formatter:on - /** - * @author gabizou April 13th, 2018 - * @reason Due to changes from Forge, we have to redirect osr modify the gamerule check, - * but since forge doesn't allow us to continue to check the gamerule method call here, - * we have to modify the arguments passed in (the two booleans). There may be a better way, - * which may include redirecting the world.newExplosion method call instead of modifyargs, - * but, it is what it is. - */ @Redirect(method = "onHit", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;" + target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)V" ) ) - public net.minecraft.world.level.@Nullable Explosion impl$throwExplosionEventAndExplode(final net.minecraft.world.level.Level worldObj, @Nullable final Entity nil, - final double x, final double y, final double z, final float strength, final boolean flaming, final Level.ExplosionInteraction mode) { - return this.bridge$throwExplosionEventAndExplode(worldObj, nil, x, y, z, strength, flaming, mode); + public void impl$onHitExplode(final Level world, final Entity thisEntity, + final double x, final double y, final double z, final float explosionRadius, final boolean causesFire, + final Level.ExplosionInteraction mode) { + this.bridge$wrappedExplode(x, y, z, explosionRadius, causesFire, mode); } @Override - public net.minecraft.world.level.Explosion bridge$throwExplosionEventAndExplode(net.minecraft.world.level.Level worldObj, @Nullable Entity nil, - double x, double y, double z, float strength, boolean flaming, Level.ExplosionInteraction mode) { - final boolean griefer = ((GrieferBridge) this).bridge$canGrief(); + public void bridge$wrappedExplode(final double x, final double y, final double z, + final float explosionRadius, final boolean causesFire, final Level.ExplosionInteraction mode) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ((Projectile) this).get(Keys.SHOOTER).ifPresent(shooter -> frame.addContext(EventContextKeys.PROJECTILE_SOURCE, shooter)); - final Optional ex = SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) worldObj, x, y, z)) - .sourceExplosive(((ExplosiveFireball) this)) - .radius(strength) - .canCauseFire(flaming && griefer) - .shouldPlaySmoke(mode != Level.ExplosionInteraction.NONE && griefer) - .shouldBreakBlocks(mode != Level.ExplosionInteraction.NONE && griefer)); - - return ex.orElse(null); + this.level().explode((LargeFireball) (Object) this, x, y, z, explosionRadius, causesFire, mode); } } @Override - public Optional bridge$getExplosionRadius() { - return Optional.of(this.explosionPower); + public Optional bridge$getExplosionRadius() { + return Optional.of((float) this.explosionPower); } @Override - public void bridge$setExplosionRadius(@Nullable final Integer radius) { - this.explosionPower = radius == null ? Constants.Entity.Fireball.DEFAULT_EXPLOSION_RADIUS : radius; + public void bridge$setExplosionRadius(final @Nullable Float radius) { + this.explosionPower = radius == null ? Constants.Entity.Fireball.DEFAULT_EXPLOSION_RADIUS : radius.intValue(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java index b56ca7cadc6..576f8154c5e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java @@ -53,7 +53,6 @@ public abstract class ProjectileMixin extends EntityMixin { @Shadow public abstract @Nullable Entity shadow$getOwner(); @Shadow protected abstract ProjectileDeflection shadow$hitTargetOrDeflectSelf(HitResult result); @Shadow protected abstract void onHit(HitResult result); - @Shadow protected abstract ProjectileDeflection hitTargetOrDeflectSelf(HitResult result); // @formatter:on private ProjectileSource impl$projectileSource = UnknownProjectileSource.UNKNOWN; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileUtilMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileUtilMixin.java index fefa12138c1..0e8674220a6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileUtilMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileUtilMixin.java @@ -70,7 +70,7 @@ public abstract class ProjectileUtilMixin { final Vec3 to = from.add(velocity); final Vec3 direction = from.subtract(to); - cir.setReturnValue(BlockHitResult.miss(to, Direction.getNearest(direction.x, direction.y, direction.z), BlockPos.containing(to))); + cir.setReturnValue(BlockHitResult.miss(to, Direction.getApproximateNearest(direction.x, direction.y, direction.z), BlockPos.containing(to))); } } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ShulkerBulletMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ShulkerBulletMixin.java index dc90ee08343..3efc4c01c22 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ShulkerBulletMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ShulkerBulletMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.projectile; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.ShulkerBullet; @@ -50,9 +51,9 @@ private void onBulletHitBlock(final HitResult result, final CallbackInfo ci) { } } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/ShulkerBullet;playSound(Lnet/minecraft/sounds/SoundEvent;FF)V")) - private void attackImpl$onAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$onAttackEntityFrom(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/SnowballMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/SnowballMixin.java index 5286cd530d4..00ec313c112 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/SnowballMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/SnowballMixin.java @@ -37,7 +37,7 @@ public abstract class SnowballMixin extends ThrowableProjectileMixin implements private boolean impl$damageSet = false; @ModifyArg(method = "onHitEntity", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)V")) private float impl$onAttackEntityFromUseCustomDamage(float damage) { return this.impl$damageSet ? (float) this.impl$damageAmount : damage; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEggMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEggMixin.java index e94c66d2615..40bebdc1d5b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEggMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEggMixin.java @@ -37,7 +37,7 @@ public abstract class ThrownEggMixin extends ThrowableProjectileMixin { @ModifyArg(method = "onHitEntity", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z") + target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)V") ) private float onAttackEntityFromUseDamage(final float damage) { return (float) this.impl$damageAmount; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEnderpearlMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEnderpearlMixin.java index 878e79e0b9e..04682400380 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEnderpearlMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrownEnderpearlMixin.java @@ -26,7 +26,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.ThrownEnderpearl; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.cause.entity.MovementTypes; @@ -44,21 +44,20 @@ public abstract class ThrownEnderpearlMixin extends ThrowableProjectileMixin { @ModifyArg(method = "onHit", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + target = "Lnet/minecraft/server/level/ServerPlayer;hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z")) private float impl$onAttackEntityFromWithDamage(final float damage) { return (float) this.impl$damageAmount; } @Redirect(method = "onHit", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;changeDimension(Lnet/minecraft/world/level/portal/DimensionTransition;)Lnet/minecraft/world/entity/Entity;") + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;teleport(Lnet/minecraft/world/level/portal/TeleportTransition;)Lnet/minecraft/world/entity/Entity;") ) - private Entity impl$callMoveEntityEventForThrower(final Entity instance, final DimensionTransition $$0) { - final Entity entity = this.shadow$getOwner(); + private Entity impl$callMoveEntityEventForThrower(final Entity instance, final TeleportTransition $$0) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { - frame.pushCause(entity); + frame.pushCause(instance); frame.addContext(EventContextKeys.MOVEMENT_TYPE, MovementTypes.ENDER_PEARL); - return instance.changeDimension($$0); + return instance.teleport($$0); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/WitherSkullMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/WitherSkullMixin.java index 2377fa1317f..c2661fc7fc3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/WitherSkullMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/WitherSkullMixin.java @@ -25,25 +25,20 @@ package org.spongepowered.common.mixin.core.world.entity.projectile; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.projectile.WitherSkull; import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.projectile.Projectile; -import org.spongepowered.api.entity.projectile.explosive.WitherSkull; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.accessor.world.entity.projectile.ProjectileAccessor; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; -import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.bridge.world.entity.projectile.WitherSkullBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; @@ -52,14 +47,14 @@ @Mixin(net.minecraft.world.entity.projectile.WitherSkull.class) public abstract class WitherSkullMixin extends AbstractHurtingProjectileMixin implements WitherSkullBridge, ExplosiveBridge { - private int impl$explosionRadius = Constants.Entity.WitherSkull.DEFAULT_EXPLOSION_RADIUS; + private float impl$explosionRadius = Constants.Entity.WitherSkull.DEFAULT_EXPLOSION_RADIUS; // TODO Key not implemented private float impl$damage = 0.0f; private boolean impl$damageSet = false; @ModifyArg(method = "onHitEntity", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z")) private float impl$onAttackEntityFrom(final float amount) { if (this.impl$damageSet) { return this.impl$damage; @@ -72,41 +67,31 @@ public abstract class WitherSkullMixin extends AbstractHurtingProjectileMixin im // Explosive Impl @Override - public Optional bridge$getExplosionRadius() { + public Optional bridge$getExplosionRadius() { return Optional.of(this.impl$explosionRadius); } @Override - public void bridge$setExplosionRadius(final @Nullable Integer explosionRadius) { + public void bridge$setExplosionRadius(final @Nullable Float explosionRadius) { this.impl$explosionRadius = explosionRadius == null ? Constants.Entity.WitherSkull.DEFAULT_EXPLOSION_RADIUS : explosionRadius; } @Redirect(method = "onHit", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;")) - public net.minecraft.world.level.@Nullable Explosion impl$CreateAndProcessExplosionEvent(final net.minecraft.world.level.Level worldObj, final Entity self, - final double x, final double y, final double z, final float strength, final boolean flaming, final Level.ExplosionInteraction mode) { - return this.bridge$throwExplosionEventAndExplosde(worldObj, self, x, y, z, strength, flaming, mode); + target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)V")) + public void impl$onHitExplode(final net.minecraft.world.level.Level worldObj, final Entity self, + final double x, final double y, final double z, final float explosionRadius, final boolean causesFire, final Level.ExplosionInteraction mode) { + this.bridge$wrappedExplode(x, y, z, explosionRadius, causesFire, mode); } @Override - public net.minecraft.world.level.Explosion bridge$throwExplosionEventAndExplosde( - final net.minecraft.world.level.Level worldObj, final Entity self, - final double x, final double y, final double z, final float strength, final boolean flaming, final Level.ExplosionInteraction mode) { - final boolean griefer = ((GrieferBridge) this).bridge$canGrief(); + public void bridge$wrappedExplode(final double x, final double y, final double z, final float explosionRadius, final boolean causesFire, final Level.ExplosionInteraction mode) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ((Projectile) this).get(Keys.SHOOTER).ifPresent(shooter -> { frame.addContext(EventContextKeys.PROJECTILE_SOURCE, shooter); frame.pushCause(shooter); }); - return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) worldObj, x, y, z)) - .sourceExplosive(((WitherSkull) this)) - .radius(this.impl$explosionRadius) - .canCauseFire(flaming) - .shouldPlaySmoke(mode != Level.ExplosionInteraction.NONE && griefer) - .shouldBreakBlocks(mode != Level.ExplosionInteraction.NONE && griefer)) - .orElse(null); + this.level().explode((WitherSkull) (Object) this, x, y, z, explosionRadius, causesFire, mode); } } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/BoatMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractBoatMixin.java similarity index 94% rename from src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/BoatMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractBoatMixin.java index a7403b7f54e..26b135e677a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/BoatMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractBoatMixin.java @@ -24,18 +24,18 @@ */ package org.spongepowered.common.mixin.core.world.entity.vehicle; -import net.minecraft.world.entity.vehicle.Boat; +import net.minecraft.world.entity.vehicle.AbstractBoat; import org.spongepowered.api.data.Keys; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.common.bridge.data.SpongeDataHolderBridge; -import org.spongepowered.common.bridge.world.entity.vehicle.BoatBridge; +import org.spongepowered.common.bridge.world.entity.vehicle.AbstractBoatBridge; import org.spongepowered.common.mixin.core.world.entity.EntityMixin; import org.spongepowered.common.util.Constants; -@Mixin(Boat.class) -public abstract class BoatMixin extends EntityMixin implements BoatBridge { +@Mixin(AbstractBoat.class) +public abstract class AbstractBoatMixin extends EntityMixin implements AbstractBoatBridge { private float impl$maxSpeed = Constants.Entity.Boat.DEFAULT_MAX_SPEED; private boolean impl$moveOnLand = Constants.Entity.Boat.MOVE_ON_LAND; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractMinecartMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractMinecartMixin.java index deb37eba7df..9844796031e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractMinecartMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/AbstractMinecartMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.vehicle; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.phys.Vec3; import org.spongepowered.api.data.Keys; @@ -54,7 +55,7 @@ public abstract class AbstractMinecartMixin extends VehicleEntityMixin implement * @reason Use our custom maximum speed for the Minecart. */ @Overwrite - protected double getMaxSpeed() { + protected double getMaxSpeed(ServerLevel level) { return this.impl$maxSpeed; } @@ -88,15 +89,6 @@ protected double getMaxSpeed() { return vec3d.multiply(this.impl$airborneMod.x(), this.impl$airborneMod.y(), this.impl$airborneMod.z()); } - @Redirect(method = "applyNaturalSlowdown", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/vehicle/AbstractMinecart;isVehicle()Z" - ) - ) - private boolean impl$applyDragIfEmpty(final AbstractMinecart self) { - return !this.impl$slowWhenEmpty || this.shadow$isVehicle(); - } - @Override public double bridge$getMaxSpeed() { return this.impl$maxSpeed; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartFurnaceMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartFurnaceMixin.java index a2c83ce6104..69ce2149a1a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartFurnaceMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartFurnaceMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.vehicle; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.vehicle.MinecartFurnace; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -47,9 +48,9 @@ private void onInit(CallbackInfo ci) { */ @Override @Overwrite - protected double getMaxSpeed() { + protected double getMaxSpeed(ServerLevel level) { // Return our custom value from EntityMinecart - return super.getMaxSpeed(); + return super.getMaxSpeed(level); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartTNTMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartTNTMixin.java index 3ee93ff1703..567b00b895e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartTNTMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/MinecartTNTMixin.java @@ -24,28 +24,22 @@ */ package org.spongepowered.common.mixin.core.world.entity.vehicle; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.vehicle.MinecartTNT; -import net.minecraft.world.level.ExplosionDamageCalculator; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Keys; -import org.spongepowered.api.entity.vehicle.minecart.TNTMinecart; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.explosives.FusedExplosiveBridge; import org.spongepowered.common.bridge.world.level.LevelBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.DamageEventUtil; @@ -61,18 +55,18 @@ public abstract class MinecartTNTMixin extends AbstractMinecartMixin implements @Shadow public abstract void shadow$primeFuse(); // @formatter:on - @Nullable private Integer impl$explosionRadius = null; + @Nullable private Float impl$explosionRadius = null; // override for fixed radius private int impl$fuseDuration = Constants.Entity.Minecart.DEFAULT_FUSE_DURATION; private boolean impl$detonationCancelled; @Nullable private Object impl$primeCause; @Override - public Optional bridge$getExplosionRadius() { + public Optional bridge$getExplosionRadius() { return Optional.ofNullable(this.impl$explosionRadius); } @Override - public void bridge$setExplosionRadius(final @Nullable Integer radius) { + public void bridge$setExplosionRadius(final @Nullable Float radius) { this.impl$explosionRadius = radius; } @@ -105,8 +99,9 @@ public abstract class MinecartTNTMixin extends AbstractMinecartMixin implements } - @Inject(method = "hurt", at = @At("HEAD")) - private void impl$onAttackSetPrimeCause(final DamageSource damageSource, final float amount, final CallbackInfoReturnable ci) { + @Inject(method = "hurtServer", at = @At("HEAD")) + private void impl$onAttackSetPrimeCause(final ServerLevel level, final DamageSource damageSource, + final float amount, final CallbackInfoReturnable ci) { this.impl$primeCause = damageSource; } @@ -140,28 +135,9 @@ public abstract class MinecartTNTMixin extends AbstractMinecartMixin implements } } - @Redirect( - method = "explode(Lnet/minecraft/world/damagesource/DamageSource;D)V", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Level$ExplosionInteraction;)Lnet/minecraft/world/level/Explosion;" - ) - ) - private net.minecraft.world.level.@Nullable Explosion impl$useSpongeExplosion(final net.minecraft.world.level.Level world, final Entity entityIn, - final DamageSource damageSource, final ExplosionDamageCalculator calculator, - final double xIn, final double yIn, final double zIn, final float explosionRadius, final boolean fire, final Level.ExplosionInteraction modeIn) { - // TODO ExplosionDamageCalculator & fire - return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() - .location(ServerLocation.of((ServerWorld) world, xIn, yIn, zIn)) - .sourceExplosive((TNTMinecart) this) - .radius(this.impl$explosionRadius != null ? this.impl$explosionRadius : explosionRadius) - .shouldPlaySmoke(modeIn.ordinal() > Level.ExplosionInteraction.NONE.ordinal()) - .shouldBreakBlocks(modeIn.ordinal() > Level.ExplosionInteraction.NONE.ordinal())) - .orElseGet(() -> { - this.impl$detonationCancelled = true; - return null; - } - ); + @Override + public void bridge$cancelExplosion() { + this.impl$detonationCancelled = true; } @Inject(method = "explode(Lnet/minecraft/world/damagesource/DamageSource;D)V", at = @At("RETURN")) @@ -172,9 +148,9 @@ public abstract class MinecartTNTMixin extends AbstractMinecartMixin implements } } - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/vehicle/MinecartTNT;explode(Lnet/minecraft/world/damagesource/DamageSource;D)V")) - private void attackImpl$postOnAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$postOnAttackEntityFrom(final ServerLevel level, final DamageSource source, final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/advancement/DisplayInfo_BuilderMixin_ItemStackLike.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/OldMinecartBehaviourMixin.java similarity index 65% rename from src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/advancement/DisplayInfo_BuilderMixin_ItemStackLike.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/OldMinecartBehaviourMixin.java index e752998a343..c08dbd2504b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/itemstacklike/advancement/DisplayInfo_BuilderMixin_ItemStackLike.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/OldMinecartBehaviourMixin.java @@ -22,21 +22,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.itemstacklike.advancement; +package org.spongepowered.common.mixin.core.world.entity.vehicle; -import org.spongepowered.api.advancement.DisplayInfo; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.minecraft.world.entity.vehicle.OldMinecartBehavior; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.bridge.world.entity.vehicle.AbstractMinecartBridge; -@Mixin(value = DisplayInfo.Builder.class, remap = false) -public interface DisplayInfo_BuilderMixin_ItemStackLike { +@Mixin(OldMinecartBehavior.class) +public abstract class OldMinecartBehaviourMixin { - default DisplayInfo.Builder icon(ItemStack itemStack) { - return ((DisplayInfo.Builder) this).icon(itemStack); + @Redirect(method = "getSlowdownFactor", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/vehicle/AbstractMinecart;isVehicle()Z")) + private boolean impl$applyDragIfEmpty(final AbstractMinecart minecart) { + return !((AbstractMinecartBridge) minecart).bridge$getSlowWhenEmpty() || minecart.isVehicle(); } - default DisplayInfo.Builder icon(ItemStackSnapshot itemStackSnapshot) { - return ((DisplayInfo.Builder) this).icon(itemStackSnapshot); - } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/VehicleEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/VehicleEntityMixin.java index 1fa0a765550..de39fb029c3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/VehicleEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/vehicle/VehicleEntityMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.entity.vehicle; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.vehicle.VehicleEntity; import org.spongepowered.asm.mixin.Mixin; @@ -36,9 +37,10 @@ @Mixin(VehicleEntity.class) public abstract class VehicleEntityMixin extends EntityMixin { - @Inject(method = "hurt", cancellable = true, at = @At(value = "INVOKE", + @Inject(method = "hurtServer", cancellable = true, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/vehicle/VehicleEntity;shouldSourceDestroy(Lnet/minecraft/world/damagesource/DamageSource;)Z")) - private void attackImpl$postOnAttackEntityFrom(final DamageSource source, final float amount, final CallbackInfoReturnable cir) { + private void attackImpl$postOnAttackEntityFrom(final ServerLevel level, final DamageSource source, + final float amount, final CallbackInfoReturnable cir) { if (DamageEventUtil.callOtherAttackEvent((net.minecraft.world.entity.Entity) (Object) this, source, amount).isCancelled()) { cir.setReturnValue(true); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java index 41a0d465762..f2f5b68172c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java @@ -91,18 +91,8 @@ public abstract class FoodDataMixin implements FoodDataBridge { this.saturationLevel = this.impl$fireEventAndGetValue(Keys.SATURATION, (double) this.saturationLevel, (double) value).floatValue(); } - @Redirect(method = "setExhaustion", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;exhaustionLevel:F", opcode = Opcodes.PUTFIELD)) - private void impl$setExhaustion(final FoodData self, final float value) { - this.exhaustionLevel = this.impl$fireEventAndGetValue(Keys.EXHAUSTION, (double) this.exhaustionLevel, (double) value).floatValue(); - } - @Redirect(method = "addExhaustion", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;exhaustionLevel:F", opcode = Opcodes.PUTFIELD)) - private void impl$addExhaustion(final FoodData self, final float value) { - this.exhaustionLevel = this.impl$fireEventAndGetValue(Keys.EXHAUSTION, (double) this.exhaustionLevel, (double) value).floatValue(); - } - - @Redirect(method = "tick", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;exhaustionLevel:F", opcode = Opcodes.PUTFIELD)) - private void impl$tickDrainExhaustion(final FoodData self, final float value) { + private void impl$setExhaustion(final FoodData self, final float value) { this.exhaustionLevel = this.impl$fireEventAndGetValue(Keys.EXHAUSTION, (double) this.exhaustionLevel, (double) value).floatValue(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/inventory/StonecutterMenuMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/inventory/StonecutterMenuMixin.java index be21fd71df1..6464a420aee 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/inventory/StonecutterMenuMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/inventory/StonecutterMenuMixin.java @@ -26,10 +26,10 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerListener; -import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.inventory.Slot; import net.minecraft.world.inventory.StonecutterMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.StonecutterRecipe; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -37,28 +37,33 @@ 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; import org.spongepowered.common.accessor.world.inventory.AbstractContainerMenuAccessor; import org.spongepowered.common.item.recipe.stonecutting.SpongeStonecuttingRecipe; -import java.util.List; +import java.util.Optional; @Mixin(StonecutterMenu.class) public abstract class StonecutterMenuMixin { // @formatter:off @Shadow @Final Slot resultSlot; - @Shadow private List recipes; - @Shadow @Final private DataSlot selectedRecipeIndex; // @formatter:on - @Inject(method = "setupResultSlot", at = @At(value = "RETURN")) - private void impl$updateRecipeResultSlot(final CallbackInfo ci) { - if (!this.recipes.isEmpty() && this.recipes.get(this.selectedRecipeIndex.get()) instanceof SpongeStonecuttingRecipe) { - // For SpongeStonecuttingRecipe resend the output slot in case the actual crafting result differs from the exemplary result - final ItemStack stack = this.resultSlot.getItem(); - for (final ContainerListener listener : ((AbstractContainerMenuAccessor) this).accessor$containerListeners()) { - listener.slotChanged((AbstractContainerMenu) (Object) this, 1, stack); - } - } + @Inject(method = "setupResultSlot", + at = @At(value = "INVOKE", target = "Ljava/util/Optional;ifPresentOrElse(Ljava/util/function/Consumer;Ljava/lang/Runnable;)V", shift = At.Shift.AFTER), + locals = LocalCapture.CAPTURE_FAILHARD + ) + private void impl$updateRecipeResultSlot( + final int $$0, final CallbackInfo ci, + final Optional> recipe) { + recipe.filter(e -> e.value() instanceof SpongeStonecuttingRecipe) + .ifPresent(e -> { + // For SpongeStonecuttingRecipe resend the output slot in case the actual crafting result differs from the exemplary result + final ItemStack stack = this.resultSlot.getItem(); + for (final ContainerListener listener : ((AbstractContainerMenuAccessor) this).accessor$containerListeners()) { + listener.slotChanged((AbstractContainerMenu) (Object) this, 1, stack); + } + }); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ConsumableMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ConsumableMixin.java new file mode 100644 index 00000000000..6aa19ac7470 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ConsumableMixin.java @@ -0,0 +1,57 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.core.world.item; + +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.Consumable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.bridge.data.VanishableBridge; + +@Mixin(Consumable.class) +public abstract class ConsumableMixin { + + @Redirect(method = "emitParticlesAndSounds", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/LivingEntity;spawnItemParticles(Lnet/minecraft/world/item/ItemStack;I)V")) + private void impl$createCauseFrameForTeleport(final LivingEntity instance, final ItemStack $$0, final int $$1) { + if (!(instance instanceof VanishableBridge bridge) || bridge.bridge$vanishState().createsParticles()) { + instance.spawnItemParticles($$0, $$1); + } + } + + + @Redirect(method = "emitParticlesAndSounds", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/LivingEntity;playSound(Lnet/minecraft/sounds/SoundEvent;FF)V")) + private void impl$ignoreExperienceLevelSoundsWhileVanished(final LivingEntity instance, final SoundEvent soundEvent, + final float $$1, final float $$2) { + if (!(instance instanceof VanishableBridge bridge) || bridge.bridge$vanishState().createsSounds()) { + instance.playSound(soundEvent, $$1, $$2); + } + } + +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java index 572050becb8..31681eb2e25 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java @@ -28,7 +28,6 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; -import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.EnderEyeItem; @@ -90,14 +89,14 @@ public abstract class EnderEyeItemMixin extends ItemMixin { cancellable = true ) private void impl$ThrowForPreEvent(final Level worldIn, final Player playerIn, final InteractionHand handIn, - final CallbackInfoReturnable> cir, final ItemStack used, final BlockHitResult rayTraceResult, final ServerLevel world, final BlockPos targetPos) { + final CallbackInfoReturnable cir, final ItemStack used, final BlockHitResult rayTraceResult, final ServerLevel world, final BlockPos targetPos) { if (targetPos != null && !((LevelBridge) worldIn).bridge$isFake() && ShouldFire.CONSTRUCT_ENTITY_EVENT_PRE) { final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(PhaseTracker.getCauseStackManager().currentCause(), ServerLocation.of((ServerWorld) worldIn, playerIn.getX(), playerIn.getY() + (double) (playerIn.getDimensions(playerIn .getPose()).height() / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); if (SpongeCommon.post(event)) { - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, used)); + cir.setReturnValue(InteractionResult.SUCCESS_SERVER); } } } @@ -108,14 +107,14 @@ public abstract class EnderEyeItemMixin extends ItemMixin { @SuppressWarnings("Duplicates") @Surrogate private void impl$ThrowForPreEvent(final Level worldIn, final Player playerIn, final InteractionHand handIn, - final CallbackInfoReturnable> cir, final ItemStack used, @Nullable final BlockPos targetPos) { + final CallbackInfoReturnable cir, final ItemStack used, @Nullable final BlockPos targetPos) { if (targetPos != null && !((LevelBridge) worldIn).bridge$isFake() && ShouldFire.CONSTRUCT_ENTITY_EVENT_PRE) { final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(PhaseTracker.getCauseStackManager().currentCause(), ServerLocation.of((ServerWorld) worldIn, playerIn.getX(), playerIn.getY() + (double) (playerIn.getDimensions(playerIn .getPose()).height() / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); if (SpongeCommon.post(event)) { - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, used)); + cir.setReturnValue(InteractionResult.SUCCESS_SERVER); } } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FireworkRocketItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FireworkRocketItemMixin.java index 56c7a4349d6..32df5b872f4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FireworkRocketItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FireworkRocketItemMixin.java @@ -24,12 +24,11 @@ */ package org.spongepowered.common.mixin.core.world.item; -import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; -import net.minecraft.world.InteractionResultHolder; -import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.FireworkRocketEntity; +import net.minecraft.world.entity.projectile.Projectile; import net.minecraft.world.item.FireworkRocketItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; @@ -87,9 +86,9 @@ public abstract class FireworkRocketItemMixin { cancellable = true ) private void impl$throwPreBeforeSpawning(final Level worldIn, final net.minecraft.world.entity.player.Player playerIn, final InteractionHand handIn, - final CallbackInfoReturnable> cir, final ItemStack stack) { + final CallbackInfoReturnable cir, final ItemStack stack) { if (this.impl$throwConstructPreEvent(worldIn, playerIn, stack)) { - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, stack)); + cir.setReturnValue(InteractionResult.SUCCESS); } } @@ -117,8 +116,8 @@ public abstract class FireworkRocketItemMixin { /** * Private method for bridging the duplicate between - * {@link #spongeImpl$ThrowPreBeforeSpawning(World, PlayerEntity, Hand, CallbackInfoReturnable, ItemStack)} and - * {@link #spongeImpl$ThrowPrimeEventsIfCancelled(ItemUseContext, CallbackInfoReturnable)} + * {@link #impl$throwPreBeforeSpawning} and + * {@link #impl$throwPrimeEventsIfCancelled} * since both follow the same logic, but differ in how they are called. * * @param world The world @@ -141,41 +140,53 @@ public abstract class FireworkRocketItemMixin { return false; } + private boolean impl$useOnCancelled = false; + + @Redirect(method = "useOn", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/Projectile;spawnProjectile(Lnet/minecraft/world/entity/projectile/Projectile;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/entity/projectile/Projectile;") + ) + private T impl$onSpawnProjectileForUseOn(final T rocket, final ServerLevel $$1, final ItemStack usedItem, final UseOnContext context) { + this.impl$useOnCancelled = this.impl$throwPrimeEventAndGetCancel(context.getLevel(), context.getPlayer(), (FireworkRocketEntity) rocket, usedItem); + if (!this.impl$useOnCancelled) { + return Projectile.spawnProjectile(rocket, $$1, usedItem); + } + return rocket; + } + @Inject(method = "useOn", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z"), + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/Projectile;spawnProjectile(Lnet/minecraft/world/entity/projectile/Projectile;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/entity/projectile/Projectile;", + shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) - private void impl$injectPrimeEventAndCancel(final UseOnContext context, final CallbackInfoReturnable cir, final Level world, - final ItemStack usedItem, final net.minecraft.world.phys.Vec3 vec3d, final Direction direction, final FireworkRocketEntity rocket) { - if (this.impl$throwPrimeEventAndGetCancel(context.getLevel(), context.getPlayer(), rocket, usedItem)) { + private void impl$afterSpawnProjectileForUseOn(final UseOnContext context, final CallbackInfoReturnable cir) { + if (this.impl$useOnCancelled) { cir.setReturnValue(InteractionResult.SUCCESS); } } - private FireworkRocketEntity impl$capturedRocket; + private boolean impl$useCancelled = false; - @Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z")) - private boolean impl$captureFireworkRocket(Level world, Entity p_217376_1_) { - this.impl$capturedRocket = (FireworkRocketEntity) p_217376_1_; - return true; + @Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/Projectile;spawnProjectile(Lnet/minecraft/world/entity/projectile/Projectile;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/entity/projectile/Projectile;")) + private T impl$onSpawnProjectileForUse(final T rocket, final ServerLevel serverLevel, final ItemStack usedItem, + final Level $$0, final net.minecraft.world.entity.player.Player player, InteractionHand $$2) { + this.impl$useCancelled = this.impl$throwPrimeEventAndGetCancel(serverLevel, player, (FireworkRocketEntity) rocket, usedItem); + if (!this.impl$useCancelled) { + return Projectile.spawnProjectile(rocket, serverLevel, usedItem); + } + return rocket; } - @Inject(method = "use(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResultHolder;", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z", shift = At.Shift.AFTER), - locals = LocalCapture.CAPTURE_FAILHARD, + @Inject(method = "use", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/Projectile;spawnProjectile(Lnet/minecraft/world/entity/projectile/Projectile;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/world/entity/projectile/Projectile;", + shift = At.Shift.AFTER), cancellable = true ) - private void impl$injectPrimeEventAndCancel(final Level worldIn, final net.minecraft.world.entity.player.Player player, final InteractionHand handIn, - final CallbackInfoReturnable> cir, final ItemStack usedItem) { - if (this.impl$throwPrimeEventAndGetCancel(worldIn, player, this.impl$capturedRocket, usedItem)) { - this.impl$capturedRocket = null; - // We have to still return success because the server/client can get out of sync otherwise. - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, usedItem)); + private void impl$afterSpawnProjectileForUse(final Level $$0, final net.minecraft.world.entity.player.Player $$1, + final InteractionHand $$2, final CallbackInfoReturnable cir) { + if (this.impl$useCancelled) { + cir.setReturnValue(InteractionResult.SUCCESS); } - - worldIn.addFreshEntity(this.impl$capturedRocket); - this.impl$capturedRocket = null; } /** @@ -183,8 +194,8 @@ public abstract class FireworkRocketItemMixin { * the prime is cancelled, then the firework will not be spawned. * This is to bridge the same logic between * - * {@link #impl$injectPrimeEventAndCancel(UseOnContext, CallbackInfoReturnable, Level, ItemStack, net.minecraft.world.phys.Vec3, Direction, FireworkRocketEntity)} - * {@link #impl$injectPrimeEventAndCancel(Level, net.minecraft.world.entity.player.Player, InteractionHand, CallbackInfoReturnable, ItemStack)} + * {@link #impl$onSpawnProjectileForUseOn} + * {@link #impl$onSpawnProjectileForUse} * * @param world The world * @param player The player using the item diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FishingRodItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FishingRodItemMixin.java index ec6a39b5881..6b53414d803 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FishingRodItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/FishingRodItemMixin.java @@ -27,7 +27,6 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; -import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.FishingHook; @@ -53,17 +52,16 @@ public abstract class FishingRodItemMixin { @Inject(method = "use", at = @At(value = "INVOKE", shift = At.Shift.AFTER, target = "Lnet/minecraft/world/entity/projectile/FishingHook;retrieve(Lnet/minecraft/world/item/ItemStack;)I"), cancellable = true) - private void cancelHookRetraction(Level world, Player player, InteractionHand hand, CallbackInfoReturnable> cir) { + private void cancelHookRetraction(Level world, Player player, InteractionHand hand, CallbackInfoReturnable cir) { if (player.fishing != null) { - // Event was cancelled - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, player.getItemInHand(hand))); + cir.setReturnValue(InteractionResult.SUCCESS); // Event was cancelled } } @Inject(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;playSound(Lnet/minecraft/world/entity/player/Player;DDDLnet/minecraft/sounds/SoundEvent;Lnet/minecraft/sounds/SoundSource;FF)V", ordinal = 1), cancellable = true) - private void onThrowEvent(Level level, Player player, InteractionHand hand, CallbackInfoReturnable> cir) { + private void onThrowEvent(Level level, Player player, InteractionHand hand, CallbackInfoReturnable cir) { if (level.isClientSide) { // Only fire event on server-side to avoid crash on client return; @@ -73,12 +71,12 @@ private void onThrowEvent(Level level, Player player, InteractionHand hand, Call if (level instanceof ServerLevel serverLevel) { int $$6 = (int)(EnchantmentHelper.getFishingTimeReduction(serverLevel, itemstack, player) * 20.0F); int $$7 = EnchantmentHelper.getFishingLuckBonus(serverLevel, itemstack, player); - FishingHook fishHook = new FishingHook(player, level, $$7, $$6); + FishingHook fishHook = new FishingHook(player, level, $$7, $$6, itemstack); PhaseTracker.getCauseStackManager().pushCause(player); if (SpongeCommon.post(SpongeEventFactory.createFishingEventStart(PhaseTracker.getCauseStackManager().currentCause(), (FishingBobber) fishHook))) { fishHook.remove(Entity.RemovalReason.DISCARDED); // Bye - cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, player.getItemInHand(hand))); + cir.setReturnValue(InteractionResult.SUCCESS); } else { this.impl$fishHook = fishHook; } @@ -87,7 +85,7 @@ private void onThrowEvent(Level level, Player player, InteractionHand hand, Call } @Redirect(method = "use", at = @At(value = "NEW", target = "net/minecraft/world/entity/projectile/FishingHook")) - private FishingHook onNewEntityFishHook(Player p_i50220_1_, Level p_i50220_2_, int p_i50220_3_, int p_i50220_4_) { + private FishingHook onNewEntityFishHook(final Player $$0, final Level $$1, final int $$2, final int $$3, final ItemStack $$4) { // Use the fish hook we created for the event FishingHook fishHook = this.impl$fishHook; this.impl$fishHook = null; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemCooldownsMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemCooldownsMixin.java index a7d72253a0e..113ff390aef 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemCooldownsMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemCooldownsMixin.java @@ -24,9 +24,10 @@ */ package org.spongepowered.common.mixin.core.world.item; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemCooldowns; -import org.spongepowered.api.item.ItemType; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -49,12 +50,15 @@ public abstract class ItemCooldownsMixin implements ItemCooldownsBridge { // @formatter:off @Shadow @Final private Map cooldowns; + @Shadow public abstract ResourceLocation shadow$getCooldownGroup(final ItemStack $$0); + // @formatter:on + private int impl$lastSetCooldownResult; @Inject( - method = "addCooldown", + method = "addCooldown(Lnet/minecraft/resources/ResourceLocation;I)V", at = @At( value = "HEAD", remap = false @@ -62,15 +66,15 @@ public abstract class ItemCooldownsMixin implements ItemCooldownsBridge { locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) - private void impl$throwEventOnSetAndTrackResult(final Item item, final int ticks, final CallbackInfo ci) { - this.impl$lastSetCooldownResult = this.impl$throwSetCooldownEvent((ItemType) item, ticks); + private void impl$throwEventOnSetAndTrackResult(final ResourceLocation group, final int ticks, final CallbackInfo ci) { + this.impl$lastSetCooldownResult = this.impl$throwSetCooldownEvent(group, ticks); if (this.impl$lastSetCooldownResult == Constants.Sponge.Entity.Player.ITEM_COOLDOWN_CANCELLED) { ci.cancel(); } } @ModifyVariable( - method = "addCooldown", + method = "addCooldown(Lnet/minecraft/resources/ResourceLocation;I)V", at = @At( value = "HEAD", remap = false @@ -82,16 +86,16 @@ public abstract class ItemCooldownsMixin implements ItemCooldownsBridge { } @Redirect(method = "tick", at = @At(value = "INVOKE", target = "Ljava/util/Map$Entry;getKey()Ljava/lang/Object;", remap = false)) - private Object onTick(final Map.Entry entry) { - this.impl$throwEndCooldownEvent((ItemType) entry.getKey()); + private Object onTick(final Map.Entry entry) { + this.impl$throwEndCooldownEvent(entry.getKey()); return entry.getKey(); } - protected int impl$throwSetCooldownEvent(final ItemType type, final int ticks) { + protected int impl$throwSetCooldownEvent(final ResourceLocation group, final int ticks) { return 0; } - protected void impl$throwEndCooldownEvent(final ItemType type) { + protected void impl$throwEndCooldownEvent(final ResourceLocation group) { } @@ -101,7 +105,8 @@ private Object onTick(final Map.Entry entry) { } @Inject(method = "getCooldownPercent", at = @At("HEAD"), cancellable = true) - private void impl$getCooldownPercentInfiniteCooldown(final Item $$0, final float $$1, final CallbackInfoReturnable cir) { + private void impl$getCooldownPercentInfiniteCooldown(final ItemStack $$0, final float $$1, final CallbackInfoReturnable cir) { + ResourceLocation $$2 = this.shadow$getCooldownGroup($$0); final ItemCooldowns_CooldownInstanceAccessor cooldown = (ItemCooldowns_CooldownInstanceAccessor) this.cooldowns.get($$0); if (cooldown != null && cooldown.accessor$endTime() == cooldown.accessor$startTime() - 1) { cir.setReturnValue(1.0F); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ServerItemCooldownsMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ServerItemCooldownsMixin.java index c4dd41280f8..97b7bba16c6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ServerItemCooldownsMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ServerItemCooldownsMixin.java @@ -24,14 +24,14 @@ */ package org.spongepowered.common.mixin.core.world.item; -import net.minecraft.world.item.Item; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ServerItemCooldowns; +import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.CooldownTracker; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.entity.living.player.CooldownEvent; -import org.spongepowered.api.item.ItemType; import org.spongepowered.api.util.Ticks; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -50,20 +50,20 @@ public abstract class ServerItemCooldownsMixin extends ItemCooldownsMixin { // @formmater:off @Shadow @Final private net.minecraft.server.level.ServerPlayer player; - @Shadow protected abstract void shadow$onCooldownStarted(Item itemIn, int ticksIn); + @Shadow protected abstract void shadow$onCooldownStarted(ResourceLocation group, int ticksIn); // @formmater:on @Override - protected int impl$throwSetCooldownEvent(final ItemType type, final int ticks) { + protected int impl$throwSetCooldownEvent(final ResourceLocation group, final int ticks) { if (ticks == 0) { return 0; } - final Optional beforeCooldown = ((CooldownTracker) this).cooldown(type); + final Optional beforeCooldown = ((CooldownTracker) this).cooldown((ResourceKey) (Object)group); final CooldownEvent.Set event = SpongeEventFactory.createCooldownEventSet(PhaseTracker.getCauseStackManager().currentCause(), - SpongeTicks.ticksOrInfinite(ticks), SpongeTicks.ticksOrInfinite(ticks), type, (ServerPlayer) this.player, beforeCooldown); + SpongeTicks.ticksOrInfinite(ticks), SpongeTicks.ticksOrInfinite(ticks), (ResourceKey) (Object) group, (ServerPlayer) this.player, beforeCooldown); if (Sponge.eventManager().post(event)) { - this.shadow$onCooldownStarted((Item) type, beforeCooldown.map(x -> (int) x.ticks()).orElse(0)); + this.shadow$onCooldownStarted(group, beforeCooldown.map(x -> (int) x.ticks()).orElse(0)); return Constants.Sponge.Entity.Player.ITEM_COOLDOWN_CANCELLED; } else { return SpongeTicks.toSaturatedIntOrInfinite(event.newCooldown()); @@ -71,9 +71,9 @@ public abstract class ServerItemCooldownsMixin extends ItemCooldownsMixin { } @Override - protected void impl$throwEndCooldownEvent(final ItemType type) { + protected void impl$throwEndCooldownEvent(final ResourceLocation group) { final CooldownEvent.End event = SpongeEventFactory.createCooldownEventEnd(PhaseTracker.getCauseStackManager().currentCause(), - type, (ServerPlayer) this.player); + (ResourceKey) (Object) group, (ServerPlayer) this.player); Sponge.eventManager().post(event); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ChorusFruitItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/TeleportRandomlyConsumeEffectMixin.java similarity index 87% rename from src/mixins/java/org/spongepowered/common/mixin/core/world/item/ChorusFruitItemMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/item/TeleportRandomlyConsumeEffectMixin.java index 01d1d24a33e..115c4446263 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ChorusFruitItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/TeleportRandomlyConsumeEffectMixin.java @@ -25,7 +25,7 @@ package org.spongepowered.common.mixin.core.world.item; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ChorusFruitItem; +import net.minecraft.world.item.consume_effects.TeleportRandomlyConsumeEffect; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.cause.entity.MovementTypes; @@ -34,10 +34,10 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.event.tracking.PhaseTracker; -@Mixin(ChorusFruitItem.class) -public abstract class ChorusFruitItemMixin { +@Mixin(TeleportRandomlyConsumeEffect.class) +public abstract class TeleportRandomlyConsumeEffectMixin { - @Redirect(method = "finishUsingItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;randomTeleport(DDDZ)Z")) + @Redirect(method = "apply", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;randomTeleport(DDDZ)Z")) private boolean impl$createCauseFrameForTeleport(final LivingEntity entity, final double x, final double y, final double z, final boolean p_213373_7_) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeMixin.java index f2a11346edf..b0bf7289762 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeMixin.java @@ -24,25 +24,16 @@ */ package org.spongepowered.common.mixin.core.world.item.crafting; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.AbstractCookingRecipe; -import org.spongepowered.asm.mixin.Final; +import net.minecraft.world.item.crafting.Ingredient; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.bridge.world.item.crafting.RecipeResultBridge; +import org.spongepowered.common.bridge.world.item.crafting.CookingRecipeBridge; @Mixin(AbstractCookingRecipe.class) -public abstract class AbstractCookingRecipeMixin implements RecipeResultBridge { - - // @formatter=off - @Shadow @Final protected ItemStack result; - - // @formatter=on +public abstract class AbstractCookingRecipeMixin extends SingleItemRecipeMixin implements CookingRecipeBridge { @Override - public ItemStack bridge$result() { - return this.result; + public Ingredient bridge$ingredient() { + return this.shadow$input(); } - - } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeSerializerMixin.java similarity index 86% rename from src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeSerializerMixin.java index 1ff1a6a7ddb..99fbd9f1af7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/AbstractCookingRecipeSerializerMixin.java @@ -38,12 +38,12 @@ import net.minecraft.world.item.crafting.CampfireCookingRecipe; import net.minecraft.world.item.crafting.CookingBookCategory; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.SimpleCookingSerializer; import net.minecraft.world.item.crafting.SmeltingRecipe; import net.minecraft.world.item.crafting.SmokingRecipe; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.bridge.world.item.crafting.CookingRecipeBridge; import org.spongepowered.common.bridge.world.item.crafting.RecipeResultBridge; import org.spongepowered.common.item.recipe.ResultFunctionRecipe; import org.spongepowered.common.item.recipe.cooking.CookingRecipeFactory; @@ -55,8 +55,8 @@ import java.util.function.Function; -@Mixin(SimpleCookingSerializer.class) -public abstract class SimpleCookingSerializerMixin { +@Mixin(AbstractCookingRecipe.Serializer.class) +public abstract class AbstractCookingRecipeSerializerMixin { @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) @@ -68,7 +68,7 @@ public abstract class SimpleCookingSerializerMixin to.map(si -> (T) si, i -> i), fr -> { if (fr instanceof SpongeBlastingRecipe si) { @@ -79,7 +79,7 @@ public abstract class SimpleCookingSerializerMixin to.map(si -> (T) si, i -> i), fr -> { if (fr instanceof SpongeCampfireCookingRecipe si) { @@ -91,7 +91,7 @@ public abstract class SimpleCookingSerializerMixin to.map(si -> (T) si, i -> i), fr -> { if (fr instanceof SpongeSmeltingRecipe si) { @@ -104,7 +104,7 @@ public abstract class SimpleCookingSerializerMixin to.map(si -> (T) si, i -> i), fr -> { if (fr instanceof SpongeSmokingRecipe si) { @@ -123,12 +123,12 @@ public abstract class SimpleCookingSerializerMixin $$2.group( Codec.STRING.fieldOf(SPONGE_TYPE).forGetter(a -> "custom"), - Codec.STRING.optionalFieldOf("group", "").forGetter(AbstractCookingRecipe::getGroup), + Codec.STRING.optionalFieldOf("group", "").forGetter(AbstractCookingRecipe::group), CookingBookCategory.CODEC.fieldOf("category").orElse(CookingBookCategory.MISC).forGetter(AbstractCookingRecipe::category), - Ingredient.CODEC_NONEMPTY.fieldOf(Constants.Recipe.COOKING_INGREDIENT).forGetter($$0x -> $$0x.getIngredients().get(0)), + Ingredient.CODEC.fieldOf(Constants.Recipe.COOKING_INGREDIENT).forGetter($$0x -> ((CookingRecipeBridge) $$0x).bridge$ingredient()), BuiltInRegistries.ITEM.byNameCodec().xmap(ItemStack::new, ItemStack::getItem).fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), - Codec.FLOAT.fieldOf(Constants.Recipe.COOKING_EXP).orElse(0.0F).forGetter(AbstractCookingRecipe::getExperience), - Codec.INT.fieldOf(Constants.Recipe.COOKING_TIME).orElse(defaultCookingTime).forGetter(AbstractCookingRecipe::getCookingTime), + Codec.FLOAT.fieldOf(Constants.Recipe.COOKING_EXP).orElse(0.0F).forGetter(AbstractCookingRecipe::experience), + Codec.INT.fieldOf(Constants.Recipe.COOKING_TIME).orElse(defaultCookingTime).forGetter(AbstractCookingRecipe::cookingTime), ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$spongeResult()), Codec.STRING.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId) ) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCraftingRecipeSerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/CustomRecipeSerializerMixin.java similarity index 93% rename from src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCraftingRecipeSerializerMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/CustomRecipeSerializerMixin.java index 9defd9d4e6b..c29e4b941b4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCraftingRecipeSerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/CustomRecipeSerializerMixin.java @@ -30,7 +30,7 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.crafting.CraftingRecipe; -import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; +import net.minecraft.world.item.crafting.CustomRecipe; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -38,8 +38,8 @@ import java.util.function.Function; -@Mixin(SimpleCraftingRecipeSerializer.class) -public abstract class SimpleCraftingRecipeSerializerMixin { +@Mixin(CustomRecipe.Serializer.class) +public abstract class CustomRecipeSerializerMixin { @Redirect(method = "", at = @At(value = "INVOKE", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java index ade3ce146d4..07dda2bd02b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java @@ -27,26 +27,33 @@ import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; import net.minecraft.world.item.crafting.Ingredient; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +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; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.item.recipe.ingredient.SpongeIngredient; @Mixin(Ingredient.class) public abstract class IngredientMixin { - @Inject(method = "codec", at = @At(value = "RETURN"), cancellable = true) - private static void impl$modifyCodec(final boolean $$0, final CallbackInfoReturnable> cir) { - final Codec original = cir.getReturnValue(); - var combinedCodec = Codec.xor(SpongeIngredient.CODEC, original).xmap(to -> to.map(si -> si, i -> i), - fr -> { - if (fr instanceof SpongeIngredient si) { - return Either.left(si); - } else { - return Either.right(fr); - } - }); - cir.setReturnValue(combinedCodec); + //@formatter:off + @Shadow @Final @Mutable public static Codec CODEC; + //@formatter:on + + @Redirect( + method = "", + at = @At(value = "FIELD", target = "Lnet/minecraft/world/item/crafting/Ingredient;CODEC:Lcom/mojang/serialization/Codec;") + ) + private static void impl$modifyCodec(Codec value) { + CODEC = Codec.xor(SpongeIngredient.CODEC, value).xmap(to -> to.map(si -> si, i -> i), + fr -> { + if (fr instanceof SpongeIngredient si) { + return Either.left(si); + } else { + return Either.right(fr); + } + }); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/RecipeManagerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/RecipeManagerMixin.java index 15ca24ce109..6a88a92d0e8 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/RecipeManagerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/RecipeManagerMixin.java @@ -24,10 +24,12 @@ */ package org.spongepowered.common.mixin.core.world.item.crafting; +import com.google.gson.JsonObject; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderLookup; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeManager; import org.spongepowered.asm.mixin.Mixin; @@ -37,20 +39,25 @@ @Mixin(RecipeManager.class) public abstract class RecipeManagerMixin { -@Redirect(method = "fromJson", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/Codec;parse(Lcom/mojang/serialization/DynamicOps;Ljava/lang/Object;)Lcom/mojang/serialization/DataResult;")) - private static DataResult> impl$onParseRecipe(final Codec> instance, final DynamicOps dynamicOps, final T element, final ResourceLocation $$0) -{ - final DataResult> parsed; - try { - parsed = instance.parse(dynamicOps, element); - } catch (Exception e) { - SpongeCommon.logger().error("Could not parse recipe {}", $$0, e); - throw new RuntimeException(e); + @Redirect(method = "fromJson", at = @At( + value = "INVOKE", + target = "Lcom/mojang/serialization/Codec;parse(Lcom/mojang/serialization/DynamicOps;Ljava/lang/Object;)Lcom/mojang/serialization/DataResult;" + )) + private static DataResult> impl$onParseRecipe( + final Codec> instance, final DynamicOps dynamicOps, final T element, + ResourceKey> $$0, JsonObject $$1, HolderLookup.Provider $$2 + ) { + final DataResult> parsed; + try { + parsed = instance.parse(dynamicOps, element); + } catch (Exception e) { + SpongeCommon.logger().error("Could not parse recipe {}", $$0, e); + throw new RuntimeException(e); + } + if (parsed.error().isPresent()) { + SpongeCommon.logger().error("Could not parse recipe {} {}", $$0, parsed.error().get().message()); + } + return parsed; } - if (parsed.error().isPresent()) { - SpongeCommon.logger().error("Could not parse recipe {} {}", $$0, parsed.error().get().message()); - } - return parsed; -} } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SingleItemRecipeMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SingleItemRecipeMixin.java index e53ce088d5a..b0925a42a67 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SingleItemRecipeMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SingleItemRecipeMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.item.crafting; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.SingleItemRecipe; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -38,8 +39,8 @@ public abstract class SingleItemRecipeMixin implements RecipeResultBridge { // @formatter=off - @Shadow @Final protected ItemStack result; - + @Shadow @Final private ItemStack result; + @Shadow public abstract Ingredient shadow$input(); // @formatter=on diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipeMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipeMixin.java index 531399e070c..0fa9a035e4f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipeMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipeMixin.java @@ -32,28 +32,30 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.bridge.world.item.crafting.SmithingRecipeBridge; +import java.util.Optional; + @Mixin(SmithingTransformRecipe.class) public abstract class SmithingTransformRecipeMixin implements SmithingRecipeBridge { // @formatter=off - @Shadow @Final Ingredient template; - @Shadow @Final Ingredient base; - @Shadow @Final Ingredient addition; + @Shadow @Final Optional template; + @Shadow @Final Optional base; + @Shadow @Final Optional addition; @Shadow @Final ItemStack result; // @formatter=on @Override - public Ingredient bridge$template() { + public Optional bridge$template() { return this.template; } @Override - public Ingredient bridge$base() { + public Optional bridge$base() { return this.base; } @Override - public Ingredient bridge$addition() { + public Optional bridge$addition() { return this.addition; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java deleted file mode 100644 index 688112d13eb..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.core.world.level; - -import com.google.common.collect.Sets; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.util.Mth; -import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.ExplosionDamageCalculator; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.SpongeEventFactory; -import org.spongepowered.api.event.world.ExplosionEvent; -import org.spongepowered.api.world.explosion.Explosion; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -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.Surrogate; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.bridge.world.level.ExplosionBridge; -import org.spongepowered.common.event.ShouldFire; -import org.spongepowered.common.event.tracking.PhaseTracker; -import org.spongepowered.common.util.VecHelper; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.StringJoiner; - -@Mixin(net.minecraft.world.level.Explosion.class) -public abstract class ExplosionMixin implements ExplosionBridge { - - // @formatter:off - @Shadow @Final private ExplosionDamageCalculator damageCalculator; - @Shadow @Final private ObjectArrayList toBlow; - @Shadow @Final private Map hitPlayers; - @Shadow @Final private boolean fire; - @Shadow @Final private net.minecraft.world.level.Level level; - @Shadow @Final private double x; - @Shadow @Final private double y; - @Shadow @Final private double z; - @Shadow @Final private Entity source; - @Shadow @Final private float radius; - @Shadow @Final private net.minecraft.world.level.Explosion.BlockInteraction blockInteraction; - - @Shadow @Final private DamageSource damageSource; - // @formatter:on - - private boolean impl$shouldBreakBlocks; - private boolean impl$shouldDamageEntities; - private boolean impl$shouldPlaySmoke; - private int impl$resolution; - private float impl$randomness; - private double impl$knockback; - - @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;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/core/Holder;)V", - at = @At("RETURN") - ) - private void impl$onConstructed(final Level $$0, final Entity $$1, final DamageSource $$2, final ExplosionDamageCalculator $$3, final double $$4, - final double $$5, final double $$6, final float $$7, final boolean $$8, final net.minecraft.world.level.Explosion.BlockInteraction $$9, - final ParticleOptions $$10, final ParticleOptions $$11, final Holder $$12, final CallbackInfo ci) { - // In Vanilla and Forge, 'damagesTerrain' controls both smoke particles and block damage - // Sponge-created explosions will explicitly set 'impl$shouldBreakBlocks' to its proper value - this.impl$shouldBreakBlocks = this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY || this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; - this.impl$shouldDamageEntities = true; - this.impl$resolution = 16; - this.impl$randomness = 1.0F; - this.impl$knockback = 1.0; - } - - // (Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/util/DamageSource;Lnet/minecraft/world/ExplosionContext;DDDFZLnet/minecraft/world/Explosion$Mode;Lorg/spongepowered/asm/mixin/injection/callback/CallbackInfo;)V - @Surrogate - private void impl$onConstructed(final Level worldIn, final Entity exploderIn, final DamageSource damageSourceIn, final ExplosionDamageCalculator explosionContextIn, final double xIn, final double yIn, final double zIn, final float sizeIn, final boolean causesFireIn, final net.minecraft.world.level.Explosion.BlockInteraction modeIn, final CallbackInfo ci) { - // In Vanilla and Forge, 'damagesTerrain' controls both smoke particles and block damage - // Sponge-created explosions will explicitly set 'impl$shouldBreakBlocks' to its proper value - this.impl$shouldBreakBlocks = this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY || this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; - this.impl$shouldDamageEntities = true; - this.impl$resolution = 16; - this.impl$randomness = 1.0F; - this.impl$knockback = 1.0; - } - - /** - * @author gabizou - * @author zidane - * @reason Fire ExplosionEvent.Detonate - */ - @Overwrite - public void explode() { - - // Sponge Start - Do not run calculation logic on client thread - if (this.level.isClientSide) { - return; - } - // Sponge End - - // Sponge Start - If the explosion should not break blocks, don't bother calculating it on server thread - if (this.impl$shouldBreakBlocks) { - final Set set = Sets.newHashSet(); - final int i = 16; - - for (int j = 0; j < 16; ++j) { - for (int k = 0; k < 16; ++k) { - for (int l = 0; l < 16; ++l) { - if (j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) { - double d0 = (double) ((float) j / 15.0F * 2.0F - 1.0F); - double d1 = (double) ((float) k / 15.0F * 2.0F - 1.0F); - double d2 = (double) ((float) l / 15.0F * 2.0F - 1.0F); - final double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - d0 = d0 / d3; - d1 = d1 / d3; - d2 = d2 / d3; - float f = this.radius * (0.7F + this.level.random.nextFloat() * 0.6F); - double d4 = this.x; - double d6 = this.y; - double d8 = this.z; - - for (final float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { - final BlockPos blockpos = new BlockPos((int) d4, (int) d6, (int) d8); - final BlockState blockstate = this.level.getBlockState(blockpos); - final FluidState fluidstate = this.level.getFluidState(blockpos); - final Optional optional = this.damageCalculator.getBlockExplosionResistance((net.minecraft.world.level.Explosion) (Object) this, this.level, blockpos, blockstate, fluidstate); - if (optional.isPresent()) { - f -= (optional.get() + 0.3F) * 0.3F; - } - - if (f > 0.0F && this.damageCalculator.shouldBlockExplode((net.minecraft.world.level.Explosion) (Object) this, this.level, blockpos, blockstate, f)) { - set.add(blockpos); - } - - d4 += d0 * (double) 0.3F; - d6 += d1 * (double) 0.3F; - d8 += d2 * (double) 0.3F; - } - } - } - } - } - - this.toBlow.addAll(set); - } - // Sponge End - - final float f3 = this.radius * 2.0F; - final int k1 = Mth.floor(this.x - (double) f3 - 1.0D); - final int l1 = Mth.floor(this.x + (double) f3 + 1.0D); - final int i2 = Mth.floor(this.y - (double) f3 - 1.0D); - final int i1 = Mth.floor(this.y + (double) f3 + 1.0D); - final int j2 = Mth.floor(this.z - (double) f3 - 1.0D); - final int j1 = Mth.floor(this.z + (double) f3 + 1.0D); - - // Sponge Start - Only query for entities if we're to damage them - final List list = this.impl$shouldDamageEntities ? this.level.getEntities(this.source, - new AABB((double) k1, (double) i2, (double) j2, (double) l1, (double) i1, (double) j1)) : Collections.emptyList(); - // Sponge End - - if (ShouldFire.EXPLOSION_EVENT_DETONATE) { - final List blockPositions = new ArrayList<>(this.toBlow.size()); - final List entities = new ArrayList<>(list.size()); - for (final BlockPos pos : this.toBlow) { - blockPositions - .add(ServerLocation.of((org.spongepowered.api.world.server.ServerWorld) this.level, pos.getX(), pos.getY(), pos.getZ())); - } - for (final Entity entity : list) { - // Make sure to check the entity is immune first. - if (!entity.ignoreExplosion((net.minecraft.world.level.Explosion) (Object) this)) { - entities.add((org.spongepowered.api.entity.Entity) entity); - } - } - final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); - final ExplosionEvent.Detonate detonate = SpongeEventFactory.createExplosionEventDetonate(cause, blockPositions, entities, - (Explosion) this, (org.spongepowered.api.world.server.ServerWorld) this.level); - SpongeCommon.post(detonate); - // Clear the positions so that they can be pulled from the event - this.toBlow.clear(); - if (detonate.isCancelled()) { - return; - } - if (this.impl$shouldBreakBlocks) { - for (final ServerLocation worldLocation : detonate.affectedLocations()) { - this.toBlow.add(VecHelper.toBlockPos(worldLocation)); - } - } - // Clear the list of entities so they can be pulled from the event. - list.clear(); - if (this.impl$shouldDamageEntities) { - for (final org.spongepowered.api.entity.Entity entity : detonate.entities()) { - try { - list.add((Entity) entity); - } catch (final Exception e) { - // Do nothing, a plugin tried to use the wrong entity somehow. - } - } - } - } - // Sponge End - - final Vec3 vec3d = new Vec3(this.x, this.y, this.z); - - for (int k2 = 0; k2 < list.size(); ++k2) { - final Entity entity = list.get(k2); - if (!entity.ignoreExplosion((net.minecraft.world.level.Explosion) (Object) this)) { - final double d12 = (Math.sqrt(entity.distanceToSqr(vec3d)) / f3); - if (d12 <= 1.0D) { - double d5 = entity.getX() - this.x; - double d7 = entity.getEyeY() - this.y; - double d9 = entity.getZ() - this.z; - final double d13 = Math.sqrt(d5 * d5 + d7 * d7 + d9 * d9); - if (d13 != 0.0D) { - d5 = d5 / d13; - d7 = d7 / d13; - d9 = d9 / d13; - final double d14 = (double) net.minecraft.world.level.Explosion.getSeenPercent(vec3d, entity); - final double d10 = (1.0D - d12) * d14; - entity.hurt(this.damageSource, (float)((int)((d10 * d10 + d10) / 2.0D * 7.0D * (double)f3 + 1.0D))); - double d11 = d10; - if (entity instanceof LivingEntity living) { - d11 = d10 * (1.0 - living.getAttributeValue(Attributes.EXPLOSION_KNOCKBACK_RESISTANCE)); - } - - // Sponge Start - Honor our knockback value from event - entity.setDeltaMovement(entity.getDeltaMovement().add(d5 * d11 * this.impl$knockback, d7 * d11 * this.impl$knockback, d9 * d11 * this.impl$knockback)); - if (entity instanceof Player) { - final Player playerentity = (Player)entity; - if (!playerentity.isSpectator() && (!playerentity.isCreative() || !playerentity.getAbilities().flying)) { - this.hitPlayers.put(playerentity, new Vec3(d5 * d10 * this.impl$knockback, - d7 * d10 * this.impl$knockback, d9 * d10 * this.impl$knockback)); - } - } - // Sponge End - } - } - } - } - } - - @Override - public boolean bridge$getShouldDamageBlocks() { - return this.impl$shouldBreakBlocks; - } - - @Override - public boolean bridge$getShouldDamageEntities() { - return this.impl$shouldDamageEntities; - } - - @Override - public void bridge$setShouldBreakBlocks(final boolean shouldBreakBlocks) { - this.impl$shouldBreakBlocks = shouldBreakBlocks; - } - - @Override - public void bridge$setShouldDamageEntities(final boolean shouldDamageEntities) { - this.impl$shouldDamageEntities = shouldDamageEntities; - } - - @Override - public void bridge$setResolution(final int resolution) { - this.impl$resolution = resolution; - } - - @Override - public int bridge$getResolution() { - return this.impl$resolution; - } - - @Override - public void bridge$setShouldPlaySmoke(final boolean shouldPlaySmoke) { - this.impl$shouldPlaySmoke = shouldPlaySmoke; - } - - @Override - public boolean bridge$getShouldPlaySmoke() { - return this.impl$shouldPlaySmoke; - } - - @Override - public void bridge$setRandomness(final float randomness) { - this.impl$randomness = randomness; - } - - @Override - public float bridge$getRandomness() { - return this.impl$randomness; - } - - @Override - public void bridge$setKnockback(final double knockback) { - this.impl$knockback = knockback; - } - - @Override - public double bridge$getKnockback() { - return this.impl$knockback; - } - - @Override - public String toString() { - return new StringJoiner(", ", ExplosionMixin.class.getSimpleName() + "[", "]") - .add("causesFire=" + this.fire) - .add("mode=" + this.blockInteraction) - .add("world=" + this.level) - .add("x=" + this.x) - .add("y=" + this.y) - .add("z=" + this.z) - .add("exploder=" + this.source) - .add("size=" + this.radius) - .add("affectedBlockPositions=" + this.toBlow) - .add("playerKnockbackMap=" + this.hitPlayers) - .add("shouldBreakBlocks=" + this.impl$shouldBreakBlocks) - .add("shouldDamageEntities=" + this.impl$shouldDamageEntities) - .add("resolution=" + this.impl$resolution) - .add("randomness=" + this.impl$randomness) - .add("knockback=" + this.impl$knockback) - .toString(); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/PowerableMobMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/Explosion_BlockInteractionMixin.java similarity index 81% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/PowerableMobMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/level/Explosion_BlockInteractionMixin.java index 47588fb4481..dd00e4d8c1a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/PowerableMobMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/Explosion_BlockInteractionMixin.java @@ -22,12 +22,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.minecraft.world.entity; +package org.spongepowered.common.mixin.core.world.level; -import net.minecraft.world.entity.PowerableMob; -import org.spongepowered.api.entity.Chargeable; +import net.minecraft.world.level.Explosion; +import org.spongepowered.api.world.explosion.ExplosionBlockInteraction; import org.spongepowered.asm.mixin.Mixin; -@Mixin(PowerableMob.class) -public interface PowerableMobMixin_API extends Chargeable { +@Mixin(Explosion.BlockInteraction.class) +public interface Explosion_BlockInteractionMixin extends ExplosionBlockInteraction { + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java index f84890c3743..8bec5197a89 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java @@ -34,6 +34,7 @@ import net.minecraft.util.datafix.DataFixers; import net.minecraft.util.datafix.fixes.References; import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.LightningBolt; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.decoration.ArmorStand; @@ -42,6 +43,7 @@ import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.projectile.ThrownEnderpearl; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Blocks; @@ -195,7 +197,7 @@ public abstract class LevelMixin implements LevelBridge, LevelAccessor { final net.minecraft.world.level.Level thisWorld = (net.minecraft.world.level.Level) (Object) this; // Not all entities have a single World parameter as their constructor if (type == net.minecraft.world.entity.EntityType.LIGHTNING_BOLT) { - entity = net.minecraft.world.entity.EntityType.LIGHTNING_BOLT.create(thisWorld); + entity = net.minecraft.world.entity.EntityType.LIGHTNING_BOLT.create(thisWorld, EntitySpawnReason.EVENT); entity.moveTo(x, y, z); ((LightningBolt) entity).setVisualOnly(false); } @@ -203,7 +205,7 @@ public abstract class LevelMixin implements LevelBridge, LevelAccessor { if (type == net.minecraft.world.entity.EntityType.ENDER_PEARL) { final ArmorStand tempEntity = new ArmorStand(thisWorld, x, y, z); tempEntity.setPos(tempEntity.getX(), tempEntity.getY() - tempEntity.getEyeHeight(), tempEntity.getZ()); - entity = new ThrownEnderpearl(thisWorld, tempEntity); + entity = new ThrownEnderpearl(thisWorld, tempEntity, Items.ENDER_PEARL.getDefaultInstance()); ((EnderPearl) entity).offer(Keys.SHOOTER, UnknownProjectileSource.UNKNOWN); } // Some entities need to have non-null fields (and the easiest way to @@ -218,7 +220,7 @@ public abstract class LevelMixin implements LevelBridge, LevelAccessor { if (entity == null) { final ResourceKey key = (ResourceKey) (Object) SpongeCommon.vanillaRegistry(Registries.ENTITY_TYPE).getKey((net.minecraft.world.entity.EntityType) type); try { - entity = ((net.minecraft.world.entity.EntityType) type).create(thisWorld); + entity = ((net.minecraft.world.entity.EntityType) type).create(thisWorld, EntitySpawnReason.EVENT); entity.moveTo(x, y, z); } catch (final Exception e) { throw new RuntimeException("There was an issue attempting to construct " + key, e); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/NaturalSpawnerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/NaturalSpawnerMixin.java index 4876dfc1d35..8327962e8cf 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/NaturalSpawnerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/NaturalSpawnerMixin.java @@ -26,12 +26,11 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.NaturalSpawner; -import net.minecraft.world.level.chunk.LevelChunk; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.accessor.world.level.NaturalSpawner_SpawnStateAccessor; import org.spongepowered.common.bridge.world.level.NaturalSpawner_SpawnStateBridge; import org.spongepowered.common.bridge.world.level.storage.PrimaryLevelDataBridge; @@ -40,46 +39,23 @@ @Mixin(NaturalSpawner.class) public abstract class NaturalSpawnerMixin { - // @formatter:off - @Shadow @Final private static MobCategory[] SPAWNING_CATEGORIES; - @Shadow static public void spawnCategoryForChunk(final MobCategory p_234967_0_, final ServerLevel p_234967_1_, final LevelChunk p_234967_2_, - final NaturalSpawner.SpawnPredicate p_234967_3_, final NaturalSpawner.AfterSpawnCallback p_234967_4_) { + @Redirect(method = "spawnForChunk", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/NaturalSpawner$SpawnState;canSpawnForCategoryLocal(Lnet/minecraft/world/entity/MobCategory;Lnet/minecraft/world/level/ChunkPos;)Z")) + private static boolean impl$canSpawnForCategoryLocal(final NaturalSpawner.SpawnState instance, final MobCategory $$0, final ChunkPos $$1, final ServerLevel level) { + return NaturalSpawnerMixin.impl$canSpawnInLevel(instance, $$0, level, $$1); } - // @formatter:on - /** - * @author morph - January 3rd, 2021 - Minecraft 1.16.4 - * @reason Use world configured spawn limits - */ - @Overwrite - public static void spawnForChunk(final ServerLevel world, final LevelChunk chunk, final NaturalSpawner.SpawnState manager, final boolean spawnFriendlies, final boolean spawnEnemies, final boolean doMobSpawning) { - world.getProfiler().push("spawner"); - - for (final MobCategory entityclassification : SPAWNING_CATEGORIES) { - if ((spawnFriendlies || !entityclassification.isFriendly()) && (spawnEnemies || entityclassification.isFriendly()) && (doMobSpawning || !entityclassification.isPersistent()) && NaturalSpawnerMixin.impl$canSpawnInLevel(manager, entityclassification, world, chunk)) { - // spawnCategoryForChunk(var0, param0, param1, (param1x, param2x, param3x) -> param2.canSpawn(param1x, param2x, - // param3x), (param1x, param2x) -> param2.afterSpawn(param1x, param2x)); - NaturalSpawnerMixin.spawnCategoryForChunk(entityclassification, world, chunk, - (p_234969_1_, p_234969_2_, p_234969_3_) -> ((NaturalSpawner_SpawnStateAccessor) manager).invoker$canSpawn(p_234969_1_, p_234969_2_, p_234969_3_), - (p_234970_1_, p_234970_2_) -> ((NaturalSpawner_SpawnStateAccessor) manager).invoker$afterSpawn(p_234970_1_, p_234970_2_) - ); - } - } - - world.getProfiler().pop(); - } - - private static boolean impl$canSpawnInLevel(final NaturalSpawner.SpawnState manager, final MobCategory classification, final ServerLevel level, final LevelChunk chunk) { + private static boolean impl$canSpawnInLevel(final NaturalSpawner.SpawnState spawnState, final MobCategory classification, final ServerLevel level, final ChunkPos chunkPos) { final int tick = NaturalSpawnerMixin.impl$getSpawningTickRate(classification, level); // Unknown category/use default if (tick == -1) { - return ((NaturalSpawner_SpawnStateAccessor) manager).invoker$canSpawnForCategory(classification, chunk.getPos()); + return ((NaturalSpawner_SpawnStateAccessor) spawnState).invoker$canSpawnForCategoryLocal(classification, chunkPos); } // Turn off spawns if (tick == 0) { return false; } - return level.getGameTime() % tick == 0L && ((NaturalSpawner_SpawnStateBridge) manager).bridge$canSpawnForCategoryInWorld(classification, level); + return level.getGameTime() % tick == 0L && ((NaturalSpawner_SpawnStateBridge) spawnState).bridge$canSpawnForCategoryInWorld(classification, level); } private static int impl$getSpawningTickRate(final MobCategory classification, final ServerLevel world) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java index cada3864214..1efb73a8c2c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java @@ -30,20 +30,18 @@ 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.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.bridge.data.DataCompoundHolder; import org.spongepowered.common.data.DataUtil; -import java.io.File; - @Mixin(SavedData.class) public abstract class SavedDataMixin { - @Inject(method = "save(Ljava/io/File;Lnet/minecraft/core/HolderLookup$Provider;)V", + @Inject(method = "save(Lnet/minecraft/core/HolderLookup$Provider;)Lnet/minecraft/nbt/CompoundTag;", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/saveddata/SavedData;save(Lnet/minecraft/nbt/CompoundTag;Lnet/minecraft/core/HolderLookup$Provider;)Lnet/minecraft/nbt/CompoundTag;"), locals = LocalCapture.CAPTURE_FAILHARD) - public void impl$writeAdditionalMapNBT(File file, HolderLookup.Provider registry, final CallbackInfo cir, CompoundTag compound) { + public void impl$writeAdditionalMapNBT(HolderLookup.Provider registry, final CallbackInfoReturnable cir, CompoundTag compound) { if (this instanceof DataCompoundHolder) { if (DataUtil.syncDataToTag(this)) { compound.merge(((DataCompoundHolder) this).data$getCompound()); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ServerExplosionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ServerExplosionMixin.java new file mode 100644 index 00000000000..dcde1d3930a --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ServerExplosionMixin.java @@ -0,0 +1,233 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.core.world.level; + +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.player.Player; +import net.minecraft.world.level.ExplosionDamageCalculator; +import net.minecraft.world.level.ServerExplosion; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.spongepowered.api.event.Cause; +import org.spongepowered.api.event.SpongeEventFactory; +import org.spongepowered.api.event.world.ExplosionEvent; +import org.spongepowered.api.world.explosion.Explosion; +import org.spongepowered.api.world.server.ServerLocation; +import org.spongepowered.api.world.server.ServerWorld; +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.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.bridge.world.level.ExplosionBridge; +import org.spongepowered.common.event.ShouldFire; +import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.util.VecHelper; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; + +@Mixin(net.minecraft.world.level.ServerExplosion.class) +public abstract class ServerExplosionMixin implements ExplosionBridge { + + // @formatter:off + @Shadow @Final private Map hitPlayers; + @Shadow @Final private boolean fire; + @Shadow @Final private ServerLevel level; + @Shadow @Final private Entity source; + @Shadow @Final private float radius; + @Shadow @Final private Vec3 center; + @Shadow @Final private net.minecraft.world.level.Explosion.BlockInteraction blockInteraction; + + @Shadow protected abstract void shadow$interactWithBlocks(final List $$0); + @Shadow protected abstract List shadow$calculateExplodedPositions(); + @Shadow protected abstract boolean shadow$interactsWithBlocks(); + + @Shadow protected abstract void shadow$createFire(final List $$0); + + // @formatter:on + + + private boolean impl$shouldDamageEntities; + private boolean impl$shouldPlaySmoke; + private int impl$resolution; + private float impl$randomness; + private double impl$knockbackMultiplier; + + @Inject(method = "", at = @At("RETURN")) + private void impl$onConstructed(final ServerLevel $$0, final Entity $$1, final DamageSource $$2, + final ExplosionDamageCalculator $$3, final Vec3 $$4, final float $$5, final boolean $$6, + final net.minecraft.world.level.Explosion.BlockInteraction $$7, final CallbackInfo ci) { + this.impl$shouldDamageEntities = true; + this.impl$resolution = 16; + this.impl$randomness = 1.0F; + this.impl$knockbackMultiplier = 1.0; + } + + private List impl$affectedBlocks; + + @Redirect(method = "explode", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/ServerExplosion;calculateExplodedPositions()Ljava/util/List;")) + private List impl$onCalculateExplodedPositions(final ServerExplosion instance) { + // If we don't fire the event and do not affect any blocks we can ignore the calculation + if (!this.fire && !this.shadow$interactsWithBlocks() && !ShouldFire.EXPLOSION_EVENT_DETONATE) { + return List.of(); + } + + this.impl$affectedBlocks = this.shadow$calculateExplodedPositions(); + return this.impl$affectedBlocks; + } + + + @Redirect(method = "hurtEntities", at = @At(value = "INVOKE", + target = "Lnet/minecraft/server/level/ServerLevel;getEntities(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/phys/AABB;)Ljava/util/List;")) + private List impl$onGetHurtEntities(final ServerLevel instance, final Entity sourceEntity, final AABB aabb) { + final List entities; + if (this.impl$shouldDamageEntities) { + // filter out invulnerable entities before event + entities = instance.getEntities(sourceEntity, aabb).stream() + .filter(e -> !e.ignoreExplosion((net.minecraft.world.level.Explosion) this)) + .toList(); + } else { + entities = Collections.emptyList(); + } + + if (ShouldFire.EXPLOSION_EVENT_DETONATE) { + final var apiWorld = (ServerWorld) this.level; + final var apiEntities = entities.stream().map(org.spongepowered.api.entity.Entity.class::cast).toList(); + final var apiBlockPositions = this.impl$affectedBlocks.stream().map(bp -> ServerLocation.of(apiWorld, VecHelper.toVector3i(bp))).toList(); + final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); + final ExplosionEvent.Detonate event = SpongeEventFactory.createExplosionEventDetonate(cause, apiBlockPositions, apiEntities, (Explosion) this, apiWorld); + if (SpongeCommon.post(event)) { + this.impl$affectedBlocks.clear(); // no blocks affected + return Collections.emptyList(); // no entities affected + } + if (this.shadow$interactsWithBlocks()) { + this.impl$affectedBlocks = event.affectedLocations().stream().map(VecHelper::toBlockPos).toList(); + } + if (this.impl$shouldDamageEntities) { + return event.entities().stream().map(Entity.class::cast).toList(); + } + } + return entities; + } + + @Redirect(method = "hurtEntities", at = @At(value = "NEW", target = "(DDD)Lnet/minecraft/world/phys/Vec3;")) + private Vec3 impl$onAddKnockback(final double $$0, final double $$1, final double $$2) { + // Honor our knockback value from event + return new Vec3($$0 * this.impl$knockbackMultiplier, + $$1 * this.impl$knockbackMultiplier, + $$2 * this.impl$knockbackMultiplier); + } + + @Redirect(method = "explode", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/ServerExplosion;interactWithBlocks(Ljava/util/List;)V")) + private void impl$onInteractWithBlocks(final ServerExplosion instance, final List $$0) { + this.shadow$interactWithBlocks(this.impl$affectedBlocks); + } + + @Redirect(method = "explode", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/ServerExplosion;createFire(Ljava/util/List;)V")) + private void impl$onCreateFire(final ServerExplosion instance, final List $$0) { + this.shadow$createFire(this.impl$affectedBlocks); + } + + @Override + public boolean bridge$getShouldDamageEntities() { + return this.impl$shouldDamageEntities; + } + + @Override + public void bridge$setShouldDamageEntities(final boolean shouldDamageEntities) { + this.impl$shouldDamageEntities = shouldDamageEntities; + } + + @Override + public void bridge$setResolution(final int resolution) { + this.impl$resolution = resolution; + } + + @Override + public int bridge$getResolution() { + return this.impl$resolution; + } + + @Override + public void bridge$setShouldPlaySmoke(final boolean shouldPlaySmoke) { + this.impl$shouldPlaySmoke = shouldPlaySmoke; + } + + @Override + public boolean bridge$getShouldPlaySmoke() { + return this.impl$shouldPlaySmoke; + } + + @Override + public void bridge$setRandomness(final float randomness) { + this.impl$randomness = randomness; + } + + @Override + public float bridge$getRandomness() { + return this.impl$randomness; + } + + @Override + public void bridge$setKnockback(final double knockback) { + this.impl$knockbackMultiplier = knockback; + } + + @Override + public double bridge$getKnockback() { + return this.impl$knockbackMultiplier; + } + + @Override + public String toString() { + return new StringJoiner(", ", ServerExplosionMixin.class.getSimpleName() + "[", "]") + .add("causesFire=" + this.fire) + .add("blockInteraction=" + this.blockInteraction) + .add("world=" + this.level) + .add("x=" + this.center.x) + .add("y=" + this.center.y) + .add("z=" + this.center.z) + .add("exploder=" + this.source) + .add("size=" + this.radius) + .add("playerKnockbackMap=" + this.hitPlayers) + .add("shouldDamageEntities=" + this.impl$shouldDamageEntities) + .add("resolution=" + this.impl$resolution) + .add("randomness=" + this.impl$randomness) + .add("knockback=" + this.impl$knockbackMultiplier) + .toString(); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java index 8837646fa7d..fec121c03e4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java @@ -28,18 +28,15 @@ import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageSources; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.CampfireBlock; -import net.minecraft.world.level.block.entity.CampfireBlockEntity; import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.common.bridge.world.level.block.entity.CampfireBlockEntityBridge; import org.spongepowered.common.mixin.core.block.BlockMixin; @Mixin(CampfireBlock.class) @@ -56,17 +53,9 @@ public abstract class CampfireBlockMixin extends BlockMixin { final ServerLocation location = ServerLocation.of((ServerWorld) world, blockPos.getX(), blockPos.getY(), blockPos.getZ()); var blockSource = org.spongepowered.api.event.cause.entity.damage.source.DamageSource.builder() .from((org.spongepowered.api.event.cause.entity.damage.source.DamageSource) source).block(location) + .type(DamageTypes.CAMPFIRE) .block(location.createSnapshot()).build(); return (DamageSource) blockSource; } - @Redirect(method = "useItemOn", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/CampfireBlockEntity;placeFood(Lnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/item/ItemStack;I)Z")) - public boolean impl$placeFood(final CampfireBlockEntity instance, final LivingEntity player, final ItemStack item, final int cookingTime) { - if (instance.placeFood(player, item, cookingTime)) { - ((CampfireBlockEntityBridge) instance).bridge$placeRecipe(instance.getCookableRecipe(item).get()); - return true; - } - return false; - } - } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/EndPortalBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/EndPortalBlockMixin.java index 74e5aca88c8..c331e66722d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/EndPortalBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/EndPortalBlockMixin.java @@ -30,7 +30,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.EndPortalBlock; import net.minecraft.world.level.levelgen.feature.EndPlatformFeature; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.portal.TeleportTransition; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.util.Axis; import org.spongepowered.api.world.portal.Portal; @@ -66,8 +66,8 @@ public abstract class EndPortalBlockMixin implements PortalBlockBridge { } if (entity instanceof ServerPlayer player) { - var transition = player.findRespawnPositionAndUseSpawnBlock(false, DimensionTransition.DO_NOTHING); - return ServerLocation.of((ServerWorld) transition.newLevel(), VecHelper.toVector3d(transition.pos())); + var transition = player.findRespawnPositionAndUseSpawnBlock(false, TeleportTransition.DO_NOTHING); + return ServerLocation.of((ServerWorld) transition.newLevel(), VecHelper.toVector3d(transition.position())); } final var sharedSpawnPos = toLevel.getSharedSpawnPos(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/TntBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/TntBlockMixin.java index e4c25d85225..ad866c991ee 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/TntBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/TntBlockMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.level.block; import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.PrimedTnt; import net.minecraft.world.level.Explosion; @@ -81,12 +82,12 @@ public abstract class TntBlockMixin extends BlockMixin { @Inject( method = "wasExploded", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z"), + at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z"), locals = LocalCapture.CAPTURE_FAILSOFT, cancellable = true ) private void impl$CheckIfCanPrimeFromExplosion( - final Level worldIn, final BlockPos pos, final Explosion explosionIn, final CallbackInfo ci, final PrimedTnt tnt) { + final ServerLevel worldIn, final BlockPos pos, final Explosion explosionIn, final CallbackInfo ci, final PrimedTnt tnt) { if (ShouldFire.PRIME_EXPLOSIVE_EVENT_PRE) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.EXPLOSION); @@ -110,7 +111,7 @@ public abstract class TntBlockMixin extends BlockMixin { return this.impl$onRemove(world, pos, isMoving); } - @Redirect(method = "use", at = @At(value = "INVOKE", + @Redirect(method = "useItemOn", 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 impl$removeActivated(final Level world, final BlockPos pos, final BlockState state, final int flag) { // Called when player manually ignites TNT diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin.java index 38afcfe57dc..0312655e337 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin.java @@ -26,12 +26,12 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.AbstractCookingRecipe; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.SingleRecipeInput; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; import net.minecraft.world.level.block.state.BlockState; import org.objectweb.asm.Opcodes; @@ -74,7 +74,9 @@ public abstract class AbstractFurnaceBlockEntityMixin extends BaseContainerBlock // Shrink Fuel @Redirect(method = "serverTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/item/ItemStack;shrink(I)V")) - private static void impl$throwFuelEventIfOrShrink(final ItemStack itemStack, final int quantity, final Level var0, final BlockPos var1, final BlockState var2, final AbstractFurnaceBlockEntity entity) { + private static void impl$throwFuelEventIfOrShrink( + final ItemStack itemStack, final int quantity, final ServerLevel var0, final BlockPos var1, + final BlockState var2, final AbstractFurnaceBlockEntity entity) { final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); final ItemStackSnapshot fuel = ItemStackUtil.snapshotOf(itemStack); @@ -103,8 +105,11 @@ public abstract class AbstractFurnaceBlockEntityMixin extends BaseContainerBlock @Override public Optional> bridge$getCurrentRecipe() { + if (!(this.level instanceof ServerLevel se)) { + return Optional.empty(); + } var recipeInpuit = new SingleRecipeInput(this.items.get(0)); - return this.quickCheck.getRecipeFor(recipeInpuit, this.level); + return this.quickCheck.getRecipeFor(recipeInpuit, se); } // Interrupt-Active - e.g. a player removing the currently smelting item @@ -112,7 +117,7 @@ public abstract class AbstractFurnaceBlockEntityMixin extends BaseContainerBlock method = "setItem", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;getTotalCookTime(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;)I" + target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;getTotalCookTime(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;)I" ) ) private void impl$interruptSmelt(final CallbackInfo ci) { @@ -130,7 +135,7 @@ public abstract class AbstractFurnaceBlockEntityMixin extends BaseContainerBlock slice = @Slice( from = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;burn(Lnet/minecraft/core/RegistryAccess;Lnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/core/NonNullList;I)Z" + target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;burn(Lnet/minecraft/core/RegistryAccess;Lnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/world/item/crafting/SingleRecipeInput;Lnet/minecraft/core/NonNullList;I)Z" ), to = @At( value = "INVOKE", @@ -138,7 +143,7 @@ public abstract class AbstractFurnaceBlockEntityMixin extends BaseContainerBlock ) ) ) - private static void impl$onResetCookTimePassive(final Level level, final BlockPos pos, final BlockState state, + private static void impl$onResetCookTimePassive(final ServerLevel level, final BlockPos pos, final BlockState state, @Coerce final AbstractFurnaceBlockEntityMixin entity, final CallbackInfo ci) { entity.impl$callInteruptSmeltEvent(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BeaconBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BeaconBlockEntityMixin.java index 6cd5a1d20fb..6bfb95f10fd 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BeaconBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BeaconBlockEntityMixin.java @@ -24,13 +24,15 @@ */ package org.spongepowered.common.mixin.core.world.level.block.entity; -import net.minecraft.world.effect.MobEffect; import net.minecraft.world.level.block.entity.BeaconBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import java.util.Optional; +import java.util.function.Function; + @Mixin(BeaconBlockEntity.class) public abstract class BeaconBlockEntityMixin extends BlockEntityMixin { @@ -43,11 +45,13 @@ public abstract class BeaconBlockEntityMixin extends BlockEntityMixin { * @param id The id * @return The potion by id, no validation */ + @SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "rawtypes"}) @Redirect(method = "loadEffect", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BeaconBlockEntity;filterEffect(Lnet/minecraft/world/effect/MobEffect;)Lnet/minecraft/world/effect/MobEffect;") + at = @At(value = "INVOKE", target = "Ljava/util/Optional;map(Ljava/util/function/Function;)Ljava/util/Optional;") ) @Nullable - private static MobEffect impl$UsePotionUtilInsteadOfCheckingValidPotions(MobEffect effect) { - return effect; + private static Optional impl$UsePotionUtilInsteadOfCheckingValidPotions( + Optional instance, Function mapper) { + return instance; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/CampfireBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/CampfireBlockEntityMixin.java index c4b932bcfce..54891998d30 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/CampfireBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/CampfireBlockEntityMixin.java @@ -26,12 +26,14 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CampfireCookingRecipe; import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.SingleRecipeInput; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.CampfireBlockEntity; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.api.ResourceKey; @@ -49,9 +51,9 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.bridge.world.level.block.entity.CampfireBlockEntityBridge; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.inventory.adapter.impl.slots.SlotAdapter; import org.spongepowered.common.item.util.ItemStackUtil; @@ -61,7 +63,7 @@ import java.util.Optional; @Mixin(CampfireBlockEntity.class) -public abstract class CampfireBlockEntityMixin implements CampfireBlockEntityBridge { +public abstract class CampfireBlockEntityMixin { // @Formatter:off @Shadow @Final private NonNullList items; @@ -76,8 +78,9 @@ public abstract class CampfireBlockEntityMixin implements CampfireBlockEntityBri // Tick up @Inject(method = "cookTick", locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "FIELD", target = "Lnet/minecraft/world/level/block/entity/CampfireBlockEntity;cookingProgress:[I", ordinal = 1)) - private static void impl$canCook(final Level level, final BlockPos pos, final BlockState state, final CampfireBlockEntity self, - final CallbackInfo ci, final boolean hasChanged, final int i, final ItemStack itemStack) { + private static void impl$canCook(final ServerLevel level, final BlockPos pos, final BlockState state, final CampfireBlockEntity self, + final RecipeManager.CachedCheck check, + final CallbackInfo ci, final boolean hasChanged, final int i, final ItemStack itemStack) { final CampfireBlockEntityMixin mixinSelf = (CampfireBlockEntityMixin) (Object) self; mixinSelf.impl$currentIndex = i; final boolean isEmpty = itemStack.isEmpty(); @@ -97,8 +100,9 @@ public abstract class CampfireBlockEntityMixin implements CampfireBlockEntityBri @Inject(method = "cookTick", locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/Containers;dropItemStack(Lnet/minecraft/world/level/Level;DDDLnet/minecraft/world/item/ItemStack;)V")) - private static void impl$assembleCampfireResult(final Level level, final BlockPos pos, final BlockState state, - final CampfireBlockEntity self, final CallbackInfo ci, final boolean hasChanged, final int i, + private static void impl$assembleCampfireResult(final ServerLevel level, final BlockPos pos, final BlockState state, + final CampfireBlockEntity self, final RecipeManager.CachedCheck check, + final CallbackInfo ci, final boolean hasChanged, final int i, final ItemStack itemStack, final SingleRecipeInput recipeInput, final ItemStack itemStack1) { final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); final CampfireBlockEntityMixin mixinSelf = (CampfireBlockEntityMixin) (Object) self; @@ -112,27 +116,32 @@ public abstract class CampfireBlockEntityMixin implements CampfireBlockEntityBri mixinSelf.impl$pendingSlotTransaction = transaction; } - @Inject(method = "cookTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;sendBlockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;I)V")) - private static void impl$setCookingEventFinishResult(final Level level, final BlockPos pos, final BlockState state, final CampfireBlockEntity entity, final CallbackInfo ci) { - final CampfireBlockEntityMixin mixinSelf = (CampfireBlockEntityMixin) (Object) entity; + @Inject(method = "cookTick", at = @At(value = "INVOKE", + target = "Lnet/minecraft/server/level/ServerLevel;sendBlockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;I)V" + ), locals = LocalCapture.CAPTURE_FAILEXCEPTION) + private static void impl$setCookingEventFinishResult( + final ServerLevel level, final BlockPos pos, final BlockState state, + final CampfireBlockEntity self, final RecipeManager.CachedCheck $$4, + final CallbackInfo ci, final boolean $$5, final int $$6, final ItemStack $$7, final SingleRecipeInput $$8, + final ItemStack $$9 + ) { + final CampfireBlockEntityMixin mixinSelf = (CampfireBlockEntityMixin) (Object) self; mixinSelf.impl$pendingSlotTransaction.custom().ifPresent(item -> mixinSelf.items.set(((SlotAdapter) mixinSelf.impl$pendingSlotTransaction.slot()).getOrdinal(), ItemStackUtil.fromSnapshotToNative(item))); mixinSelf.impl$pendingSlotTransaction = null; } - @Override - public void bridge$placeRecipe(final RecipeHolder recipe) { - for(int i = 0; i < this.items.size(); ++i) { - final ItemStack itemstack = this.items.get(i); - if (itemstack.isEmpty()) { - this.impl$cookingRecipe[i] = recipe; - return; - } - } + @Inject(method = "placeFood", at = @At(value = "INVOKE", target = "Ljava/util/Optional;get()Ljava/lang/Object;"), + locals = LocalCapture.CAPTURE_FAILHARD) + private void impl$captureRecipeUsage( + final ServerLevel $$0, final LivingEntity $$1, final ItemStack $$2, final CallbackInfoReturnable cir, + final int i, final ItemStack stack, final Optional> recipeOptional) { + // We know that the crafting recipe will exist because mojang checked for us + this.impl$cookingRecipe[i] = recipeOptional.get(); } @Redirect(method = "cookTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/item/ItemStack;isItemEnabled(Lnet/minecraft/world/flag/FeatureFlagSet;)Z")) - private static boolean impl$checkInfiniteCookingTime(final ItemStack instance, final FeatureFlagSet featureFlagSet, final Level level, final BlockPos blockPos, + private static boolean impl$checkInfiniteCookingTime(final ItemStack instance, final FeatureFlagSet featureFlagSet, final ServerLevel level, final BlockPos blockPos, final BlockState state, final CampfireBlockEntity self) { final int cookingTime = ((CampfireBlockEntityMixin) (Object) self).cookingTime[((CampfireBlockEntityMixin) (Object) self).impl$currentIndex]; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/LecternBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/LecternBlockEntityMixin.java index bb91ec378a9..885ec0481d1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/LecternBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/LecternBlockEntityMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.level.block.entity; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.entity.LecternBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; @@ -37,14 +38,14 @@ public abstract class LecternBlockEntityMixin implements CommandSourceProviderBridge { @Shadow - private CommandSourceStack createCommandSourceStack(@Nullable final Player playerEntity) { + private CommandSourceStack createCommandSourceStack(@Nullable final Player playerEntity, final ServerLevel $$1) { throw new AssertionError("This method should be a shadow."); } @Override public CommandSourceStack bridge$getCommandSource(final Cause cause) { // We assume that if a player is in the Cause, they're the one reading the book. - return this.createCommandSourceStack(cause.first(Player.class).orElse(null)); + return this.createCommandSourceStack(cause.first(Player.class).orElse(null), cause.first(ServerLevel.class).orElse(null)); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkSerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkSerializerMixin.java deleted file mode 100644 index 04956c160d1..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkSerializerMixin.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.core.world.level.chunk; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.entity.ai.village.poi.PoiManager; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ImposterProtoChunk; -import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.ProtoChunk; -import net.minecraft.world.level.chunk.storage.ChunkSerializer; -import net.minecraft.world.level.chunk.storage.RegionStorageInfo; -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 org.spongepowered.common.bridge.data.DataCompoundHolder; -import org.spongepowered.common.data.DataUtil; - -@Mixin(ChunkSerializer.class) -public abstract class ChunkSerializerMixin { - - @Inject(method = "write", at = @At(value = "RETURN")) - private static void impl$writeSpongeChunkData(final ServerLevel level, final ChunkAccess chunk, final CallbackInfoReturnable cir) { - if (!(chunk instanceof LevelChunk)) { - return; - } - - final CompoundTag compound = cir.getReturnValue(); - if (DataUtil.syncDataToTag(chunk)) { - compound.merge(((DataCompoundHolder) chunk).data$getCompound()); - } - } - - @Inject(method = "read", at = @At("RETURN")) - private static void impl$readSpongeChunkData(final ServerLevel level, final PoiManager poi, final RegionStorageInfo $$2, final ChunkPos pos, final CompoundTag compound, final CallbackInfoReturnable cir) { - if (!(cir.getReturnValue() instanceof ImposterProtoChunk imposter)) { - return; - } - - ((DataCompoundHolder) imposter.getWrapped()).data$setCompound(compound); - DataUtil.syncTagToData(imposter.getWrapped()); - ((DataCompoundHolder) imposter.getWrapped()).data$setCompound(null); - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/LevelChunkMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/LevelChunkMixin.java index 07a4474a29c..7a6618479d1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/LevelChunkMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/LevelChunkMixin.java @@ -92,7 +92,9 @@ public abstract class LevelChunkMixin extends ChunkAccess implements LevelChunkB @Shadow @Nullable public abstract BlockEntity shadow$getBlockEntity(BlockPos pos, net.minecraft.world.level.chunk.LevelChunk.EntityCreationType p_177424_2_); @Shadow public abstract BlockState shadow$getBlockState(BlockPos pos); @Shadow public abstract void shadow$addEntity(net.minecraft.world.entity.Entity param0); - // @formatter:on + @Shadow public abstract void shadow$markUnsaved(); +// @formatter:on + private long impl$scheduledForUnload = -1; // delay chunk unloads private boolean impl$persistedChunk = false; @@ -130,7 +132,7 @@ public LevelChunkMixin( @Override public void bridge$markChunkDirty() { - this.unsaved = true; + this.shadow$markUnsaved(); } @Override @@ -399,14 +401,14 @@ public String toString() { @Override public DataTransactionResult bridge$offer(final Key<@NonNull ? extends Value> key, final E value) { final DataTransactionResult result = DataHolderProcessor.bridge$offer(this, key, value); - this.unsaved = true; + this.shadow$markUnsaved(); return result; } @Override public DataTransactionResult bridge$remove(final Key<@NonNull ? extends Value> key) { final DataTransactionResult result = DataHolderProcessor.bridge$remove(this, key); - this.unsaved = true; + this.shadow$markUnsaved(); return result; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/SerializableChunkDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/SerializableChunkDataMixin.java new file mode 100644 index 00000000000..bc55b4669ed --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/SerializableChunkDataMixin.java @@ -0,0 +1,135 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.core.world.level.chunk; + +import net.minecraft.core.RegistryAccess; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.storage.SerializableChunkData; +import org.spongepowered.api.world.SerializationBehavior; +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.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.common.bridge.data.DataCompoundHolder; +import org.spongepowered.common.bridge.world.level.chunk.storage.SerializableChunkDataBridge; +import org.spongepowered.common.bridge.world.level.storage.PrimaryLevelDataBridge; +import org.spongepowered.common.data.DataUtil; + +@Mixin(SerializableChunkData.class) +public abstract class SerializableChunkDataMixin implements SerializableChunkDataBridge { + + private CompoundTag impl$tag; + private SerializationBehavior impl$serializationBehavior; + + + @Inject(method = "copyOf", at = @At(value = "RETURN")) + private static void impl$copyOfSpongeData(final ServerLevel level, final ChunkAccess chunkAccess, final CallbackInfoReturnable cir) { + final var bridge = (SerializableChunkDataBridge) (Object) cir.getReturnValue(); + if (level.getLevelData() instanceof PrimaryLevelDataBridge levelBridge) { + final var behavior = levelBridge.bridge$serializationBehavior().orElse(SerializationBehavior.AUTOMATIC); + bridge.bridge$setSerializationBehavior(behavior); + } + if (chunkAccess instanceof LevelChunk levelChunk) { + + bridge.bridge$setTrackerData(levelChunk); + bridge.bridge$setDataHolderData(levelChunk); + } + } + + @Override + public void bridge$setSerializationBehavior(final SerializationBehavior serializationBehavior) { + this.impl$serializationBehavior = serializationBehavior; + } + + @Override + public void bridge$setDataHolderData(final LevelChunk levelChunk) { + this.impl$tag = null; + if (DataUtil.syncDataToTag(levelChunk)) { + this.impl$tag = ((DataCompoundHolder) levelChunk).data$getCompound(); + } + } + + @Inject(method = "write", at = @At(value = "HEAD"), cancellable = true) + private void tracker$beforeWrite(final CallbackInfoReturnable cir) { + switch (this.impl$serializationBehavior) { + case AUTOMATIC, MANUAL -> {} // write normally + default -> cir.setReturnValue(null); + } + + } + + @Inject(method = "write", at = @At(value = "RETURN")) + private void tracker$writeSpongeData(final CallbackInfoReturnable cir) { + final CompoundTag level = cir.getReturnValue(); + this.bridge$writeTrackerData(level); + this.bridge$writeDataHolderData(level); + } + + @Override + public void bridge$writeDataHolderData(final CompoundTag level) { + if (this.impl$tag != null) { + level.merge(this.impl$tag); + } + } + + @Inject(method = "parse", at = @At(value = "RETURN")) + private static void tracker$parseSpongeData(final LevelHeightAccessor $$0, final RegistryAccess $$1, final CompoundTag tag, final CallbackInfoReturnable cir) { + final var bridge = (SerializableChunkDataBridge) (Object) cir.getReturnValue(); + bridge.bridge$parseTrackerData(tag); + bridge.bridge$parseDataHolderData(tag); + } + + @Override + public void bridge$parseDataHolderData(final CompoundTag tag) { + this.impl$tag = tag; + } + + @Redirect(method = "read", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/ChunkAccess;setLightCorrect(Z)V")) + private void impl$readSpongeLevelData(final ChunkAccess chunkAccess, final boolean lightCorrect) { + chunkAccess.setLightCorrect(lightCorrect); + + if (!(chunkAccess instanceof LevelChunk levelChunk)) { + return; + } + + this.bridge$readTrackerDataFrom(levelChunk); + this.bridge$readDataHolderDataFrom(levelChunk); + } + + @Override + public void bridge$readDataHolderDataFrom(final LevelChunk levelChunk) { + ((DataCompoundHolder) levelChunk).data$setCompound(this.impl$tag); + DataUtil.syncTagToData(levelChunk); + ((DataCompoundHolder) levelChunk).data$setCompound(null); + } + + +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/IOWorkerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/IOWorkerMixin.java index e94a7e7fddf..053438fdbe4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/IOWorkerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/IOWorkerMixin.java @@ -31,8 +31,7 @@ import net.minecraft.nbt.visitors.CollectFields; import net.minecraft.nbt.visitors.FieldSelector; import net.minecraft.resources.ResourceKey; -import net.minecraft.util.thread.ProcessorMailbox; -import net.minecraft.util.thread.StrictQueue; +import net.minecraft.util.thread.PriorityConsecutiveExecutor; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.chunk.storage.IOWorker; @@ -45,6 +44,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.Inject; @@ -59,7 +59,7 @@ import org.spongepowered.math.vector.Vector3i; import java.util.BitSet; -import java.util.Map; +import java.util.SequencedMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; @@ -71,9 +71,9 @@ public abstract class IOWorkerMixin implements IOWorkerBridge { @Shadow @Final private static Logger LOGGER; @Shadow @Final private AtomicBoolean shutdownRequested; - @Shadow @Final private ProcessorMailbox mailbox; + @Shadow @Final private PriorityConsecutiveExecutor consecutiveExecutor; @Shadow @Final private RegionFileStorage storage; - @Shadow @Final private Map pendingWrites; + @Shadow @Final private SequencedMap pendingWrites; @Shadow protected abstract boolean shadow$isOldChunk(CompoundTag $$0); @Shadow protected abstract void shadow$tellStorePending(); @@ -163,16 +163,20 @@ private CompletableFuture createOldDataForRegion(final int x, final int }); } + @Unique private CompletableFuture impl$submitTaskCancellable(final Supplier> supplier) { - final CompletableFuture future = this.mailbox.askEither(processor -> new StrictQueue.IntRunnable(0, () -> { + final CompletableFuture future = this.consecutiveExecutor.scheduleWithResult(0, f -> { if (!this.shutdownRequested.get()) { - processor.tell(supplier.get()); + supplier.get() + .ifLeft(f::complete) + .ifRight(f::completeExceptionally); + f.complete(supplier.get().orThrow()); } else { - processor.tell(Either.right(SpongeUnloadedChunkException.INSTANCE)); //Sponge: Complete exceptionally if shutdown was requested + f.completeExceptionally(SpongeUnloadedChunkException.INSTANCE); //Sponge: Complete exceptionally if shutdown was requested } this.shadow$tellStorePending(); - })); + }); //Sponge start: Complete exceptionally if shutdown was requested if (this.shutdownRequested.get()) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java index 31bd3782263..ddde9ac9d2b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java @@ -37,7 +37,7 @@ import org.spongepowered.common.bridge.data.DataCompoundHolder; import org.spongepowered.common.data.DataUtil; -import java.io.File; +import java.nio.file.Path; import java.util.function.BiFunction; @Mixin(DimensionDataStorage.class) @@ -46,7 +46,7 @@ public abstract class DimensionDataStorageMixin { @Inject(method = "readSavedData", at = @At(value = "RETURN", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD) public void readSpongeMapData(BiFunction var1, DataFixTypes $$1, String var2, CallbackInfoReturnable cir, - File var3, CompoundTag rootTag) { + Path var3, CompoundTag rootTag) { final SavedData savedData = cir.getReturnValue(); if (savedData instanceof DataCompoundHolder) { ((DataCompoundHolder) savedData).data$setCompound(rootTag); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java index 1550eb680e9..d6d8f54f8db 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java @@ -339,11 +339,11 @@ public ServerLevelData overworldData() { final Difficulty difficulty = ((LevelData) this).getDifficulty(); if (difficulty == Difficulty.HARD) { - world.setSpawnSettings(true, true); + world.setSpawnSettings(true); // set spawn enemies true } else if (server.isSingleplayer()) { - world.setSpawnSettings(difficulty != Difficulty.PEACEFUL, true); + world.setSpawnSettings(difficulty != Difficulty.PEACEFUL); } else { - world.setSpawnSettings(((MinecraftServerAccessor) server).invoker$isSpawningMonsters(), server.isSpawningAnimals()); + world.setSpawnSettings(((MinecraftServerAccessor) server).invoker$isSpawningMonsters()); } world.players().forEach(player -> player.connection.send(new ClientboundChangeDifficultyPacket(difficulty, isLocked))); diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/CrafterBlockBlockEntityMixin_Inventory_API.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/CrafterBlockBlockEntityMixin_Inventory_API.java index a0ca6cfd4ed..09a74c9bb08 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/CrafterBlockBlockEntityMixin_Inventory_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/CrafterBlockBlockEntityMixin_Inventory_API.java @@ -70,8 +70,11 @@ public GridInventory asGrid() { */ @Override public boolean craftItem() { + if (!(this.level instanceof ServerLevel sl)) { + return false; + } final var input = ((CraftingContainer) this).asCraftInput(); - final var potentialResults = CrafterBlock.getPotentialResults(this.level, input); + final var potentialResults = CrafterBlock.getPotentialResults(sl, input); if (potentialResults.isEmpty()) { return false; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/SlotMixin_Inventory_API.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/SlotMixin_Inventory_API.java index 16790079ee4..132c5f30982 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/SlotMixin_Inventory_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/inventory/SlotMixin_Inventory_API.java @@ -77,7 +77,7 @@ public InventoryTransactionResult set(ItemStackLike stack) { remaining -= push; if (remaining > 0) { - result.reject(ItemStackUtil.cloneDefensive(nativeStack, remaining)); + result.reject((ItemStackLike) ItemStackUtil.cloneDefensive(nativeStack, remaining)); } return result.build(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/CraftingMenuMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/CraftingMenuMixin_Inventory.java index bf57192d81a..3b173f8ebbe 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/CraftingMenuMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/CraftingMenuMixin_Inventory.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.inventory.event.world.inventory; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -31,7 +32,6 @@ import net.minecraft.world.inventory.CraftingMenu; import net.minecraft.world.inventory.ResultContainer; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.crafting.CraftingInventory; @@ -50,8 +50,10 @@ public abstract class CraftingMenuMixin_Inventory { // Crafting Preview @Redirect(method = "slotChangedCraftingGrid", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/ResultContainer;setItem(ILnet/minecraft/world/item/ItemStack;)V")) - private static void beforeSlotChangedCraftingGrid(final ResultContainer resultContainer, final int slotId, final ItemStack itemStack, - final AbstractContainerMenu param0, final Level param1, final Player player, final CraftingContainer craftingContainer, final ResultContainer resultcontainer) { + private static void beforeSlotChangedCraftingGrid( + final ResultContainer resultContainer, final int slotId, final ItemStack itemStack, + final AbstractContainerMenu param0, final ServerLevel param1, final Player player, + final CraftingContainer craftingContainer, final ResultContainer resultcontainer) { resultContainer.setItem(slotId, itemStack); final Inventory inv = ((Inventory) player.containerMenu).query(QueryTypes.INVENTORY_TYPE.get().of(CraftingInventory.class)); diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/ResultSlotMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/ResultSlotMixin_Inventory.java index 65ac8c43f99..7a43a4977ea 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/ResultSlotMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/inventory/ResultSlotMixin_Inventory.java @@ -26,6 +26,7 @@ import net.minecraft.core.NonNullList; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -33,11 +34,11 @@ import net.minecraft.world.inventory.ResultSlot; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.item.inventory.Inventory; @@ -64,6 +65,10 @@ public abstract class ResultSlotMixin_Inventory extends Slot { @Shadow @Final private net.minecraft.world.inventory.CraftingContainer craftSlots; + @Shadow private NonNullList shadow$getRemainingItems(CraftingInput input, Level level) { + throw new IllegalStateException("Untransformed shadow method!"); + } + public ResultSlotMixin_Inventory(final Container inventoryIn, final int index, final int xPosition, final int yPosition) { super(inventoryIn, index, xPosition, yPosition); } @@ -87,8 +92,11 @@ public void set(@Nullable final ItemStack stack) { @Inject(method = "onTake", at = @At("HEAD")) private void impl$beforeTake(final Player thePlayer, final ItemStack stack, final CallbackInfo ci) { + if (!(thePlayer.level() instanceof ServerLevel sl)) { + return; + } if (this.impl$onTakeRecipe == null || !this.impl$onTakeRecipe.value().matches(this.craftSlots.asCraftInput(), thePlayer.level())) { - final RecipeManager manager = thePlayer.level().getRecipeManager(); + final RecipeManager manager = sl.recipeAccess(); this.impl$onTakeRecipe = manager.getRecipeFor(RecipeType.CRAFTING, this.craftSlots.asCraftInput(), thePlayer.level()).orElse(null); } @@ -105,12 +113,12 @@ public void set(@Nullable final ItemStack stack) { stack.shrink(1); } - @Redirect(method = "onTake", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/item/crafting/RecipeManager;getRemainingItemsFor(Lnet/minecraft/world/item/crafting/RecipeType;Lnet/minecraft/world/item/crafting/RecipeInput;Lnet/minecraft/world/level/Level;)Lnet/minecraft/core/NonNullList;")) - private > NonNullList impl$onGetRemainingItems(final RecipeManager recipeManager, final RecipeType recipeTypeIn, final I recipeInput, final net.minecraft.world.level.Level worldIn) { + @Redirect(method = "onTake", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/ResultSlot;getRemainingItems(Lnet/minecraft/world/item/crafting/CraftingInput;Lnet/minecraft/world/level/Level;)Lnet/minecraft/core/NonNullList;")) + private NonNullList impl$onGetRemainingItems(ResultSlot instance, CraftingInput $$0, Level $$1) { if (this.impl$onTakeRecipe == null) { - return NonNullList.withSize(recipeInput.size(), ItemStack.EMPTY); + return NonNullList.withSize($$0.size(), ItemStack.EMPTY); } - return worldIn.getRecipeManager().getRemainingItemsFor(recipeTypeIn, recipeInput, worldIn); + return this.shadow$getRemainingItems($$0, $$1); } @Inject(method = "onTake", cancellable = true, at = @At("RETURN")) diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/entity/player/InventoryMixin_Bridge_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/entity/player/InventoryMixin_Bridge_Inventory.java index 76465fafa51..267bc686dcb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/entity/player/InventoryMixin_Bridge_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/entity/player/InventoryMixin_Bridge_Inventory.java @@ -25,7 +25,7 @@ package org.spongepowered.common.mixin.inventory.impl.world.entity.player; import net.minecraft.core.NonNullList; -import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ClientboundSetHeldSlotPacket; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; @@ -85,7 +85,7 @@ private void onConstructed(final Player playerIn, final CallbackInfo ci) { public void bridge$setSelectedItem(int itemIndex, final boolean notify) { itemIndex = itemIndex % 9; if (notify && this.player instanceof ServerPlayer) { - final ClientboundSetCarriedItemPacket packet = new ClientboundSetCarriedItemPacket(itemIndex); + final var packet = new ClientboundSetHeldSlotPacket(itemIndex); ((ServerPlayer)this.player).connection.send(packet); } this.selected = itemIndex; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/Boat_TypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory.java similarity index 74% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/Boat_TypeMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory.java index a21cd6e2815..1d66bc49ace 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/vehicle/Boat_TypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory.java @@ -22,25 +22,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.minecraft.world.entity.vehicle; +package org.spongepowered.common.mixin.inventory.impl.world.inventory; -import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.level.block.Block; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.data.type.BoatType; +import net.minecraft.world.inventory.AbstractCraftingMenu; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.inventory.ResultContainer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -@Mixin(Boat.Type.class) -public abstract class Boat_TypeMixin_API implements BoatType { +@Mixin(AbstractCraftingMenu.class) +public abstract class AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory { // @formatter:off - @Shadow @Final private Block planks; + @Shadow @Final protected CraftingContainer craftSlots; + @Shadow @Final protected ResultContainer resultSlots; // @formatter:on - @Override - public BlockType representedBlock() { - return (BlockType) this.planks; - } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory.java index 4d405bf7779..155b32b5a54 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.inventory.impl.world.inventory; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -41,14 +42,18 @@ @Mixin(AbstractFurnaceMenu.class) public abstract class AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory { - @Inject(method = "(Lnet/minecraft/world/inventory/MenuType;Lnet/minecraft/world/item/crafting/RecipeType;Lnet/minecraft/world/inventory/RecipeBookType;ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/Container;Lnet/minecraft/world/inventory/ContainerData;)V", at = @At("RETURN")) - private void inventory$attachContainerMenu(final MenuType $$0, final RecipeType $$1, final RecipeBookType $$2, final int $$3, final Inventory $$4, - final Container $$5, final ContainerData $$6, final CallbackInfo ci) { - if ($$4 instanceof final TrackedMenuBridge trackedMenu) { + @Inject( + method = "(Lnet/minecraft/world/inventory/MenuType;Lnet/minecraft/world/item/crafting/RecipeType;Lnet/minecraft/resources/ResourceKey;Lnet/minecraft/world/inventory/RecipeBookType;ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/Container;Lnet/minecraft/world/inventory/ContainerData;)V", + at = @At("RETURN")) + private void inventory$attachContainerMenu( + final MenuType $$0, final RecipeType $$1, final ResourceKey $$2, + final RecipeBookType $$3, final int $$4, final Inventory inventory, final Container container, final ContainerData $$7, + final CallbackInfo ci) { + if (inventory instanceof final TrackedMenuBridge trackedMenu) { trackedMenu.bridge$trackContainerMenu((AbstractContainerMenu) (Object) this); } - if ($$5 instanceof final TrackedMenuBridge trackedMenu) { + if (container instanceof final TrackedMenuBridge trackedMenu) { trackedMenu.bridge$trackContainerMenu((AbstractContainerMenu) (Object) this); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/CraftingMenuMixin_TrackedMenuBridge_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/CraftingMenuMixin_TrackedMenuBridge_Inventory.java index 33dd9c1078e..1f06cc385b0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/CraftingMenuMixin_TrackedMenuBridge_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/CraftingMenuMixin_TrackedMenuBridge_Inventory.java @@ -27,24 +27,15 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerLevelAccess; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.CraftingMenu; -import net.minecraft.world.inventory.ResultContainer; -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.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.world.inventory.container.TrackedMenuBridge; @Mixin(CraftingMenu.class) -public abstract class CraftingMenuMixin_TrackedMenuBridge_Inventory { - - // @formatter:off - @Shadow @Final private CraftingContainer craftSlots; - @Shadow @Final private ResultContainer resultSlots; - // @formatter:on +public abstract class CraftingMenuMixin_TrackedMenuBridge_Inventory extends AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory { @Inject(method = "(ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/inventory/ContainerLevelAccess;)V", at = @At("RETURN")) private void inventory$attachContainerMenu(final int $$0, final Inventory $$1, final ContainerLevelAccess $$2, final CallbackInfo ci) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/InventoryMenuMixin_TrackedMenuBridge_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/InventoryMenuMixin_TrackedMenuBridge_Inventory.java index 624eb0e6007..088b78c8386 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/InventoryMenuMixin_TrackedMenuBridge_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/InventoryMenuMixin_TrackedMenuBridge_Inventory.java @@ -27,24 +27,15 @@ 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.CraftingContainer; import net.minecraft.world.inventory.InventoryMenu; -import net.minecraft.world.inventory.ResultContainer; -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.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.world.inventory.container.TrackedMenuBridge; @Mixin(InventoryMenu.class) -public abstract class InventoryMenuMixin_TrackedMenuBridge_Inventory { - - // @formatter:off - @Shadow @Final private CraftingContainer craftSlots; - @Shadow @Final private ResultContainer resultSlots; - // @formatter:on +public abstract class InventoryMenuMixin_TrackedMenuBridge_Inventory extends AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory { @Inject(method = "", at = @At("RETURN")) private void inventory$attachContainerMenu(final Inventory $$0, final boolean $$1, final Player $$2, final CallbackInfo ci) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/ItemCombinerMenuMixin_TrackedMenuBridge_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/ItemCombinerMenuMixin_TrackedMenuBridge_Inventory.java index d5ac16172a7..d24d110bd99 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/ItemCombinerMenuMixin_TrackedMenuBridge_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/ItemCombinerMenuMixin_TrackedMenuBridge_Inventory.java @@ -29,9 +29,9 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.inventory.ItemCombinerMenu; +import net.minecraft.world.inventory.ItemCombinerMenuSlotDefinition; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.ResultContainer; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -49,7 +49,8 @@ public abstract class ItemCombinerMenuMixin_TrackedMenuBridge_Inventory { // @formatter:on @Inject(method = "", at = @At("RETURN")) - private void inventory$attachContainerMenu(final @Nullable MenuType $$0, final int $$1, final Inventory $$2, final ContainerLevelAccess $$3, final CallbackInfo ci) { + private void inventory$attachContainerMenu( + MenuType $$0, int $$1, Inventory $$2, ContainerLevelAccess $$3, ItemCombinerMenuSlotDefinition $$4, CallbackInfo ci) { if ($$2 instanceof final TrackedMenuBridge trackedMenu) { trackedMenu.bridge$trackContainerMenu((AbstractContainerMenu) (Object) this); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/movementcheck/server/network/ServerGamePacketListenerImplMixin_MovementCheck.java b/src/mixins/java/org/spongepowered/common/mixin/movementcheck/server/network/ServerGamePacketListenerImplMixin_MovementCheck.java index 33baee1c932..acb2835c33a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/movementcheck/server/network/ServerGamePacketListenerImplMixin_MovementCheck.java +++ b/src/mixins/java/org/spongepowered/common/mixin/movementcheck/server/network/ServerGamePacketListenerImplMixin_MovementCheck.java @@ -42,7 +42,7 @@ public abstract class ServerGamePacketListenerImplMixin_MovementCheck { @ModifyConstant(method = "handleMovePlayer", constant = @Constant(floatValue = 100.0F, ordinal = 0), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;isFallFlying()Z", ordinal = 0), - to = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;isSingleplayerOwner()Z", ordinal = 0) + to = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;getBoundingBox()Lnet/minecraft/world/phys/AABB;", ordinal = 0) ) ) private float movementCheck$onMovedTooQuickly(final float value) { @@ -55,7 +55,7 @@ public abstract class ServerGamePacketListenerImplMixin_MovementCheck { @ModifyConstant(method = "handleMovePlayer", constant = @Constant(doubleValue = 0.0625D, ordinal = 0), slice = @Slice( - from = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;isChangingDimension()Z", ordinal = 1), + from = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;isChangingDimension()Z", ordinal = 0), to = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;isSleeping()Z", ordinal = 1) ) ) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java index d868c48c8f8..894d7e8a63d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java @@ -60,7 +60,7 @@ public abstract class ChunkMapMixin_Tracker { return exception; } - @Redirect(method = "lambda$prepareTickingChunk$27", + @Redirect(method = "lambda$prepareTickingChunk$25", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;startTickingChunk(Lnet/minecraft/world/level/chunk/LevelChunk;)V")) private void tracker$wrapUnpackTicks(final ServerLevel level, final LevelChunk chunk) { if (!PhaseTracker.SERVER.onSidedThread()) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerChunkCacheMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerChunkCacheMixin_Tracker.java index 7ab99989ace..4551170d435 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerChunkCacheMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerChunkCacheMixin_Tracker.java @@ -26,6 +26,7 @@ import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.MobCategory; import net.minecraft.world.level.NaturalSpawner; import net.minecraft.world.level.chunk.LevelChunk; import org.checkerframework.checker.nullness.qual.NonNull; @@ -36,33 +37,33 @@ import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.phase.generation.GenerationPhase; +import java.util.List; + @Mixin(ServerChunkCache.class) public abstract class ServerChunkCacheMixin_Tracker { @Redirect( - method = "tickChunks", + method = "tickChunks(Lnet/minecraft/util/profiling/ProfilerFiller;JLjava/util/List;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/NaturalSpawner;spawnForChunk(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/LevelChunk;Lnet/minecraft/world/level/NaturalSpawner$SpawnState;ZZZ)V" + target = "Lnet/minecraft/world/level/NaturalSpawner;spawnForChunk(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/LevelChunk;Lnet/minecraft/world/level/NaturalSpawner$SpawnState;Ljava/util/List;)V" ) ) private void tracker$wrapEntitySpawner( final ServerLevel serverWorld, final LevelChunk targetChunk, - final NaturalSpawner.SpawnState manager, - final boolean something, - final boolean somethingElse, - final boolean somethingLast + final NaturalSpawner.SpawnState spawnState, + final List mobCategories ) { try (final PhaseContext<@NonNull ?> context = GenerationPhase.State.WORLD_SPAWNER_SPAWNING.createPhaseContext(PhaseTracker.SERVER) .world(serverWorld)) { context.buildAndSwitch(); - NaturalSpawner.spawnForChunk(serverWorld, targetChunk, manager, something, somethingElse, somethingLast); + NaturalSpawner.spawnForChunk(serverWorld, targetChunk, spawnState, mobCategories); } } @Redirect( - method = "tickChunks", + method = "tickChunks(Lnet/minecraft/util/profiling/ProfilerFiller;JLjava/util/List;)V", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;tickCustomSpawners(ZZ)V" diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java index 970ac0fd2b3..8c6797c20fc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java @@ -26,14 +26,22 @@ import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.particles.ParticleOptions; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; import net.minecraft.util.RandomSource; +import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.BlockEventData; import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.ExplosionDamageCalculator; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ServerExplosion; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.TickingBlockEntity; import net.minecraft.world.level.block.piston.PistonBaseBlock; @@ -48,6 +56,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.entity.BlockEntity; +import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.SpongeEventFactory; @@ -55,9 +64,8 @@ import org.spongepowered.api.event.world.ExplosionEvent; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.LocatableBlock; -import org.spongepowered.asm.mixin.Final; +import org.spongepowered.api.world.server.ServerWorld; 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.Redirect; @@ -66,8 +74,10 @@ import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.TrackableBridge; +import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.bridge.server.level.ServerLevelBridge; import org.spongepowered.common.bridge.world.TrackedWorldBridge; +import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.bridge.world.level.LevelBridge; import org.spongepowered.common.bridge.world.level.TrackableBlockEventDataBridge; import org.spongepowered.common.bridge.world.level.block.state.BlockStateBridge; @@ -99,6 +109,7 @@ import org.spongepowered.common.event.tracking.context.transaction.pipeline.PipelineCursor; import org.spongepowered.common.event.tracking.context.transaction.pipeline.TileEntityPipeline; import org.spongepowered.common.event.tracking.context.transaction.pipeline.WorldPipeline; +import org.spongepowered.common.event.tracking.phase.general.GeneralPhase; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.mixin.tracker.world.level.LevelMixin_Tracker; import org.spongepowered.common.util.Constants; @@ -111,14 +122,10 @@ import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; -import java.util.function.Function; @Mixin(ServerLevel.class) public abstract class ServerLevelMixin_Tracker extends LevelMixin_Tracker implements TrackedWorldBridge { - // @formatting:off - @Shadow @Final List players; - // @formatting:on @Redirect( // This normally would target this.entityTickList.forEach((var2x) -> @@ -162,9 +169,9 @@ public abstract class ServerLevelMixin_Tracker extends LevelMixin_Tracker implem @Redirect(method = "tickFluid(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/material/Fluid;)V", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/material/FluidState;tick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V")) - private void tracker$wrapFluidTick(final FluidState fluidState, final net.minecraft.world.level.Level level, final BlockPos pos) { - TrackingUtil.updateTickFluid(this, fluidState, pos); + target = "Lnet/minecraft/world/level/material/FluidState;tick(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) + private void tracker$wrapFluidTick(final FluidState fluidState, final ServerLevel level, final BlockPos pos, final BlockState blockState) { + TrackingUtil.updateTickFluid(this, fluidState, pos, blockState); } private ScheduledTick tracker$createTick(final BlockPos pos, final T type, final int triggerTick, final TickPriority priority) { @@ -222,10 +229,10 @@ public void scheduleTick(final BlockPos pos, final Fluid fluid, final int trigge @Redirect(method = "tickChunk(Lnet/minecraft/world/level/chunk/LevelChunk;I)V", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/material/FluidState;randomTick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/util/RandomSource;)V" + target = "Lnet/minecraft/world/level/material/FluidState;randomTick(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/core/BlockPos;Lnet/minecraft/util/RandomSource;)V" ) ) - private void tracker$wrapFluidRandomTick(final FluidState fluidState, final net.minecraft.world.level.Level worldIn, final BlockPos pos, final RandomSource random) { + private void tracker$wrapFluidRandomTick(final FluidState fluidState, final ServerLevel worldIn, final BlockPos pos, final RandomSource random) { TrackingUtil.randomTickFluid(this, fluidState, pos, this.random); } @@ -329,81 +336,102 @@ public void scheduleTick(final BlockPos pos, final Fluid fluid, final int trigge return list.add(blockEventData); } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public Explosion tracker$triggerInternalExplosion(org.spongepowered.api.world.explosion.Explosion explosion, - final Function> contextCreator) { - // Sponge start - final Explosion originalExplosion = (Explosion) explosion; + @Redirect(method = "explode", at = @At(value = "NEW", + target = "(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;Lnet/minecraft/world/phys/Vec3;FZLnet/minecraft/world/level/Explosion$BlockInteraction;)Lnet/minecraft/world/level/ServerExplosion;")) + private ServerExplosion tracker$onExplode(final ServerLevel $$0, final Entity entity, final DamageSource $$2, + final ExplosionDamageCalculator $$3, final Vec3 $$4, final float radius, final boolean $$6, + final Explosion.BlockInteraction blockInteraction) { + final var cannotGrief = entity instanceof GrieferBridge grieferBridge && !grieferBridge.bridge$canGrief(); + var finalRadius = radius; + if (entity instanceof ExplosiveBridge bridge) { + finalRadius = bridge.bridge$getExplosionRadius().orElse(finalRadius); + } + + return new ServerExplosion($$0, entity, $$2, $$3, $$4, finalRadius, $$6, cannotGrief ? Explosion.BlockInteraction.KEEP : blockInteraction); + } + + private org.spongepowered.api.world.explosion.Explosion tracker$apiExplosion; + + @Redirect(method = "explode", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/ServerExplosion;explode()V")) + private void tracker$onExplode(final ServerExplosion instance) { + var mcExplosion = instance; + final var entity = instance.getDirectSourceEntity(); + // TODO entity can be null, what is our API explosive then? + // TODO API explosive can be smth. that is not an entity? + final var thisWorld = (ServerWorld) this; + + final var explosionBuilder = org.spongepowered.api.world.explosion.Explosion.builder().from((org.spongepowered.api.world.explosion.Explosion) mcExplosion); + + Explosive apiExplosive = (Explosive) entity; + final var detonateEvent = SpongeEventFactory.createDetonateExplosiveEvent(PhaseTracker.getCauseStackManager().currentCause(), + explosionBuilder, apiExplosive, (org.spongepowered.api.world.explosion.Explosion) instance); + if (Sponge.eventManager().post(detonateEvent)) { + this.tracker$cancelExplosionEffects(entity); + return; + } + + // Build the explosion from event + var apiExplosion = detonateEvent.explosionBuilder().build(); + if (apiExplosion.radius() <= 0) { + this.tracker$cancelExplosionEffects(entity); + return; + } + if (ShouldFire.EXPLOSION_EVENT_PRE) { // Set up the pre event - final ExplosionEvent.Pre - event = - SpongeEventFactory.createExplosionEventPre( - PhaseTracker.SERVER.currentCause(), - explosion, ((org.spongepowered.api.world.server.ServerWorld) this)); + final ExplosionEvent.Pre event = + SpongeEventFactory.createExplosionEventPre(PhaseTracker.SERVER.currentCause(), apiExplosion, thisWorld); if (SpongeCommon.post(event)) { - return (Explosion) explosion; + this.tracker$cancelExplosionEffects(entity); + return; } - explosion = event.explosion(); - } - final Explosion mcExplosion; - try { - // Since we already have the API created implementation Explosion, let's use it. - mcExplosion = (Explosion) explosion; - } catch (final Exception e) { - new org.spongepowered.asm.util.PrettyPrinter(60).add("Explosion not compatible with this implementation").centre().hr() - .add("An explosion that was expected to be used for this implementation does not") - .add("originate from this implementation.") - .add(e) - .trace(); - return originalExplosion; - } - - try (final PhaseContext<@NonNull ?> ignored = contextCreator.apply(mcExplosion) - .source(((Optional) explosion.sourceExplosive()).orElse(this))) { - ignored.buildAndSwitch(); - final boolean damagesTerrain = explosion.shouldBreakBlocks(); - // Sponge End + + try { + // Since we already have the API created implementation Explosion, let's use it. + mcExplosion = (ServerExplosion) event.explosion(); + apiExplosion = event.explosion(); + } catch (final ClassCastException e) { + new org.spongepowered.asm.util.PrettyPrinter(60).add("Explosion not compatible with this implementation").centre().hr() + .add("An explosion that was expected to be used for this implementation does not originate from this implementation.") + .trace(); + mcExplosion = (ServerExplosion) detonateEvent.explosionBuilder().build(); + } + } + + try (final PhaseContext<@NonNull ?> ctx = GeneralPhase.State.EXPLOSION.createPhaseContext(PhaseTracker.SERVER).explosion(mcExplosion) + .source(((Optional) apiExplosion.sourceExplosive()).orElse(this))) { + ctx.buildAndSwitch(); mcExplosion.explode(); - mcExplosion.finalizeExplosion(true); + } - if (!damagesTerrain) { - mcExplosion.clearToBlow(); - } + this.tracker$apiExplosion = apiExplosion; + } - // Sponge Start - Don't send explosion packets, they're spammy, we can replicate it on the server entirely - /* - for (EntityPlayer entityplayer : this.playerEntities) { - if (entityplayer.getDistanceSq(x, y, z) < 4096.0D) { - ((EntityPlayerMP) entityplayer).connection - .sendPacket(new SPacketExplosion(x, y, z, strength, mcExplosion.getAffectedBlockPositions(), - mcExplosion.getPlayerKnockbackMap().get(entityplayer))); - } - } + /** + * See {@link net.minecraft.client.multiplayer.ClientPacketListener#handleExplosion} for client side handling + */ + @Redirect(method = "explode", at = @At(value = "INVOKE", + target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;send(Lnet/minecraft/network/protocol/Packet;)V")) + private void tracker$onClientboundExplodePacket(final ServerGamePacketListenerImpl instance, final Packet packet) { + final var originalPacket = (ClientboundExplodePacket) packet; + ((ServerLevelBridge) this).bridge$handleExplosionPacket(instance, this.tracker$apiExplosion, originalPacket); + } - */ - // Use the knockback map and set velocities, since the explosion packet isn't sent, we need to replicate - // the players being moved. - for (final ServerPlayer playerEntity : this.players) { - final Vec3 knockback = mcExplosion.getHitPlayers().get(playerEntity); - if (knockback != null) { - // In Vanilla, doExplosionB always updates the 'motion[xyz]' fields for every entity in range. - // However, this field is completely ignored for players (since 'velocityChanged') is never set, and - // a completely different value is sent through 'SPacketExplosion'. - - // To replicate this behavior, we manually send a velocity packet. It's critical that we don't simply - // add to the 'motion[xyz]' fields, as that will end up using the value set by 'doExplosionB', which must be - // ignored. - playerEntity.connection.send(new ClientboundSetEntityMotionPacket(playerEntity.getId(), new Vec3(knockback.x, knockback.y, knockback.z))); - } - } - // Sponge End + @Inject(method = "explode", at = @At(value = "RETURN")) + private void tracker$afterExplodeCleanup(final Entity $$0, final DamageSource $$1, + final ExplosionDamageCalculator $$2, final double $$3, final double $$4, final double $$5, final float $$6, + final boolean $$7, final Level.ExplosionInteraction $$8, final ParticleOptions $$9, final ParticleOptions $$10, + final Holder $$11, final CallbackInfo ci) { + this.tracker$apiExplosion = null; + } + private void tracker$cancelExplosionEffects(final Entity entity) { + // TODO cancel effects + if (entity instanceof ExplosiveBridge explosiveBridge) { + explosiveBridge.bridge$cancelExplosion(); } - // Sponge End - return mcExplosion; } @Override @@ -619,7 +647,7 @@ public boolean destroyBlock(final BlockPos pos, final boolean doDrops, @Nullable final TileEntityPipeline pipeline = TileEntityPipeline.kickOff((ServerLevel) (Object) this, immutable) .addEffect(RemoveTileEntityFromChunkEffect.getInstance()) .build(); - pipeline.processEffects(current, new PipelineCursor(tileentity.getBlockState(), 0,immutable, tileentity, (Entity) null, Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT)); + pipeline.processEffects(current, new PipelineCursor(tileentity.getBlockState(), immutable, tileentity, (Entity) null, Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT)); return; } super.shadow$removeBlockEntity(immutable); @@ -650,7 +678,7 @@ public boolean destroyBlock(final BlockPos pos, final boolean doDrops, @Nullable final TileEntityPipeline pipeline = TileEntityPipeline.kickOff((ServerLevel) (Object) this, immutable) .addEffect(SetAndRegisterBlockEntityToLevelChunk.getInstance()) .build(); - pipeline.processEffects(current, new PipelineCursor(proposed.getBlockState(), 0,immutable, proposed, (Entity) null, Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT)); + pipeline.processEffects(current, new PipelineCursor(proposed.getBlockState(), immutable, proposed, (Entity) null, Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT)); return; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java index 91e3465fc9a..06fb1b321cc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java @@ -30,7 +30,6 @@ import net.minecraft.server.level.ServerPlayerGameMode; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; -import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.MenuProvider; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; @@ -82,7 +81,7 @@ public abstract class ServerPlayerGameModeMixin_Tracker { @Inject(method = "useItem", cancellable = true, at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/item/ItemCooldowns;isOnCooldown(Lnet/minecraft/world/item/Item;)Z")) + target = "Lnet/minecraft/world/item/ItemCooldowns;isOnCooldown(Lnet/minecraft/world/item/ItemStack;)Z")) public void impl$callInteractItemSecondary(final ServerPlayer player, final Level level, final ItemStack stack, final InteractionHand hand, final CallbackInfoReturnable cir ) { @@ -137,14 +136,14 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl final boolean flag1 = playerIn.isSecondaryUseActive() && flag; final ItemStack copiedStack = stackIn.copy(); if (useBlock != Tristate.FALSE && !flag1) { // Sponge check useBlock - final ItemInteractionResult result = blockstate.useItemOn(playerIn.getItemInHand(handIn), worldIn, playerIn, handIn, blockRaytraceResultIn); + final InteractionResult result = blockstate.useItemOn(playerIn.getItemInHand(handIn), worldIn, playerIn, handIn, blockRaytraceResultIn); if (result.consumesAction()) { CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(playerIn, blockpos, copiedStack); - return result.result(); + return result; } - if (result == ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION && handIn == InteractionHand.MAIN_HAND) { + if (result instanceof InteractionResult.TryEmptyHandInteraction && handIn == InteractionHand.MAIN_HAND) { final AbstractContainerMenu lastOpenContainer = playerIn.containerMenu; // Sponge final InteractionResult result2 = blockstate.useWithoutItem(worldIn, playerIn, blockRaytraceResultIn); if (result2.consumesAction()) { @@ -169,7 +168,7 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl } } - if (!stackIn.isEmpty() && !playerIn.getCooldowns().isOnCooldown(stackIn.getItem())) { + if (!stackIn.isEmpty() && !playerIn.getCooldowns().isOnCooldown(stackIn)) { // Sponge start if (useItem == Tristate.FALSE) { ((ServerPlayerGameModeBridge) this).bridge$setInteractBlockRightClickCancelled(true); diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerMixin_Tracker.java index 9ffbd536d43..0837a8cffc3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerMixin_Tracker.java @@ -27,7 +27,6 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.event.CauseStackManager; @@ -59,12 +58,12 @@ public abstract class ServerPlayerMixin_Tracker extends PlayerMixin_Tracker { method = "drop(Lnet/minecraft/world/item/ItemStack;ZZ)Lnet/minecraft/world/entity/item/ItemEntity;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/entity/player/Player;drop(Lnet/minecraft/world/item/ItemStack;ZZ)Lnet/minecraft/world/entity/item/ItemEntity;" + target = "Lnet/minecraft/server/level/ServerPlayer;createItemStackToDrop(Lnet/minecraft/world/item/ItemStack;ZZ)Lnet/minecraft/world/entity/item/ItemEntity;" ) ) @Nullable private ItemEntity tracker$throwItemDrop( - final Player thisPlayer, final ItemStack droppedItem, final boolean dropAround, final boolean traceItem + final ServerPlayer thisPlayer, final ItemStack droppedItem, final boolean dropAround, final boolean traceItem ) { if (droppedItem.isEmpty()) { return null; diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityMixin_Tracker.java index 5746dda6774..4647439094d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityMixin_Tracker.java @@ -26,6 +26,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; +import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -88,16 +89,16 @@ public abstract class EntityMixin_Tracker implements DelegatingConfigTrackableBr protected @MonotonicNonNull EffectTransactor tracker$dropsTransactor = null; @Inject( - method = "spawnAtLocation(Lnet/minecraft/world/item/ItemStack;F)Lnet/minecraft/world/entity/item/ItemEntity;", + method = "spawnAtLocation(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/item/ItemStack;F)Lnet/minecraft/world/entity/item/ItemEntity;", at = @At("HEAD") ) - private void tracker$logEntityDropTransactionIfNecessary(final ItemStack stack, final float offsetY, - final CallbackInfoReturnable cir) { + private void tracker$logEntityDropTransactionIfNecessary(final ServerLevel level, final ItemStack stack, final float offsetY, + final CallbackInfoReturnable cir) { final PhaseTracker instance = PhaseTracker.SERVER; if (!instance.onSidedThread()) { return; } - if (((LevelBridge) this.shadow$level()).bridge$isFake()) { + if (((LevelBridge) level).bridge$isFake()) { return; } final PhaseContext<@NonNull ?> context = instance.getPhaseContext(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityTypeMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityTypeMixin_Tracker.java index 1c1a0fbc372..b4e1f3b7b37 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityTypeMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/EntityTypeMixin_Tracker.java @@ -26,6 +26,7 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.entity.EntityType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -37,14 +38,14 @@ @Mixin(EntityType.class) public abstract class EntityTypeMixin_Tracker implements RegistryBackedTrackableBridge> { - @Redirect(method = "register", + @Redirect(method = "register(Lnet/minecraft/resources/ResourceKey;Lnet/minecraft/world/entity/EntityType$Builder;)Lnet/minecraft/world/entity/EntityType;", at = @At( value = "INVOKE", - target = "Lnet/minecraft/core/Registry;register(Lnet/minecraft/core/Registry;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;" + target = "Lnet/minecraft/core/Registry;register(Lnet/minecraft/core/Registry;Lnet/minecraft/resources/ResourceKey;Ljava/lang/Object;)Ljava/lang/Object;" ) ) - private static Object impl$initializeTrackerState(final Registry registry, final String key, final Object toRegister) { - final Object registered = Registry.register(registry, key, toRegister); + private static V impl$initializeTrackerState(final Registry registry, final ResourceKey key, final V toRegister) { + final V registered = Registry.register(registry, key, toRegister); final RegistryBackedTrackableBridge> trackableBridge = (RegistryBackedTrackableBridge>) toRegister; trackableBridge.bridge$refreshTrackerStates(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/LivingEntityMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/LivingEntityMixin_Tracker.java index 6f7e33dd68a..43ffb8ba24c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/LivingEntityMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/LivingEntityMixin_Tracker.java @@ -120,7 +120,7 @@ public abstract class LivingEntityMixin_Tracker extends EntityMixin_Tracker { * @reason Instead of inlining the onDeath method with the main mixin, we can "toggle" * the usage of the death state control in the tracker mixin. */ - @Redirect(method = "hurt", + @Redirect(method = "hurtServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;die(Lnet/minecraft/world/damagesource/DamageSource;)V" ) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java deleted file mode 100644 index 747a96b39a1..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.tracker.world.level; - -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.Util; -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.RandomSource; -import net.minecraft.world.level.Explosion; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.BaseFireBlock; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.bridge.world.TrackedWorldBridge; -import org.spongepowered.common.bridge.world.level.ExplosionBridge; -import org.spongepowered.common.event.tracking.BlockChangeFlagManager; -import org.spongepowered.common.event.tracking.PhaseContext; -import org.spongepowered.common.event.tracking.PhaseTracker; -import org.spongepowered.common.event.tracking.context.transaction.effect.AddBlockLootDropsEffect; -import org.spongepowered.common.event.tracking.context.transaction.effect.ExplodeBlockEffect; -import org.spongepowered.common.event.tracking.context.transaction.effect.SpawnDestructBlocksEffect; -import org.spongepowered.common.event.tracking.context.transaction.effect.WorldBlockChangeCompleteEffect; -import org.spongepowered.common.event.tracking.context.transaction.pipeline.WorldPipeline; -import org.spongepowered.common.util.Constants; - -@Mixin(Explosion.class) -public abstract class ExplosionMixin_Tracker { - - @Shadow @Final private Level level; - @Shadow @Final private double x; - @Shadow @Final private double y; - @Shadow @Final private double z; - @Shadow @Final private Explosion.BlockInteraction blockInteraction; - @Shadow @Final private float radius; - @Shadow @Final private ObjectArrayList toBlow; - - @Shadow @Final private boolean fire; - @Shadow @Final private RandomSource random; - - /** - * @author gabziou - * @author zidane - * @reason Run explosion logic through tracking - */ - @Overwrite - public void finalizeExplosion(final boolean spawnParticles) { - // Sponge Start - In Sponge, we no longer call doExplosionB client-side (kills client perf) - if (this.level.isClientSide) { - return; - } - // Sponge End - - // Sponge Start - Send the sound packet down. We must do this as we do not call doExplosionB client-side - this.level.playSound(null, this.x, this.y, this.z, SoundEvents.GENERIC_EXPLODE.value(), SoundSource.BLOCKS, 4.0F, - (1.0F + (this.level.random.nextFloat() - this.level.random.nextFloat()) * 0.2F) * 0.7F); - // Sponge End - - final boolean flag = this.blockInteraction != Explosion.BlockInteraction.KEEP; - if (spawnParticles) { - if (!(this.radius < 2.0F) && (flag || ((ExplosionBridge) this).bridge$getShouldDamageBlocks())) { - // Sponge Start - Use WorldServer methods since we prune the explosion packets - // to avoid spamming/lagging the client out when some ~idiot~ decides to explode - // hundreds of explosions at once - if (this.level instanceof ServerLevel) { - ((ServerLevel) this.level).sendParticles(ParticleTypes.EXPLOSION_EMITTER, this.x, this.y, this.z, 1, 0, 0, 0, 0.1D); - } else { - this.level.addParticle(ParticleTypes.EXPLOSION_EMITTER, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); - } - // Sponge End - } else { - // Sponge Start - Use WorldServer methods since we prune the explosion packets - // to avoid spamming/lagging the client out when some ~idiot~ decides to explode - // hundreds of explosions at once - if (this.level instanceof ServerLevel) { - ((ServerLevel) this.level).sendParticles(ParticleTypes.EXPLOSION, this.x, this.y, this.z, 1, 0, 0, 0, 0.1D); - } else { - this.level.addParticle(ParticleTypes.EXPLOSION, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); - } - // Sponge End - } - } - - if (flag) { - // Sponge Start - Forward changes through a WorldPipeline to associate side effects - // Vanilla - uses a list of itemstacks to do a bunch of pre-merging - // ObjectArrayList> objectarraylist = new ObjectArrayList<>(); - Util.shuffle(this.toBlow, this.level.random); - - for (final BlockPos blockpos : this.toBlow) { - final BlockState blockstate = this.level.getBlockState(blockpos); - // Block block = blockstate.getBlock(); // Sponge - we don't use this - if (!blockstate.isAir()) { - final BlockPos blockpos1 = blockpos.immutable(); - this.level.getProfiler().push("explosion_blocks"); - - // Sponge - All of this is forwarded to the effects - // if (block.canDropFromExplosion(this) && this.level instanceof ServerLevel) { - // BlockEntity var6 = block.isEntityBlock() ? this.level.getBlockEntity(blockpos) : null; - // LootContext.Builder lootcontext$builder = (new LootContext.Builder((ServerLevel)this.level)).withRandom(this.level.rand).withParameter( - // LootParameters.ORIGIN, Vec3.atCenterOf(blockpos)).withParameter(LootParameters.TOOL, ItemStack.EMPTY).withNullableParameter(LootParameters.BLOCK_ENTITY, var6).withNullableParameter(LootParameters.THIS_ENTITY, this.source); - // if (this.blockInteraction == Explosion.BlockInteraction.DESTROY) { - // lootcontext$builder.withParameter(LootParameters.EXPLOSION_RADIUS, this.radius); - // } - - // var3.getDrops(var7).forEach((param2) -> addBlockDrops(var1, param2, var5)); - // } - - //this.level.setBlock(blockpos, Blocks.AIR.defaultState(), 3); - //block.onExplosionDestroy(this.world, blockpos, this); - - final PhaseContext<@NonNull ?> context = PhaseTracker.getInstance().getPhaseContext(); - ((TrackedWorldBridge) this.level).bridge$startBlockChange(blockpos1, Blocks.AIR.defaultBlockState(), 3) - .ifPresent(builder -> { - final WorldPipeline build = builder - .addEffect(AddBlockLootDropsEffect.getInstance()) - .addEffect(ExplodeBlockEffect.getInstance()) - .addEffect(SpawnDestructBlocksEffect.getInstance()) - .addEffect(WorldBlockChangeCompleteEffect.getInstance()) - .build(); - build.processEffects(context, blockstate, Blocks.AIR.defaultBlockState(), blockpos1, - null, - BlockChangeFlagManager.fromNativeInt(3), - Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT); - }); - // Sponge End - this.level.getProfiler().pop(); - } - } - // Sponge Start - This is built into the SpawnDestructBlocksEffect - // for(Pair var8 : objectarraylist) { - // Block.popResource(this.level, var8.getSecond(), var8.getFirst()); - // } - // Sponge End - } - - if (this.fire) { - for(final BlockPos blockpos2 : this.toBlow) { - if (this.random.nextInt(3) == 0 && this.level.getBlockState(blockpos2).isAir() && this.level.getBlockState(blockpos2.below()).isSolidRender(this.level, blockpos2.below())) { - this.level.setBlockAndUpdate(blockpos2, BaseFireBlock.getState(this.level, blockpos2)); - } - } - } - - } -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelAccessorMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelAccessorMixin_Tracker.java deleted file mode 100644 index 4ae817d3e95..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelAccessorMixin_Tracker.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.tracker.world.level; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.storage.LevelData; -import net.minecraft.world.ticks.LevelTickAccess; -import net.minecraft.world.ticks.TickPriority; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(LevelAccessor.class) -public interface LevelAccessorMixin_Tracker { - - // @formatter:off - @Shadow LevelData shadow$getLevelData(); - @Shadow long shadow$nextSubTickCount(); - @Shadow LevelTickAccess shadow$getBlockTicks(); - @Shadow LevelTickAccess shadow$getFluidTicks(); - - // Shadow methods to be overridden in ServerLevelMixin_Tracker - @Shadow void shadow$scheduleTick(BlockPos pos, Block block, int $$2, TickPriority priority); - @Shadow void shadow$scheduleTick(BlockPos pos, Block block, int $$2); - @Shadow void shadow$scheduleTick(BlockPos pos, Fluid fluid, int $$2, TickPriority priority); - @Shadow void shadow$scheduleTick(BlockPos pos, Fluid fluid, int $$2); - // @formatter:on - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelMixin_Tracker.java index c513fc0d26b..8a4441d0352 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/LevelMixin_Tracker.java @@ -73,7 +73,6 @@ public abstract class LevelMixin_Tracker implements LevelBridge, LevelAccessor { @Shadow public abstract FluidState shadow$getFluidState(BlockPos p_204610_1_); // @formatter:on - /** * We introduce the protected method to be overridden in * {@code org.spongepowered.common.mixin.core.world.server.ServerWorldMixin#tracker$wrapTileEntityTick(ITickableTileEntity)} diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ServerExplosionMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ServerExplosionMixin_Tracker.java new file mode 100644 index 00000000000..5f5f71eebca --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ServerExplosionMixin_Tracker.java @@ -0,0 +1,90 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.tracker.world.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Explosion; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ServerExplosion; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.bridge.world.TrackedWorldBridge; +import org.spongepowered.common.event.tracking.BlockChangeFlagManager; +import org.spongepowered.common.event.tracking.PhaseContext; +import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.event.tracking.context.transaction.effect.AddBlockLootDropsEffect; +import org.spongepowered.common.event.tracking.context.transaction.effect.ExplodeBlockEffect; +import org.spongepowered.common.event.tracking.context.transaction.effect.SpawnDestructBlocksEffect; +import org.spongepowered.common.event.tracking.context.transaction.effect.WorldBlockChangeCompleteEffect; +import org.spongepowered.common.event.tracking.context.transaction.pipeline.WorldPipeline; +import org.spongepowered.common.util.Constants; + +import java.util.function.BiConsumer; + +@Mixin(ServerExplosion.class) +public abstract class ServerExplosionMixin_Tracker { + + + // TODO sounds & particles? + + @Redirect(method = "interactWithBlocks", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/Block;popResource(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/item/ItemStack;)V")) + private void tracker$onPopResource(final Level $$0, final BlockPos $$1, final ItemStack $$2) { + // This is built into the SpawnDestructBlocksEffect + // Block.popResource(this.level, $$3.pos, $$3.stack); + } + + + @Redirect(method = "interactWithBlocks", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;onExplosionHit(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/Explosion;Ljava/util/function/BiConsumer;)V")) + private void tracker$onExplosionHit(final BlockState instance, final ServerLevel serverLevel, + final BlockPos blockPos, final Explosion explosion, final BiConsumer biConsumer) { + // this.level.getBlockState($$2).onExplosionHit(this.level, $$2, this, ($$1x, $$2x) -> addOrAppendStack($$1, $$1x, $$2x)); + + // TODO addOrAppendStack? ItemStack pre merging + final PhaseContext<@NonNull ?> context = PhaseTracker.getInstance().getPhaseContext(); + ((TrackedWorldBridge) serverLevel).bridge$startBlockChange(blockPos, Blocks.AIR.defaultBlockState(), 3) + .ifPresent(builder -> { + final WorldPipeline build = builder + .addEffect(AddBlockLootDropsEffect.getInstance()) + .addEffect(ExplodeBlockEffect.getInstance()) + .addEffect(SpawnDestructBlocksEffect.getInstance()) + .addEffect(WorldBlockChangeCompleteEffect.getInstance()) + .build(); + build.processEffects(context, instance, Blocks.AIR.defaultBlockState(), blockPos, + null, + BlockChangeFlagManager.fromNativeInt(3), + Constants.World.DEFAULT_BLOCK_CHANGE_LIMIT); + }); + } + + +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/block/BlockMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/block/BlockMixin_Tracker.java index 3534f5443bb..093ad2e886a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/block/BlockMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/block/BlockMixin_Tracker.java @@ -37,6 +37,7 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; 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; @@ -52,16 +53,12 @@ @Mixin(Block.class) public abstract class BlockMixin_Tracker implements TrackableBlockBridge, RegistryBackedTrackableBridge { - private final boolean tracker$hasNeighborLogicOverridden = ReflectionUtil.isNeighborChangedDeclared(this.getClass()); + @Unique private final boolean tracker$hasEntityInsideLogicOverridden = ReflectionUtil.isEntityInsideDeclared(this.getClass()); + @Unique @Nullable private static EffectTransactor tracker$effectTransactorForDrops = null; - @Override - public boolean bridge$overridesNeighborNotificationLogic() { - return this.tracker$hasNeighborLogicOverridden; - } - @Override public boolean bridge$hasEntityInsideLogic() { return this.tracker$hasEntityInsideLogicOverridden; diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/ChunkSerializerMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/SerializableChunkDataMixin_Tracker.java similarity index 55% rename from src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/ChunkSerializerMixin_Tracker.java rename to src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/SerializableChunkDataMixin_Tracker.java index d33ce42dfdd..50e2973ce6d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/ChunkSerializerMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/chunk/storage/SerializableChunkDataMixin_Tracker.java @@ -27,19 +27,11 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.entity.ai.village.poi.PoiManager; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.storage.ChunkSerializer; -import net.minecraft.world.level.chunk.storage.RegionStorageInfo; +import net.minecraft.world.level.chunk.storage.SerializableChunkData; 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.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; +import org.spongepowered.common.bridge.world.level.chunk.storage.SerializableChunkDataBridge; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.util.Constants; @@ -47,28 +39,37 @@ import java.util.Map; import java.util.function.BiConsumer; -@Mixin(ChunkSerializer.class) -public abstract class ChunkSerializerMixin_Tracker { +@Mixin(SerializableChunkData.class) +public abstract class SerializableChunkDataMixin_Tracker implements SerializableChunkDataBridge { - @Inject(method = "write", at = @At(value = "RETURN")) - private static void impl$writeSpongeLevelData(final ServerLevel param0, final ChunkAccess param1, final CallbackInfoReturnable cir) { - if (!(param1 instanceof LevelChunk)) { - return; - } - final LevelChunkBridge chunk = (LevelChunkBridge) param1; + private Map tracker$shortPlayerPos = null; + private Map tracker$intPlayerPos = null; + + @Override + public void bridge$setTrackerData(final LevelChunk chunkAccess) { + final LevelChunkBridge chunk = (LevelChunkBridge) chunkAccess; if (!chunk.bridge$getTrackedShortPlayerPositions().isEmpty() || !chunk.bridge$getTrackedIntPlayerPositions().isEmpty()) { - final CompoundTag level = cir.getReturnValue(); - final CompoundTag trackedNbt = new CompoundTag(); - final ListTag positions = new ListTag(); - trackedNbt.put(Constants.Sponge.SPONGE_BLOCK_POS_TABLE, positions); - level.put(Constants.Sponge.Data.V2.SPONGE_DATA, trackedNbt); + this.tracker$shortPlayerPos = chunk.bridge$getTrackedShortPlayerPositions(); + this.tracker$intPlayerPos = chunk.bridge$getTrackedIntPlayerPositions(); + } + } - ChunkSerializerMixin_Tracker.impl$writeMap(positions, chunk.bridge$getTrackedShortPlayerPositions(), (nbt, pos) -> nbt.putShort("pos", pos)); - ChunkSerializerMixin_Tracker.impl$writeMap(positions, chunk.bridge$getTrackedIntPlayerPositions(), (nbt, pos) -> nbt.putInt("ipos", pos)); + @Override + public void bridge$writeTrackerData(final CompoundTag level) { + if (this.tracker$intPlayerPos == null && this.tracker$shortPlayerPos == null) { + return; } + final CompoundTag trackedNbt = new CompoundTag(); + final ListTag positions = new ListTag(); + trackedNbt.put(Constants.Sponge.SPONGE_BLOCK_POS_TABLE, positions); + level.put(Constants.Sponge.Data.V2.SPONGE_DATA, trackedNbt); + + SerializableChunkDataMixin_Tracker.tracker$writeMap(positions, this.tracker$shortPlayerPos, (nbt, pos) -> nbt.putShort("pos", pos)); + SerializableChunkDataMixin_Tracker.tracker$writeMap(positions, this.tracker$intPlayerPos, (nbt, pos) -> nbt.putInt("ipos", pos)); } - private static void impl$writeMap(final ListTag positions, final Map map, final BiConsumer consumer) { + + private static void tracker$writeMap(final ListTag positions, final Map map, final BiConsumer consumer) { for (final Map.Entry mapEntry : map.entrySet()) { final T pos = mapEntry.getKey(); final int ownerUniqueIdIndex = mapEntry.getValue().creatorindex; @@ -81,21 +82,17 @@ public abstract class ChunkSerializerMixin_Tracker { } } - @Redirect(method = "read", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/ChunkAccess;setLightCorrect(Z)V")) - private static void impl$readSpongeLevelData(final ChunkAccess chunkAccess, final boolean var1, final ServerLevel param0, final PoiManager param2, final RegionStorageInfo $$2, final ChunkPos param3, final CompoundTag param4) { - if (!(chunkAccess instanceof LevelChunk)) { - return; - } - final CompoundTag spongeData = param4.getCompound(Constants.Sponge.Data.V2.SPONGE_DATA); + @Override + public void bridge$parseTrackerData(final CompoundTag fullTag) { + final CompoundTag spongeData = fullTag.getCompound(Constants.Sponge.Data.V2.SPONGE_DATA); + this.tracker$intPlayerPos = new HashMap<>(); + this.tracker$shortPlayerPos = new HashMap<>(); + if (spongeData.isEmpty()) { return; } - final Map trackedIntPlayerPositions = new HashMap<>(); - final Map trackedShortPlayerPositions = new HashMap<>(); final ListTag list = spongeData.getList(Constants.Sponge.SPONGE_BLOCK_POS_TABLE, 10); - final LevelChunkBridge chunk = (LevelChunkBridge) chunkAccess; for (final Tag tag : list) { final PlayerTracker tracker = new PlayerTracker(); final CompoundTag data = (CompoundTag) tag; @@ -108,13 +105,19 @@ public abstract class ChunkSerializerMixin_Tracker { } if (tracker.notifierIndex != -1 || tracker.creatorindex != -1) { if (isShortPos) { - trackedShortPlayerPositions.put(data.getShort("pos"), tracker); + this.tracker$shortPlayerPos.put(data.getShort("pos"), tracker); } else { - trackedIntPlayerPositions.put(data.getInt("ipos"), tracker); + this.tracker$intPlayerPos.put(data.getInt("ipos"), tracker); } } } - chunk.bridge$setTrackedIntPlayerPositions(trackedIntPlayerPositions); - chunk.bridge$setTrackedShortPlayerPositions(trackedShortPlayerPositions); } + + @Override + public void bridge$readTrackerDataFrom(final LevelChunk levelChunk) { + final LevelChunkBridge chunk = (LevelChunkBridge) levelChunk; + chunk.bridge$setTrackedIntPlayerPositions(this.tracker$intPlayerPos); + chunk.bridge$setTrackedShortPlayerPositions(this.tracker$shortPlayerPos); + } + } diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/redstone/NeighborUpdaterMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/redstone/NeighborUpdaterMixin_Tracker.java index e16d22970e2..05776e94678 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/redstone/NeighborUpdaterMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/redstone/NeighborUpdaterMixin_Tracker.java @@ -31,6 +31,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.redstone.NeighborUpdater; +import net.minecraft.world.level.redstone.Orientation; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; @@ -50,20 +51,12 @@ public interface NeighborUpdaterMixin_Tracker { /** * Logs a transaction to the {@link PhaseContext} for neighbor notifications. Otherwise, * we will fail to create notification events in the API. This avoids a redirect or overwrite - * - * @param level - * @param targetState - * @param targetPos - * @param fromBlock - * @param fromPos - * @param movement - * @param ci */ @Inject(method = "executeUpdate", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;handleNeighborChanged(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/core/BlockPos;Z)V" + target = "Lnet/minecraft/world/level/block/state/BlockState;handleNeighborChanged(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/redstone/Orientation;Z)V" )) - private static void tracker$wrapNeighborUpdateInSideEffect(Level level, BlockState targetState, BlockPos targetPos, Block fromBlock, BlockPos fromPos, boolean movement, CallbackInfo ci) { + private static void tracker$wrapNeighborUpdateInSideEffect(Level level, BlockState targetState, BlockPos targetPos, Block fromBlock, @Nullable Orientation orientation, boolean movement, CallbackInfo ci) { // Sponge start - prepare notification final PhaseContext<@NonNull ?> peek = PhaseTracker.getInstance().getPhaseContext(); if (!(level instanceof ServerLevel serverLevel)) { @@ -76,6 +69,8 @@ public interface NeighborUpdaterMixin_Tracker { targetPos, LevelChunk.EntityCreationType.CHECK ); + + var fromPos = targetPos; // TODO fromPos is gone THIS IS ALMOST CERTAINLY WRONG peek.getTransactor().logNeighborNotification(worldSupplier, fromPos, fromBlock, targetPos, targetState, existingTile); peek.associateNeighborStateNotifier(fromPos, targetState.getBlock(), targetPos, serverLevel, PlayerTracker.Type.NOTIFIER); diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index e370254598e..1a65cdb3432 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -9,35 +9,6 @@ "data.persistence.DataContainerMixin_API", "entity.ai.goal.AbstractGoalMixin_API", "item.merchant.MerchantMixin_API", - "itemstacklike.advancement.DisplayInfo_BuilderMixin_ItemStackLike", - "itemstacklike.block.entity.JukeboxMixin_ItemStackLike", - "itemstacklike.event.cause.entity.damage.DamageModifier_BuilderMixin_ItemStackLike", - "itemstacklike.item.enchantment.EnchantmentTypeMixin_ItemStackLike", - "itemstacklike.item.inventory.ArmorEquipableMixin_ItemStackLike", - "itemstacklike.item.inventory.ContainerMixin_ItemStackLike", - "itemstacklike.item.inventory.EquipableMixin_ItemStackLike", - "itemstacklike.item.inventory.InventoryMixin_ItemStackLike", - "itemstacklike.item.inventory.SlotMixin_ItemStackLike", - "itemstacklike.item.inventory.equipment.EquipmentInventoryMixin_ItemStackLike", - "itemstacklike.item.inventory.slot.FilteringSlotMixin_ItemStackLike", - "itemstacklike.item.inventory.slot.SidedSlotMixin_ItemStackLike", - "itemstacklike.item.inventory.transaction.InventoryTransactionResult_BuilderMixin_ItemStackLike", - "itemstacklike.item.inventory.transaction.SlotTransactionMixin_ItemStackLike", - "itemstacklike.item.inventory.type.GridInventoryMixin_ItemStackLike", - "itemstacklike.item.inventory.type.Inventory2DMixin_ItemStackLike", - "itemstacklike.item.inventory.type.ViewableInventory_Builder_DummyStepMixin_ItemStackLike", - "itemstacklike.item.merchant.TradeOffer_BuilderMixin_ItemStackLike", - "itemstacklike.item.recipe.RecipeManagerMixin_ItemStackLike", - "itemstacklike.item.recipe.cooking.CookingRecipe_Builder_ResultStepMixin_ItemStackLike", - "itemstacklike.item.recipe.cooking.CookingRecipeMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.Ingredient_BuilderMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.IngredientMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.RecipeInput_FactoryMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.ShapedCraftingRecipe_Builder_ResultStepMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.ShapelessCraftingRecipe_Builder_ResultStepMixin_ItemStackLike", - "itemstacklike.item.recipe.crafting.SpecialCraftingRecipe_Builder_ResultStepMixin_ItemStackLike", - "itemstacklike.item.recipe.single.StoneCutterRecipe_Builder_ResultStepMixin_ItemStackLike", - "itemstacklike.item.recipe.smithing.SmithingRecipe_Builder_ResultStepMixin_ItemStackLike", "minecraft.advancements.AdvancementMixin_API", "minecraft.advancements.AdvancementNodeMixin_API", "minecraft.advancements.AdvancementProgressMixin_API", @@ -47,7 +18,7 @@ "minecraft.advancements.CriterionTriggerInstanceMixin_API", "minecraft.advancements.CriterionTriggerMixin_API", "minecraft.advancements.DisplayInfoMixin_API", - "minecraft.block.AbstractBlockMixin_API", + "minecraft.block.BlockBehaviourMixin_API", "minecraft.block.BlockMixin_API", "minecraft.block.BlockSoundGroupMixin_API", "minecraft.commands.CommandSourceStackMixin_API", @@ -145,7 +116,6 @@ "minecraft.world.entity.OwnableEntityMixin_API", "minecraft.world.entity.PathfinderMobMixin_API", "minecraft.world.entity.PortalProcessorMixin_API", - "minecraft.world.entity.PowerableMobMixin_API", "minecraft.world.entity.SaddleableMixin_API", "minecraft.world.entity.TamableAnimalMixin_API", "minecraft.world.entity.TargetingMixin_API", @@ -171,6 +141,7 @@ "minecraft.world.entity.animal.AbstractFishMixin_API", "minecraft.world.entity.animal.AbstractGolemMixin_API", "minecraft.world.entity.animal.AbstractSchoolingFishMixin_API", + "minecraft.world.entity.animal.AgeableWaterCreatureMixin_API", "minecraft.world.entity.animal.AnimalMixin_API", "minecraft.world.entity.animal.BeeMixin_API", "minecraft.world.entity.animal.CatMixin_API", @@ -180,7 +151,7 @@ "minecraft.world.entity.animal.CowMixin_API", "minecraft.world.entity.animal.DolphinMixin_API", "minecraft.world.entity.animal.FlyingAnimalMixin_API", - "minecraft.world.entity.animal.Fox_TypeMixin_API", + "minecraft.world.entity.animal.Fox_VariantMixin_API", "minecraft.world.entity.animal.FoxMixin_API", "minecraft.world.entity.animal.IronGolemMixin_API", "minecraft.world.entity.animal.MushroomCow_MushroomTypeMixin_API", @@ -332,9 +303,8 @@ "minecraft.world.entity.raid.RaidMixin_API", "minecraft.world.entity.vehicle.AbstractMinecartContainerMixin_API", "minecraft.world.entity.vehicle.AbstractMinecartMixin_API", - "minecraft.world.entity.vehicle.Boat_TypeMixin_API", - "minecraft.world.entity.vehicle.BoatMixin_API", - "minecraft.world.entity.vehicle.ChestBoatMixin_API", + "minecraft.world.entity.vehicle.AbstractBoatMixin_API", + "minecraft.world.entity.vehicle.AbstractChestBoatMixin_API", "minecraft.world.entity.vehicle.MinecartChestMixin_API", "minecraft.world.entity.vehicle.MinecartCommandBlockMixin_API", "minecraft.world.entity.vehicle.MinecartFurnaceMixin_API", @@ -352,7 +322,7 @@ "minecraft.world.item.ItemStackMixin_API", "minecraft.world.item.JukeboxSongMixin_API", "minecraft.world.item.RarityMixin_API", - "minecraft.world.item.TiersMixin_API", + "minecraft.world.item.ToolMaterialMixin_API", "minecraft.world.item.alchemy.PotionMixin_API", "minecraft.world.item.component.FireworkExplosionMixin_API", "minecraft.world.item.component.Tool_RuleMixin_API", @@ -372,7 +342,6 @@ "minecraft.world.item.trading.MerchantOfferMixin_API", "minecraft.world.level.BlockGetterMixin_API", "minecraft.world.level.EntityGetterMixin_API", - "minecraft.world.level.ExplosionMixin_API", "minecraft.world.level.GameRules_KeyMixin_API", "minecraft.world.level.GameTypeMixin_API", "minecraft.world.level.LevelAccessorMixin_API", @@ -380,6 +349,7 @@ "minecraft.world.level.LevelReaderMixin_API", "minecraft.world.level.LevelWriterMixin_API", "minecraft.world.level.LightLayerMixin_API", + "minecraft.world.level.ServerExplosionMixin_API", "minecraft.world.level.biome.AmbientAdditionsSettingsMixin_API", "minecraft.world.level.biome.AmbientMoodSettingsMixin_API", "minecraft.world.level.biome.AmbientParticleSettingsMixin_API", @@ -477,7 +447,6 @@ "minecraft.world.level.gameevent.PositionSourceMixin_API", "minecraft.world.level.levelgen.DensityFunctionMixin_API", "minecraft.world.level.levelgen.FlatLevelSourceMixin_API", - "minecraft.world.level.levelgen.GenerationStep_CarvingMixin_API", "minecraft.world.level.levelgen.GenerationStep_DecorationMixin_API", "minecraft.world.level.levelgen.Heightmap_TypeMixin_API", "minecraft.world.level.levelgen.NoiseBasedChunkGeneratorMixin_API", diff --git a/src/mixins/resources/mixins.sponge.core.json b/src/mixins/resources/mixins.sponge.core.json index 850d47de6fb..8c102eed091 100644 --- a/src/mixins/resources/mixins.sponge.core.json +++ b/src/mixins/resources/mixins.sponge.core.json @@ -34,6 +34,7 @@ "item.EmptyMapItemMixin", "item.ThrowableInaccurateItemMixin", "item.YeetableInaccurateItemMixin", + "nbt.CompoundTagMixin", "network.ConnectionMixin", "network.PacketEncoderMixin", "network.chat.Component_SerializerMixin", @@ -139,6 +140,7 @@ "world.entity.animal.OcelotMixin", "world.entity.animal.ParrotMixin", "world.entity.animal.Rabbit_RaidGardenGoalMixin", + "world.entity.animal.SnowGolemMixin", "world.entity.animal.WolfMixin", "world.entity.animal.horse.AbstractHorseMixin", "world.entity.boss.enderdragon.EndCrystalMixin", @@ -182,17 +184,18 @@ "world.entity.projectile.ThrownEnderpearlMixin", "world.entity.projectile.ThrownTridentMixin", "world.entity.projectile.WitherSkullMixin", + "world.entity.vehicle.AbstractBoatMixin", "world.entity.vehicle.AbstractMinecartContainerMixin", "world.entity.vehicle.AbstractMinecartMixin", - "world.entity.vehicle.BoatMixin", "world.entity.vehicle.MinecartCommandBlock_MinecartCommandBaseMixin", "world.entity.vehicle.MinecartCommandBlockMixin", "world.entity.vehicle.MinecartFurnaceMixin", "world.entity.vehicle.MinecartTNTMixin", + "world.entity.vehicle.OldMinecartBehaviourMixin", "world.entity.vehicle.VehicleEntityMixin", "world.food.FoodDataMixin", "world.inventory.StonecutterMenuMixin", - "world.item.ChorusFruitItemMixin", + "world.item.ConsumableMixin", "world.item.EnderEyeItemMixin", "world.item.FireworkRocketItemMixin", "world.item.FishingRodItemMixin", @@ -201,6 +204,7 @@ "world.item.ItemStackMixin", "world.item.MapItemMixin", "world.item.ServerItemCooldownsMixin", + "world.item.TeleportRandomlyConsumeEffectMixin", "world.item.crafting.AbstractCookingRecipeMixin", "world.item.crafting.IngredientMixin", "world.item.crafting.RecipeManagerMixin", @@ -208,8 +212,8 @@ "world.item.crafting.ShapedRecipeMixin", "world.item.crafting.ShapelessRecipe_SerializerMixin", "world.item.crafting.ShapelessRecipeMixin", - "world.item.crafting.SimpleCookingSerializerMixin", - "world.item.crafting.SimpleCraftingRecipeSerializerMixin", + "world.item.crafting.AbstractCookingRecipeSerializerMixin", + "world.item.crafting.CustomRecipeSerializerMixin", "world.item.crafting.SingleItemRecipeMixin", "world.item.crafting.SmithingTransformRecipe_SerializerMixin", "world.item.crafting.SmithingTransformRecipeMixin", @@ -217,11 +221,12 @@ "world.item.enchantment.EnchantmentMixin", "world.level.BaseSpawnerMixin", "world.level.BlockGetterMixin", - "world.level.ExplosionMixin", + "world.level.Explosion_BlockInteractionMixin", "world.level.LevelMixin", "world.level.NaturalSpawner_SpawnStateMixin", "world.level.NaturalSpawnerMixin", "world.level.SavedDataMixin", + "world.level.ServerExplosionMixin", "world.level.biome.BiomeSourceMixin", "world.level.block.BaseFireBlockMixin", "world.level.block.CactusBlockMixin", @@ -236,9 +241,11 @@ "world.level.block.MagmaBlockMixin", "world.level.block.NetherPortalBlockMixin", "world.level.block.NoteBlockMixin", + "world.level.block.TntBlockMixin", "world.level.block.entity.AbstractFurnaceBlockEntityMixin", "world.level.block.entity.BannerBlockEntityMixin", "world.level.block.entity.BaseContainerBlockEntityMixin", + "world.level.block.entity.BeaconBlockEntityMixin", "world.level.block.entity.BellBLockEntityMixin", "world.level.block.entity.BlockEntityMixin", "world.level.block.entity.BrewingStandBlockEntityMixin", @@ -254,9 +261,9 @@ "world.level.block.state.BlockStateMixin", "world.level.border.WorldBorderMixin", "world.level.chunk.ChunkGeneratorMixin", - "world.level.chunk.ChunkSerializerMixin", "world.level.chunk.ChunkStatusTasksMixin", "world.level.chunk.LevelChunkMixin", + "world.level.chunk.SerializableChunkDataMixin", "world.level.chunk.storage.EntityStorageMixin", "world.level.chunk.storage.IOWorkerMixin", "world.level.chunk.storage.RegionFileMixin", @@ -303,5 +310,5 @@ }, "overwrites": { "conformVisibility": true - } + } } diff --git a/src/mixins/resources/mixins.sponge.inventory.json b/src/mixins/resources/mixins.sponge.inventory.json index 81700e21b07..0b4ba5ddbb6 100644 --- a/src/mixins/resources/mixins.sponge.inventory.json +++ b/src/mixins/resources/mixins.sponge.inventory.json @@ -86,6 +86,7 @@ "impl.world.inventory.AbstractContainerMenuMixin_Bridge_Inventory", "impl.world.inventory.AbstractContainerMenuMixin_Fabric_Inventory", "impl.world.inventory.AbstractContainerMenuMixin_Menu_Inventory", + "impl.world.inventory.AbstractCraftingMenuMixin_TrackedMenuBridge_Inventory", "impl.world.inventory.AbstractFurnaceMenuMixin_TrackedMenuBridge_Inventory", "impl.world.inventory.BeaconMenuMixin_TrackedMenuBridge_Inventory", "impl.world.inventory.BrewingStandMenuMixin_TrackedMenuBridge_Inventory", diff --git a/src/mixins/resources/mixins.sponge.tracker.json b/src/mixins/resources/mixins.sponge.tracker.json index 4cc2dc73bf8..d3969c69be7 100644 --- a/src/mixins/resources/mixins.sponge.tracker.json +++ b/src/mixins/resources/mixins.sponge.tracker.json @@ -32,8 +32,7 @@ "world.item.BoneMealItemMixin_Tracker", "world.item.ItemStackMixin_Tracker", "world.level.BlockEventDataMixin_Tracker", - "world.level.ExplosionMixin_Tracker", - "world.level.LevelAccessorMixin_Tracker", + "world.level.ServerExplosionMixin_Tracker", "world.level.LevelHeightAccessorMixin_Tracker", "world.level.LevelMixin_Tracker", "world.level.block.BlockMixin_Tracker", @@ -44,7 +43,7 @@ "world.level.block.entity.BlockEntityTypeMixin_Tracker", "world.level.chunk.ChunkAccessMixin_Tracker", "world.level.chunk.LevelChunkMixin_Tracker", - "world.level.chunk.storage.ChunkSerializerMixin_Tracker", + "world.level.chunk.storage.SerializableChunkDataMixin_Tracker", "world.level.dimension.end.EndDragonFightMixin_Tracker", "world.level.redstone.NeighborUpdaterMixin_Tracker", "world.ticks.LevelTicksMixin_Tracker", diff --git a/src/test/java/org/spongepowered/common/test/block/SpongeBlock.java b/src/test/java/org/spongepowered/common/test/block/SpongeBlock.java index 7174e1aa314..3fbae6a0c5f 100644 --- a/src/test/java/org/spongepowered/common/test/block/SpongeBlock.java +++ b/src/test/java/org/spongepowered/common/test/block/SpongeBlock.java @@ -24,21 +24,11 @@ */ package org.spongepowered.common.test.block; -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; -@SuppressWarnings("deprecation") public class SpongeBlock extends Block { public SpongeBlock(Properties param0) { super(param0); } - @Override - public void neighborChanged( - BlockState param0, Level param1, BlockPos param2, Block param3, BlockPos param4, boolean param5 - ) { - super.neighborChanged(param0, param1, param2, param3, param4, param5); - } } diff --git a/src/test/java/org/spongepowered/common/util/ReflectionTest.java b/src/test/java/org/spongepowered/common/util/ReflectionTest.java index 67cbcee200c..6f40b536677 100644 --- a/src/test/java/org/spongepowered/common/util/ReflectionTest.java +++ b/src/test/java/org/spongepowered/common/util/ReflectionTest.java @@ -24,113 +24,14 @@ */ package org.spongepowered.common.util; -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.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; import org.spongepowered.common.test.UnitTestExtension; -import org.spongepowered.common.test.block.SpongeBlock; -import java.lang.reflect.Method; @Disabled @ExtendWith(UnitTestExtension.class) public class ReflectionTest { - @Test - public void testCheckNeighborChangedDeclared() { - final boolean isNeighborChangedDeclared = ReflectionUtil.isNeighborChangedDeclared(SpongeBlock.class); - Assertions.assertTrue(isNeighborChangedDeclared, "NeighborChanged should be declared on SpongeBlock"); - } - - @Test - public void testEntityInsideNotDeclared() { - final boolean entityInsideDeclared = ReflectionUtil.isEntityInsideDeclared(SpongeBlock.class); - Assertions.assertFalse(entityInsideDeclared, "isEntityInsideDeclared is not declared on SpongeBlock"); - } - - @Test - public void testNonExistentMethodOnCustomClass() { - final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/spongepowered/common/test/block/BombDummy", null, "net/minecraft/world/level/block/Block", null); - { - final MethodVisitor ctor = writer.visitMethod( - Opcodes.ACC_PUBLIC, - "", - "(Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V", - null, - null - ); - ctor.visitCode(); - ctor.visitVarInsn(Opcodes.ALOAD, 0); - ctor.visitVarInsn(Opcodes.ALOAD, 1); - ctor.visitMethodInsn( - Opcodes.INVOKESPECIAL, - "net/minecraft/world/level/block/Block", - "", - "(Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V", - false - ); - ctor.visitInsn(Opcodes.RETURN); - ctor.visitMaxs(0, 0); - } - { - final MethodVisitor el = writer.visitMethod( - Opcodes.ACC_PUBLIC, - "neighborChanged", - "(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/core/BlockPos;Z)V", - null, - null - ); - el.visitCode(); - el.visitInsn(Opcodes.RETURN); - el.visitMaxs(0,0); - } - { - final MethodVisitor bomb = writer.visitMethod( - Opcodes.ACC_PUBLIC, - "throwup", - "(Lcom/example/doesnt/Exist;)V", - null, - null - ); - bomb.visitCode(); - bomb.visitInsn(Opcodes.RETURN); - bomb.visitMaxs(0, 0); - } - - final DefinableClassLoader loader = new DefinableClassLoader(this.getClass().getClassLoader()); - final byte[] bombClazzBytes = writer.toByteArray(); - final Class clazz = loader.defineClass("org.spongepowered.common.test.block.BombDummy", bombClazzBytes); - final boolean neighborChanged = ReflectionUtil.isNeighborChangedDeclared(clazz); - Assertions.assertTrue(neighborChanged, "NeighborChanged should have been defined on BombDummy"); - final boolean entityInside = ReflectionUtil.isEntityInsideDeclared(clazz); - Assertions.assertFalse(entityInside, "isEntityInsideDeclared is not defined on BombDummy"); - NoClassDefFoundError e = null; - try { - ReflectionTest.getNeighborChanged(clazz); - } catch (final Exception ex) { - Assertions.fail("Expected a class not found exception for com/example/doesnt/Exist"); - } catch (final NoClassDefFoundError ee) { - e = ee; - } - Assertions.assertNotNull(e, "Should have gotten a class exception"); - } - - private static void getNeighborChanged(final Class clazz) throws Exception, Error { - final Method m = clazz.getMethod("neighborChanged", BlockState.class, - Level.class, - BlockPos.class, - Block.class, - BlockPos.class, - boolean.class); - } } diff --git a/testplugins/src/main/java/org/spongepowered/test/data/DataTest.java b/testplugins/src/main/java/org/spongepowered/test/data/DataTest.java index 67d263c5a9d..5a732f206ce 100644 --- a/testplugins/src/main/java/org/spongepowered/test/data/DataTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/data/DataTest.java @@ -373,7 +373,7 @@ public void testData(final ServerPlayer player) { this.checkOfferData(ravager, Keys.CAN_JOIN_RAID, true); this.checkOfferData(ravager, Keys.CAN_JOIN_RAID, false); - final Entity boat = world.createEntity(EntityTypes.BOAT.get(), position); + final Entity boat = world.createEntity(EntityTypes.OAK_BOAT.get(), position); this.checkOfferData(boat, Keys.CAN_MOVE_ON_LAND, true); this.checkOfferData(boat, Keys.CAN_MOVE_ON_LAND, false); @@ -548,7 +548,7 @@ public void testData(final ServerPlayer player) { this.checkGetData(player, Keys.EXPERIENCE, 7); this.checkOfferData(player, Keys.EXPERIENCE_SINCE_LEVEL, 1); - this.checkOfferData(tntEntity, Keys.EXPLOSION_RADIUS, 1); + this.checkOfferData(tntEntity, Keys.EXPLOSION_RADIUS, 1f); this.checkGetData(player, Keys.EYE_HEIGHT, (double)1.62f); this.checkGetData(sheep, Keys.EYE_HEIGHT, (double)(1.3f * 0.95f)); diff --git a/testplugins/src/main/java/org/spongepowered/test/data/InfiniteTicksDataTest.java b/testplugins/src/main/java/org/spongepowered/test/data/InfiniteTicksDataTest.java index 29dfbfa6ae1..a2785f03f9b 100644 --- a/testplugins/src/main/java/org/spongepowered/test/data/InfiniteTicksDataTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/data/InfiniteTicksDataTest.java @@ -169,6 +169,7 @@ private void onRegisterCommand(final RegisterCommandEvent final Parameter.Value potionEffectParameter = Parameter.registryElement(TypeToken.get(PotionEffectType.class), RegistryTypes.POTION_EFFECT_TYPE, "minecraft").key("potionEffectType").build(); final Parameter.Value itemTypeParameter = Parameter.registryElement(TypeToken.get(ItemType.class), RegistryTypes.ITEM_TYPE, "minecraft").key("itemType").build(); final Parameter.Value weatherTypeParameter = Parameter.registryElement(TypeToken.get(WeatherType.class), RegistryTypes.WEATHER_TYPE, "sponge").key("weatherType").build(); + final Parameter.Value resourceKeyParameter = Parameter.resourceKey().key("resourceKey").build(); event.register(this.plugin, Command.builder() .addParameter(entityParameter) @@ -250,11 +251,11 @@ private void onRegisterCommand(final RegisterCommandEvent }).build(), "offerInfiniteRangedAttackDelay"); event.register(this.plugin, Command.builder() - .addParameter(itemTypeParameter) + .addParameter(resourceKeyParameter) .executor(context -> { final ServerPlayer player = context.cause().first(ServerPlayer.class).get(); - final ItemType itemType = context.requireOne(itemTypeParameter); - if (player.cooldownTracker().setCooldown(itemType, Ticks.infinite())) { + final ResourceKey group = context.requireOne(resourceKeyParameter); + if (player.cooldownTracker().setCooldown(group, Ticks.infinite())) { context.sendMessage(Component.text("Applied!", NamedTextColor.GREEN)); return CommandResult.success(); } else { diff --git a/testplugins/src/main/java/org/spongepowered/test/recipe/RecipeTest.java b/testplugins/src/main/java/org/spongepowered/test/recipe/RecipeTest.java index 2fb84f4a299..491fa5c59e3 100644 --- a/testplugins/src/main/java/org/spongepowered/test/recipe/RecipeTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/recipe/RecipeTest.java @@ -42,6 +42,7 @@ import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; +import org.spongepowered.api.item.inventory.ItemStackLike; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.query.QueryTypes; import org.spongepowered.api.item.recipe.RecipeRegistration; @@ -254,7 +255,7 @@ private void onRecipeRegistry(final RegisterDataPackValueEvent hardnessPredicate = stack -> stack.type().block().map(b -> b.defaultState().get(Keys.DESTROY_SPEED).orElse(0d) > 20).orElse(false); // e.g. obsidian + final Predicate hardnessPredicate = stack -> stack.type().block().map(b -> b.defaultState().get(Keys.DESTROY_SPEED).orElse(0d) > 20).orElse(false); // e.g. obsidian final Ingredient hardBlock = Ingredient.of(ResourceKey.of(this.plugin, "hardblock"), hardnessPredicate, ItemStack.of(ItemTypes.OBSIDIAN)); final RecipeRegistration hardblockToWool = ShapelessCraftingRecipe.builder().addIngredients(hardBlock).result(ItemStack.of(ItemTypes.WHITE_WOOL)) diff --git a/testplugins/src/main/java/org/spongepowered/test/worldgen/BiomeTest.java b/testplugins/src/main/java/org/spongepowered/test/worldgen/BiomeTest.java index e338b45d318..78e35a2572e 100644 --- a/testplugins/src/main/java/org/spongepowered/test/worldgen/BiomeTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/worldgen/BiomeTest.java @@ -79,14 +79,12 @@ private CommandResult info(final CommandContext ctx, final Parameter.Value { - if (!list.isEmpty()) { - ctx.sendMessage(Identity.nil(), Component.text("Carvers Step:", NamedTextColor.DARK_AQUA)); - list.forEach(configuredCarver -> { - ctx.sendMessage(Identity.nil(), Component.text(" - " + configuredCarver.type().getClass().getSimpleName(), NamedTextColor.GRAY)); - }); - } - }); + if (!biome.carvers().isEmpty()) { + ctx.sendMessage(Identity.nil(), Component.text("Carvers Step:", NamedTextColor.DARK_AQUA)); + biome.carvers().forEach(configuredCarver -> { + ctx.sendMessage(Identity.nil(), Component.text(" - " + configuredCarver.type().getClass().getSimpleName(), NamedTextColor.GRAY)); + }); + } biome.ambientMood().ifPresent(mood -> { ctx.sendMessage(Identity.nil(), Component.text("Mood: " + mood, NamedTextColor.DARK_AQUA)); @@ -112,7 +110,7 @@ private CommandResult register(CommandContext commandContext) { final BiomeTemplate template = BiomeTemplate.builder().fromValue(defaultBiome) .add(Keys.FEATURES, Map.of(DecorationSteps.LAKES.get(), List.of(PlacedFeatures.LAKE_LAVA_SURFACE.get()))) - .add(Keys.CARVERS, Map.of()) + .add(Keys.CARVERS, List.of()) .add(Keys.NATURAL_SPAWNERS, Map.of(EntityCategories.MONSTER.get(), spawner)) .add(Keys.AMBIENT_ADDITIONAL_SOUND, SoundConfig.factory().ofAdditional(SoundTypes.ENTITY_CREEPER_PRIMED.get(), 0.001)) .add(Keys.AMBIENT_PARTICLE, ParticleConfig.of(ParticleTypes.BUBBLE.get(), 0.01f)) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/inventory/StonecutterMenuAccessor.java b/vanilla/src/accessors/java/org/spongepowered/vanilla/accessor/world/level/block/entity/AbstractFurnaceBlockEntityAccessor_Vanilla.java similarity index 68% rename from src/accessors/java/org/spongepowered/common/accessor/world/inventory/StonecutterMenuAccessor.java rename to vanilla/src/accessors/java/org/spongepowered/vanilla/accessor/world/level/block/entity/AbstractFurnaceBlockEntityAccessor_Vanilla.java index 7b6b94afb21..86fdaf869e4 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/inventory/StonecutterMenuAccessor.java +++ b/vanilla/src/accessors/java/org/spongepowered/vanilla/accessor/world/level/block/entity/AbstractFurnaceBlockEntityAccessor_Vanilla.java @@ -22,20 +22,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.accessor.world.inventory; +package org.spongepowered.vanilla.accessor.world.level.block.entity; -import net.minecraft.world.Container; -import net.minecraft.world.inventory.StonecutterMenu; +import net.minecraft.core.NonNullList; +import net.minecraft.core.RegistryAccess; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.SingleRecipeInput; +import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedInvokerError; -@Mixin(StonecutterMenu.class) -public interface StonecutterMenuAccessor { +@Mixin(AbstractFurnaceBlockEntity.class) +public interface AbstractFurnaceBlockEntityAccessor_Vanilla { - @Invoker("createRecipeInput") static SingleRecipeInput invoker$createRecipeInput(Container $$0) { + @Invoker("canBurn") + static boolean invoker$canBurn(final RegistryAccess registryAccess, @Nullable final RecipeHolder var0, final SingleRecipeInput input, final NonNullList var1, final int var2) { throw new UntransformedInvokerError(); } - } diff --git a/vanilla/src/accessors/resources/mixins.spongevanilla.accessors.json b/vanilla/src/accessors/resources/mixins.spongevanilla.accessors.json index 4cd6f66f91f..ce65de30a97 100644 --- a/vanilla/src/accessors/resources/mixins.spongevanilla.accessors.json +++ b/vanilla/src/accessors/resources/mixins.spongevanilla.accessors.json @@ -3,5 +3,6 @@ "parent": "mixins.sponge.parent.json", "package": "org.spongepowered.vanilla.accessor", "mixins": [ + "world.level.block.entity.AbstractFurnaceBlockEntityAccessor_Vanilla" ] } diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java index cc70debc8d9..60c70d1ca23 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java @@ -36,7 +36,6 @@ import net.minecraft.client.gui.components.events.AbstractContainerEventHandler; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.GameRenderer; import java.util.Collections; import java.util.List; @@ -189,7 +188,7 @@ public void render(final GuiGraphics stack, final int mouseX, final int mouseY, RenderSystem.enableScissor((int) (this.left * scale), (int) (this.client.getWindow().getHeight() - (this.bottom * scale)), (int) (this.width * scale), (int) (this.height * scale)); - RenderSystem.setShader(GameRenderer::getPositionTexColorShader); +// TODO fix me RenderSystem.setShader(GameRenderer::getPositionTexColorShader); RenderSystem.setShaderTexture(0, Screen.MENU_BACKGROUND); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); final float texScale = 32.0F; @@ -219,7 +218,7 @@ public void render(final GuiGraphics stack, final int mouseX, final int mouseY, } // RenderSystem.disableTexture(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); + // TODO fix me RenderSystem.setShader(GameRenderer::getPositionColorShader); worldr = tess.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); worldr.addVertex(this.barLeft, this.bottom, 0.0f).setColor(0x00, 0x00, 0x00, 0xFF); worldr.addVertex(this.barLeft + this.barWidth, this.bottom, 0.0f).setColor(0x00, 0x00, 0x00, 0xFF); diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/commands/SpreadPlayersCommandMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/commands/SpreadPlayersCommandMixin_Vanilla.java index 7fc77f6b85b..f47673ed676 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/commands/SpreadPlayersCommandMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/commands/SpreadPlayersCommandMixin_Vanilla.java @@ -27,7 +27,7 @@ import net.minecraft.server.commands.SpreadPlayersCommand; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.RelativeMovement; +import net.minecraft.world.entity.Relative; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.cause.entity.MovementTypes; @@ -41,14 +41,14 @@ @Mixin(SpreadPlayersCommand.class) public abstract class SpreadPlayersCommandMixin_Vanilla { - @Redirect(method = "setPlayerPositions", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;teleportTo(Lnet/minecraft/server/level/ServerLevel;DDDLjava/util/Set;FF)Z")) + @Redirect(method = "setPlayerPositions", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;teleportTo(Lnet/minecraft/server/level/ServerLevel;DDDLjava/util/Set;FFZ)Z")) private static boolean vanilla$createCauseFrameForTeleport( final Entity instance, final ServerLevel level, final double x, final double y, - final double z, final Set relativeMovements, final float yRot, final float xRot) { + final double z, final Set relativeMovements, final float yRot, final float xRot, final boolean setCamera) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.MOVEMENT_TYPE, MovementTypes.COMMAND); - return instance.teleportTo(level, x, y, z, relativeMovements, yRot, xRot); + return instance.teleportTo(level, x, y, z, relativeMovements, yRot, xRot, setCamera); } } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 2c792dce9d6..78e63b13177 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -25,6 +25,8 @@ package org.spongepowered.vanilla.mixin.core.server.network; import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.inventory.RecipeBookMenu; import net.minecraft.world.item.crafting.RecipeHolder; @@ -45,22 +47,27 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla implements ServerGamePacketListener { @SuppressWarnings({"unchecked", "rawtypes"}) - @Redirect(method = "lambda$handlePlaceRecipe$10", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) - private void vanilla$onPlaceRecipe(final RecipeBookMenu recipeBookMenu, final boolean shift, final RecipeHolder recipe, final net.minecraft.server.level.ServerPlayer player) { + @Redirect(method = "handlePlaceRecipe", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/player/Inventory;)Lnet/minecraft/world/inventory/RecipeBookMenu$PostPlaceAction;")) + private RecipeBookMenu.PostPlaceAction vanilla$onPlaceRecipe( + final RecipeBookMenu instance, final boolean shift, final boolean creative, + final RecipeHolder recipe, final ServerLevel serverLevel, + final net.minecraft.world.entity.player.Inventory inventory) { + final var player = inventory.player; final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext(); final TransactionalCaptureSupplier transactor = context.getTransactor(); final Inventory craftInv = ((Inventory) player.containerMenu).query(QueryTypes.INVENTORY_TYPE.get().of(CraftingInventory.class)); if (!(craftInv instanceof CraftingInventory)) { - recipeBookMenu.handlePlacement(shift, recipe, player); + final var postPlaceAction = instance.handlePlacement(shift, creative, recipe, serverLevel, inventory); SpongeCommon.logger().warn("Detected crafting without a InventoryCrafting!? Crafting Event will not fire."); - return; + return postPlaceAction; } - try (final EffectTransactor ignored = transactor.logPlaceRecipe(shift, (RecipeHolder) recipe, player, (CraftingInventory) craftInv)) { - recipeBookMenu.handlePlacement(shift, recipe, player); + try (final EffectTransactor ignored = transactor.logPlaceRecipe(shift, (RecipeHolder) recipe, (ServerPlayer) player, (CraftingInventory) craftInv)) { + final var postPlaceAction = instance.handlePlacement(shift, creative, recipe, serverLevel, inventory); player.containerMenu.broadcastChanges(); + return postPlaceAction; } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/EntityTypeMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/EntityTypeMixin_Vanilla.java index 3ff3a9d9344..8b8eda0b2cc 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/EntityTypeMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/EntityTypeMixin_Vanilla.java @@ -26,6 +26,9 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import org.spongepowered.asm.mixin.Mixin; @@ -41,13 +44,14 @@ public abstract class EntityTypeMixin_Vanilla { @Inject(method = "", at = @At("TAIL")) private static void impl$createHumanType(CallbackInfo ci) { + final var loc = ResourceLocation.fromNamespaceAndPath("sponge", "human"); SpongeEntityTypes.HUMAN = Registry.register(BuiltInRegistries.ENTITY_TYPE, HumanEntity.KEY, EntityType.Builder.of(HumanEntity::new, MobCategory.MISC) .noSave() .sized(0.6F, 1.8F) .clientTrackingRange(Constants.Entity.Player.TRACKING_RANGE) .updateInterval(2) - .build("sponge:human") + .build(ResourceKey.create(Registries.ENTITY_TYPE, loc)) ); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java index 0e03da3251f..718aacee6b9 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Attack_Impl.java @@ -41,18 +41,18 @@ public abstract class LivingEntityMixin_Attack_Impl { @SuppressWarnings("InvalidInjectorMethodSignature") - @ModifyConstant(method = "hurt", constant = @Constant(classValue = Wolf.class, ordinal = 0)) + @ModifyConstant(method = "hurtServer", constant = @Constant(classValue = Wolf.class, ordinal = 0)) private Class attackImpl$onWolfCast(final Object entity, final Class wolf) { return TamableAnimal.class; } - @Redirect(method = "hurt", + @Redirect(method = "hurtServer", at = @At(value = "INVOKE" , target = "Lnet/minecraft/world/entity/animal/Wolf;isTame()Z")) private boolean attackImpl$onWolfIsTame(@Coerce final Object instance) { return ((TamableAnimal)instance).isTame(); } - @Redirect(method = "hurt", + @Redirect(method = "hurtServer", at = @At(value = "INVOKE" , target = "Lnet/minecraft/world/entity/animal/Wolf;getOwner()Lnet/minecraft/world/entity/LivingEntity;")) private LivingEntity attackImpl$onWolfGetOwner(@Coerce final Object instance) { return ((TamableAnimal)instance).getOwner(); diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/player/PlayerMixin_Vanilla_Attack_Impl.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/player/PlayerMixin_Vanilla_Attack_Impl.java index cd9c042866d..490e74f75ff 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/player/PlayerMixin_Vanilla_Attack_Impl.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/player/PlayerMixin_Vanilla_Attack_Impl.java @@ -41,7 +41,7 @@ public class PlayerMixin_Vanilla_Attack_Impl { */ @ModifyVariable(method = "attack", ordinal = 2, slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;isSprinting()Z", ordinal = 1), - to = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/player/Player;walkDist:F")), + to = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;getKnownMovement()Lnet/minecraft/world/phys/Vec3;")), at = @At(value = "JUMP", opcode = Opcodes.IFEQ) ) public boolean attackImpl$critHook(final boolean isCritical) { diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/BoatMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/AbstractBoatMixin_Vanilla.java similarity index 89% rename from vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/BoatMixin_Vanilla.java rename to vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/AbstractBoatMixin_Vanilla.java index 2e60f5aea1f..693141a973a 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/BoatMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/vehicle/AbstractBoatMixin_Vanilla.java @@ -24,16 +24,16 @@ */ package org.spongepowered.vanilla.mixin.core.world.entity.vehicle; -import net.minecraft.world.entity.vehicle.Boat; +import net.minecraft.world.entity.vehicle.AbstractBoat; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.common.bridge.world.entity.vehicle.BoatBridge; +import org.spongepowered.common.bridge.world.entity.vehicle.AbstractBoatBridge; -@Mixin(Boat.class) -public abstract class BoatMixin_Vanilla implements BoatBridge { +@Mixin(AbstractBoat.class) +public abstract class AbstractBoatMixin_Vanilla implements AbstractBoatBridge { /** * Forge changes this check to ask the block state for "slipperiness" so we return the check here to Vanilla diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin_Vanilla.java index c66af4416f0..675a242248b 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/level/block/entity/AbstractFurnaceBlockEntityMixin_Vanilla.java @@ -27,10 +27,12 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; +import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.AbstractCookingRecipe; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.level.Level; +import net.minecraft.world.item.crafting.SingleRecipeInput; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; import net.minecraft.world.level.block.state.BlockState; import org.checkerframework.checker.nullness.qual.Nullable; @@ -56,6 +58,7 @@ import org.spongepowered.common.inventory.adapter.impl.slots.SlotAdapter; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.mixin.core.world.level.block.entity.BaseContainerBlockEntityMixin; +import org.spongepowered.vanilla.accessor.world.level.block.entity.AbstractFurnaceBlockEntityAccessor_Vanilla; import java.util.ArrayList; import java.util.Collections; @@ -68,9 +71,6 @@ public abstract class AbstractFurnaceBlockEntityMixin_Vanilla extends BaseContai // @formatter:off @Shadow protected NonNullList items; @Shadow int cookingProgress; - @Shadow private static boolean canBurn(final RegistryAccess registryAccess, @Nullable final RecipeHolder recipe, final NonNullList slots, final int maxStackSize) { - throw new UnsupportedOperationException("Shadowed canBurn"); - } // @formatter:on private boolean vanilla$filledWaterBucket; @@ -78,10 +78,13 @@ public abstract class AbstractFurnaceBlockEntityMixin_Vanilla extends BaseContai // Tick up and Start @Redirect(method = "serverTick", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;canBurn(Lnet/minecraft/core/RegistryAccess;Lnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/core/NonNullList;I)Z", + target = "Lnet/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity;canBurn(Lnet/minecraft/core/RegistryAccess;Lnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/world/item/crafting/SingleRecipeInput;Lnet/minecraft/core/NonNullList;I)Z", ordinal = 1)) - private static boolean vanilla$checkIfCanSmelt(final RegistryAccess registryAccess, @Nullable final RecipeHolder recipe, final NonNullList slots, final int maxStackSize, final Level level, final BlockPos entityPos, final BlockState state, final AbstractFurnaceBlockEntity entityIn) { - if (!AbstractFurnaceBlockEntityMixin_Vanilla.canBurn(registryAccess, recipe, slots, maxStackSize)) { + private static boolean vanilla$checkIfCanSmelt( + final RegistryAccess registryAccess, @Nullable final RecipeHolder recipe, final SingleRecipeInput input, + final NonNullList slots, final int maxStackSize, final ServerLevel level, final BlockPos entityPos, + final BlockState state, final AbstractFurnaceBlockEntity entityIn) { + if (!AbstractFurnaceBlockEntityAccessor_Vanilla.invoker$canBurn(registryAccess, recipe, input, slots, maxStackSize)) { return false; } @@ -105,8 +108,10 @@ public abstract class AbstractFurnaceBlockEntityMixin_Vanilla extends BaseContai // Tick down @Redirect(method = "serverTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Mth;clamp(III)I")) - private static int vanilla$resetCookTimeIfCancelled(final int newCookTime, final int zero, final int totalCookTime, - final Level level, final BlockPos entityPos, final BlockState state, final AbstractFurnaceBlockEntity entityIn) { + private static int vanilla$resetCookTimeIfCancelled( + final int newCookTime, final int zero, final int totalCookTime, + final ServerLevel level, final BlockPos entityPos, final BlockState state, + final AbstractFurnaceBlockEntity entityIn) { final int clampedCookTime = Mth.clamp(newCookTime, zero, totalCookTime); final var entity = (AbstractFurnaceBlockEntityMixin_Vanilla) (Object) entityIn; final ItemStackSnapshot fuel = ItemStackUtil.snapshotOf(entity.items.get(1)); @@ -128,7 +133,10 @@ public abstract class AbstractFurnaceBlockEntityMixin_Vanilla extends BaseContai slice = @Slice( from = @At(value = "FIELD", target = "Lnet/minecraft/world/level/block/Blocks;WET_SPONGE:Lnet/minecraft/world/level/block/Block;", opcode = Opcodes.GETSTATIC) )) - private static void vanilla$captureBucketFill(final RegistryAccess registryAccess, final RecipeHolder recipe, final NonNullList slots, final int maxStackSize, final CallbackInfoReturnable cir) { + private static void vanilla$captureBucketFill( + final RegistryAccess registryAccess, final RecipeHolder recipe, + final SingleRecipeInput input, final NonNullList slots, final int maxStackSize, + final CallbackInfoReturnable cir) { final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); final FurnaceBlockEntity entity = cause.first(FurnaceBlockEntity.class) .orElseThrow(() -> new IllegalStateException("Expected to have a FurnaceBlockEntity in the Cause")); @@ -136,9 +144,13 @@ public abstract class AbstractFurnaceBlockEntityMixin_Vanilla extends BaseContai } @Inject(method = "burn", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/item/ItemStack;shrink(I)V", shift = At.Shift.AFTER)) - private static void vanilla$afterSmeltItem(final RegistryAccess registryAccess, final RecipeHolder recipe, final NonNullList slots, final int maxStackSize, final CallbackInfoReturnable cir) { + // final RegistryAccess registryAccess, final RecipeHolder recipe, final NonNullList slots, final int var2, final CallbackInfoReturnable cir + private static void vanilla$afterSmeltItem( + final RegistryAccess registryAccess, final RecipeHolder recipe, + final SingleRecipeInput input, final NonNullList slots, final int $$4, + final CallbackInfoReturnable cir) { final ItemStack itemIn = slots.get(0); - final ItemStack recipeResult = recipe.value().getResultItem(registryAccess); + final ItemStack recipeResult = recipe.value().assemble(input, registryAccess); final ItemStack itemOut = slots.get(2); final Cause cause = PhaseTracker.getCauseStackManager().currentCause(); diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Vanilla_Tracker.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Vanilla_Tracker.java index bee1fba6587..eaf69d196bd 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Vanilla_Tracker.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Vanilla_Tracker.java @@ -24,34 +24,34 @@ */ package org.spongepowered.vanilla.mixin.tracker.world.level.block; -import net.minecraft.resources.ResourceKey; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.storage.loot.LootTable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.accessor.world.level.block.state.BlockBehaviourAccessor; import org.spongepowered.common.bridge.RegistryBackedTrackableBridge; @Mixin(Blocks.class) public abstract class BlocksMixin_Vanilla_Tracker { - @Redirect(method = "", + @Inject(method = "", at = @At( - value = "INVOKE", + value = "RETURN", target = "Lnet/minecraft/world/level/block/Block;getLootTable()Lnet/minecraft/resources/ResourceKey;" ) ) - private static ResourceKey impl$initializeTrackerState(final Block block) { - final boolean randomlyTicking = ((BlockBehaviourAccessor) block).invoker$isRandomlyTicking(block.defaultBlockState()); + private static void impl$initializeTrackerState(final CallbackInfo ci) { + for (final Block block : BuiltInRegistries.BLOCK) { + final boolean randomlyTicking = ((BlockBehaviourAccessor) block).invoker$isRandomlyTicking(block.defaultBlockState()); - // TODO Not the best check but the tracker options only matter during block ticks... - if (randomlyTicking) { - final var trackableBridge = (RegistryBackedTrackableBridge) block; - trackableBridge.bridge$refreshTrackerStates(); + // TODO Not the best check but the tracker options only matter during block ticks... + if (randomlyTicking) { + final var trackableBridge = (RegistryBackedTrackableBridge) block; + trackableBridge.bridge$refreshTrackerStates(); + } } - - return block.getLootTable(); } } diff --git a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json index f70c40c0ea5..d59b474243c 100644 --- a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json +++ b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json @@ -34,7 +34,7 @@ "world.entity.ai.attributes.DefaultAttributesMixin", "world.entity.item.ItemEntityMixin_Vanilla", "world.entity.player.PlayerMixin_Vanilla_Attack_Impl", - "world.entity.vehicle.BoatMixin_Vanilla", + "world.entity.vehicle.AbstractBoatMixin_Vanilla", "world.level.block.FireBlockMixin_Vanilla", "world.level.block.entity.AbstractFurnaceBlockEntityMixin_Vanilla", "world.level.storage.LevelStorageSourceMixin_Vanilla"