From bd5dfdbf9fecb1d48495f5dc73c24870aeb20366 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 18 Jan 2023 04:07:55 +0100 Subject: [PATCH] refactor limit access to built-in registries --- src/main/java/carpet/CarpetSettings.java | 3 +- .../java/carpet/commands/MobAICommand.java | 2 +- .../carpet/fakes/RecipeManagerInterface.java | 4 +- .../java/carpet/helpers/FeatureGenerator.java | 6 +- .../java/carpet/helpers/HopperCounter.java | 36 ++++--- .../logHelpers/ExplosionLogHelper.java | 9 +- .../mixins/Explosion_optimizedTntMixin.java | 2 +- .../mixins/RecipeManager_scarpetMixin.java | 9 +- .../java/carpet/script/CarpetEventServer.java | 28 +++--- .../script/annotation/OutputConverter.java | 1 + .../java/carpet/script/api/Auxiliary.java | 17 ++-- src/main/java/carpet/script/api/Entities.java | 5 +- .../java/carpet/script/api/Inventories.java | 35 ++++--- .../java/carpet/script/api/WorldAccess.java | 30 +++--- .../carpet/script/argument/BlockArgument.java | 2 +- .../script/command/CommandArgument.java | 7 +- .../carpet/script/utils/ShapeDispatcher.java | 97 ++++++++++--------- .../carpet/script/utils/ShapesRenderer.java | 8 +- .../java/carpet/script/value/BlockValue.java | 47 ++++----- .../java/carpet/script/value/EntityValue.java | 27 +++--- .../java/carpet/script/value/ScreenValue.java | 2 +- .../carpet/script/value/ValueConversions.java | 23 ++++- src/main/java/carpet/utils/BlockInfo.java | 5 +- .../java/carpet/utils/CarpetProfiler.java | 7 +- src/main/java/carpet/utils/MobAI.java | 7 +- 25 files changed, 243 insertions(+), 176 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 863a84a2..ded6c7f9 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -14,6 +14,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerInterface; @@ -1007,7 +1008,7 @@ public class CarpetSettings @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) { - Optional ignoredBlock = BuiltInRegistries.BLOCK.getOptional(ResourceLocation.tryParse(newValue)); + Optional ignoredBlock = source.registryAccess().registryOrThrow(Registries.BLOCK).getOptional(ResourceLocation.tryParse(newValue)); if (!ignoredBlock.isPresent()) { Messenger.m(source, "r Unknown block '" + newValue + "'."); return null; diff --git a/src/main/java/carpet/commands/MobAICommand.java b/src/main/java/carpet/commands/MobAICommand.java index 26b1e031..f905ebda 100644 --- a/src/main/java/carpet/commands/MobAICommand.java +++ b/src/main/java/carpet/commands/MobAICommand.java @@ -24,7 +24,7 @@ public class MobAICommand requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandTrackAI)). then(argument("entity type", resource(commandBuildContext, Registries.ENTITY_TYPE)). - suggests( (c, b) -> suggest(MobAI.availbleTypes(), b)). + suggests( (c, b) -> suggest(MobAI.availbleTypes(c.getSource()), b)). then(literal("clear").executes( (c) -> { MobAI.clearTracking(getSummonableEntityType(c, "entity type").value()); diff --git a/src/main/java/carpet/fakes/RecipeManagerInterface.java b/src/main/java/carpet/fakes/RecipeManagerInterface.java index 6e618389..ff130d00 100644 --- a/src/main/java/carpet/fakes/RecipeManagerInterface.java +++ b/src/main/java/carpet/fakes/RecipeManagerInterface.java @@ -1,6 +1,8 @@ package carpet.fakes; import java.util.List; + +import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; @@ -11,5 +13,5 @@ public interface RecipeManagerInterface * Gets all the recipes for a given item. Also used for {@link carpet.helpers.HopperCounter#guessColor} to guess the * colour of an item to display it prettily */ - List> getAllMatching(RecipeType type, ResourceLocation output); + List> getAllMatching(final RecipeType type, final ResourceLocation output, final RegistryAccess registryAccess); } diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/helpers/FeatureGenerator.java index c6f00687..8ba56c40 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/helpers/FeatureGenerator.java @@ -92,14 +92,14 @@ public class FeatureGenerator CarpetSettings.skipGenerationChecks.set(false); } } - Optional> structureType = BuiltInRegistries.STRUCTURE_TYPE.getOptional(id); + Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); if (structureType.isPresent()) { Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); if (configuredStandard != null) return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false); } - Feature feature = BuiltInRegistries.FEATURE.get(id); + Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); if (feature != null) { ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); @@ -124,7 +124,7 @@ public class FeatureGenerator ResourceLocation id = new ResourceLocation(name); Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); if (configuredStructureFeature != null) return configuredStructureFeature; - StructureType structureFeature = BuiltInRegistries.STRUCTURE_TYPE.get(id); + StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); if (structureFeature == null) return null; return getDefaultFeature(structureFeature, world, pos); } diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index d0340ef4..f7f51597 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -8,7 +8,10 @@ import carpet.utils.Messenger; import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import net.minecraft.ChatFormatting; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; @@ -211,7 +214,7 @@ public class HopperCounter Item item = e.getKey(); MutableComponent itemName = Component.translatable(item.getDescriptionId()); Style itemStyle = itemName.getStyle(); - TextColor color = guessColor(item); + TextColor color = guessColor(item, server.registryAccess()); itemName.setStyle((color != null) ? itemStyle.withColor(color) : itemStyle.withItalic(true)); long count = e.getLongValue(); return Messenger.c("g - ", itemName, @@ -240,7 +243,7 @@ public class HopperCounter /** * Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the - * {@link Block#getDefaultMaterialColor()} method as these items have those same colours. + * {@link Block#defaultMaterialColor()} method as these items have those same colours. */ private static final Map DEFAULTS = Map.ofEntries( entry(Items.DANDELION, Blocks.YELLOW_WOOL), @@ -331,19 +334,21 @@ public class HopperCounter /** * Gets the colour to print an item in when printing its count in a hopper counter. */ - public static TextColor fromItem(Item item) + public static TextColor fromItem(Item item, RegistryAccess registryAccess) { if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMaterialColor().col)); - if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getDyeColor().getMaterialColor().col)); + if (item instanceof DyeItem dye) return TextColor.fromRgb(appropriateColor(dye.getDyeColor().getMaterialColor().col)); Block block = null; - ResourceLocation id = BuiltInRegistries.ITEM.getKey(item); - if (item instanceof BlockItem) + final Registry itemRegistry = registryAccess.registryOrThrow(Registries.ITEM); + final Registry blockRegistry = registryAccess.registryOrThrow(Registries.BLOCK); + ResourceLocation id = itemRegistry.getKey(item); + if (item instanceof BlockItem blockItem) { - block = ((BlockItem) item).getBlock(); + block = blockItem.getBlock(); } - else if (BuiltInRegistries.BLOCK.getOptional(id).isPresent()) + else if (blockRegistry.getOptional(id).isPresent()) { - block = BuiltInRegistries.BLOCK.get(id); + block = blockRegistry.get(id); } if (block != null) { @@ -358,15 +363,16 @@ public class HopperCounter * Guesses the item's colour from the item itself. It first calls {@link HopperCounter#fromItem} to see if it has a * valid colour there, if not just makes a guess, and if that fails just returns null */ - public static TextColor guessColor(Item item) + public static TextColor guessColor(Item item, RegistryAccess registryAccess) { - TextColor direct = fromItem(item); + TextColor direct = fromItem(item, registryAccess); if (direct != null) return direct; if (CarpetServer.minecraft_server == null) return WHITE; - ResourceLocation id = BuiltInRegistries.ITEM.getKey(item); - for (RecipeType type: BuiltInRegistries.RECIPE_TYPE) + + ResourceLocation id = registryAccess.registryOrThrow(Registries.ITEM).getKey(item); + for (RecipeType type: registryAccess.registryOrThrow(Registries.RECIPE_TYPE)) { - for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id)) + for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id, registryAccess)) { for (Ingredient ingredient: r.getIngredients()) { @@ -374,7 +380,7 @@ public class HopperCounter { for (ItemStack iStak : stacks) { - TextColor cand = fromItem(iStak.getItem()); + TextColor cand = fromItem(iStak.getItem(), registryAccess); if (cand != null) return cand; } diff --git a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java index 300b4b8d..3b9fba76 100644 --- a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java +++ b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java @@ -6,7 +6,10 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.ArrayList; import java.util.List; + +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -19,6 +22,7 @@ public class ExplosionLogHelper { private final boolean createFire; private final Explosion.BlockInteraction blockDestructionType; + private final RegistryAccess regs; public final Vec3 pos; private final float power; private boolean affectBlocks = false; @@ -28,11 +32,12 @@ public class ExplosionLogHelper private static int explosionCountInCurretGT = 0; private static boolean newTick; - public ExplosionLogHelper(double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType) { + public ExplosionLogHelper(double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType, RegistryAccess regs) { this.power = power; this.pos = new Vec3(x,y,z); this.createFire = createFire; this.blockDestructionType = blockDestructionType; + this.regs = regs; } public void setAffectBlocks(boolean b) @@ -76,7 +81,7 @@ public class ExplosionLogHelper messages.add(c((k.pos.equals(pos))?"r - TNT":"w - ", Messenger.dblt((k.pos.equals(pos))?"r":"y", k.pos.x, k.pos.y, k.pos.z), "w dV", Messenger.dblt("d", k.accel.x, k.accel.y, k.accel.z), - "w "+ BuiltInRegistries.ENTITY_TYPE.getKey(k.type).getPath(), (v>1)?"l ("+v+")":"" + "w "+ regs.registryOrThrow(Registries.ENTITY_TYPE).getKey(k.type).getPath(), (v>1)?"l ("+v+")":"" )); }); } diff --git a/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java b/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java index 984f3f31..52e0dc34 100644 --- a/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java +++ b/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java @@ -80,7 +80,7 @@ public abstract class Explosion_optimizedTntMixin { if (LoggerRegistry.__explosions && ! world.isClientSide) { - eLogger = new ExplosionLogHelper(x, y, z, power, createFire, destructionType); + eLogger = new ExplosionLogHelper(x, y, z, power, createFire, destructionType, level.registryAccess()); } } diff --git a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java index e2c18b87..39ae1591 100644 --- a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java @@ -2,7 +2,11 @@ package carpet.mixins; import carpet.fakes.RecipeManagerInterface; import com.google.common.collect.Lists; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.item.Item; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,13 +26,14 @@ public class RecipeManager_scarpetMixin implements RecipeManagerInterface @Shadow private Map, Map>> recipes; @Override - public List> getAllMatching(RecipeType type, ResourceLocation output) + public List> getAllMatching(RecipeType type, ResourceLocation output, final RegistryAccess registryAccess) { Map> typeRecipes = recipes.get(type); // happens when mods add recipe to the registry without updating recipe manager if (typeRecipes == null) return Collections.emptyList(); if (typeRecipes.containsKey(output)) return Collections.singletonList(typeRecipes.get(output)); + final Registry regs = registryAccess.registryOrThrow(Registries.ITEM); return Lists.newArrayList(typeRecipes.values().stream().filter( - r -> BuiltInRegistries.ITEM.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); + r -> regs.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); } } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 920d84e6..01ebfe99 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -43,12 +43,16 @@ import java.util.stream.Collectors; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; 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.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.stats.Stat; +import net.minecraft.stats.StatType; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.DamageSource; @@ -551,7 +555,7 @@ public class CarpetEventServer //ItemStack itemstack = player.getStackInHand(enumhand); return Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ); }, player::createCommandSourceStack); @@ -585,7 +589,7 @@ public class CarpetEventServer Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), blockpos), StringValue.of(enumfacing.getName()), @@ -630,7 +634,7 @@ public class CarpetEventServer { return handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), pos) ), player::createCommandSourceStack); @@ -643,7 +647,7 @@ public class CarpetEventServer { handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), pos) ), player::createCommandSourceStack); @@ -676,12 +680,13 @@ public class CarpetEventServer @Override public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) { + final RegistryAccess regs = player.getLevel().registryAccess(); handler.call( () -> Arrays.asList( new EntityValue(player), merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL, - ValueConversions.of(tradeOffer.getBaseCostA()), - ValueConversions.of(tradeOffer.getCostB()), - ValueConversions.of(tradeOffer.getResult()) + ValueConversions.of(tradeOffer.getBaseCostA(), regs), + ValueConversions.of(tradeOffer.getCostB(), regs), + ValueConversions.of(tradeOffer.getResult(), regs) ), player::createCommandSourceStack); } }; @@ -689,7 +694,7 @@ public class CarpetEventServer { @Override public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { - handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::createCommandSourceStack); + handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack); return false; } }; @@ -748,7 +753,7 @@ public class CarpetEventServer handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ), player::createCommandSourceStack); return false; @@ -763,7 +768,7 @@ public class CarpetEventServer return handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), new StringValue(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ), player::createCommandSourceStack); } @@ -946,9 +951,10 @@ public class CarpetEventServer { ResourceLocation id = getStatId(stat); if (skippedStats.contains(id)) return; + final Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE); handler.call( () -> Arrays.asList( new EntityValue(player), - StringValue.of(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.STAT_TYPE.getKey(stat.getType()))), + StringValue.of(NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType()))), StringValue.of(NBTSerializableValue.nameFromRegistryId(id)), new NumericValue(amount) ), player::createCommandSourceStack); diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index c9de72ca..59f99233 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -6,6 +6,7 @@ import java.util.Objects; import java.util.function.Function; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index de9b76e2..c5611e0a 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -139,12 +139,12 @@ public class Auxiliary { CarpetContext cc = (CarpetContext)c; if (lv.size() == 0) { - return ListValue.wrap(BuiltInRegistries.SOUND_EVENT.keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).keySet().stream().map(ValueConversions::of)); } String rawString = lv.get(0).getString(); ResourceLocation soundName = InputValidator.identifierOf(rawString); Vector3Argument locator = Vector3Argument.findIn(lv, 1); - if (BuiltInRegistries.SOUND_EVENT.get(soundName) == null) + if (cc.registry(Registries.SOUND_EVENT).get(soundName) == null) throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND); final Holder soundHolder = Holder.direct(SoundEvent.createVariableRangeEvent(soundName)); float volume = 1.0F; @@ -180,7 +180,7 @@ public class Auxiliary { expression.addContextFunction("particle", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - if (lv.size() == 0) return ListValue.wrap(BuiltInRegistries.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of)); + if (lv.size() == 0) return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); MinecraftServer ms = cc.server(); ServerLevel world = cc.level(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); @@ -756,21 +756,20 @@ public class Auxiliary { { Map plopData = new HashMap<>(); CarpetContext cc = (CarpetContext)c; - RegistryAccess registryManager = cc.registryAccess(); plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("features"), - ListValue.wrap(BuiltInRegistries.FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_features"), - ListValue.wrap(registryManager.registryOrThrow(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structure_types"), - ListValue.wrap(BuiltInRegistries.STRUCTURE_TYPE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.STRUCTURE_TYPE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structures"), - ListValue.wrap(registryManager.registryOrThrow(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); return MapValue.wrap(plopData); } @@ -966,7 +965,7 @@ public class Auxiliary { ResourceLocation statName; category = InputValidator.identifierOf(lv.get(1).getString()); statName = InputValidator.identifierOf(lv.get(2).getString()); - StatType type = BuiltInRegistries.STAT_TYPE.get(category); + StatType type = cc.registry(Registries.STAT_TYPE).get(category); if (type == null) return Value.NULL; Stat stat = getStat(type, statName); if (stat == null) return Value.NULL; diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index 70f9eb39..be7205ec 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -26,6 +26,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; @@ -101,7 +102,7 @@ public class Entities { try { entityId = ResourceLocation.read(new StringReader(entityString)); - EntityType type = BuiltInRegistries.ENTITY_TYPE.getOptional(entityId).orElse(null); + EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); if (type == null || !type.canSummon()) return Value.NULL; } @@ -244,7 +245,7 @@ public class Entities { { if (lv.size() > 1) throw new InternalExpressionException("'entity_types' requires one or no arguments"); String desc = (lv.size() == 1)?lv.get(0).getString():"*"; - return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(); + return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(((CarpetContext)c).registryAccess()); }); expression.addContextFunction("entity_load_handler", -1, (c, t, lv) -> diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 8175cd22..29015287 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -30,6 +30,7 @@ import java.util.stream.Collectors; import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -66,10 +67,10 @@ public class Inventories { expression.addContextFunction("item_list", -1, (c, t, lv) -> { - if (lv.size() == 0) - return ListValue.wrap(BuiltInRegistries.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; Registry items = cc.registry(Registries.ITEM); + if (lv.size() == 0) + return ListValue.wrap(items.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); String tag = lv.get(0).getString(); Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); if (itemTag.isEmpty()) return Value.NULL; @@ -125,13 +126,14 @@ public class Inventories { if (lv.size() > 1) { String recipeType = lv.get(1).getString(); - type = BuiltInRegistries.RECIPE_TYPE.get(InputValidator.identifierOf(recipeType)); + type = cc.registry(Registries.RECIPE_TYPE).get(InputValidator.identifierOf(recipeType)); } List> recipes; - recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); + recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName), cc.registryAccess()); if (recipes.isEmpty()) return Value.NULL; List recipesOutput = new ArrayList<>(); + RegistryAccess regs = cc.registryAccess(); for (Recipe recipe: recipes) { ItemStack result = recipe.getResultItem(); @@ -150,7 +152,7 @@ public class Inventories { else { List alternatives = new ArrayList<>(); - stacks.forEach(col -> col.stream().map(ValueConversions::of).forEach(alternatives::add)); + stacks.forEach(col -> col.stream().map(is -> ValueConversions.of(is, regs)).forEach(alternatives::add)); ingredientValue.add(ListValue.wrap(alternatives)); } } @@ -189,19 +191,20 @@ public class Inventories { recipeSpec = ListValue.of(new StringValue("custom")); } - recipesOutput.add(ListValue.of(ValueConversions.of(result), ListValue.wrap(ingredientValue), recipeSpec)); + recipesOutput.add(ListValue.of(ValueConversions.of(result, regs), ListValue.wrap(ingredientValue), recipeSpec)); } return ListValue.wrap(recipesOutput); }); - expression.addUnaryFunction("crafting_remaining_item", v -> + expression.addContextFunction("crafting_remaining_item", 1, (c, t, v) -> { - String itemStr = v.getString(); + String itemStr = v.get(0).getString(); Item item; ResourceLocation id = InputValidator.identifierOf(itemStr); - item = BuiltInRegistries.ITEM.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); + Registry registry = ((CarpetContext)c).registry(Registries.ITEM); + item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); if (!item.hasCraftingRemainingItem()) return Value.NULL; - return new StringValue(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.ITEM.getKey(item.getCraftingRemainingItem()))); + return new StringValue(NBTSerializableValue.nameFromRegistryId(registry.getKey(item.getCraftingRemainingItem()))); }); expression.addContextFunction("inventory_size", -1, (c, t, lv) -> @@ -226,17 +229,18 @@ public class Inventories { CarpetContext cc = (CarpetContext) c; NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) return Value.NULL; + RegistryAccess regs = cc.registryAccess(); if (lv.size() == inventoryLocator.offset()) { List fullInventory = new ArrayList<>(); for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) - fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i))); + fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i), regs)); return ListValue.wrap(fullInventory); } int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; - return ValueConversions.of(inventoryLocator.inventory().getItem(slot)); + return ValueConversions.of(inventoryLocator.inventory().getItem(slot), regs); }); //inventory_set(, , , , ) @@ -251,13 +255,14 @@ public class Inventories { slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); + RegistryAccess regs = cc.registryAccess(); if (count == 0) { // clear slot ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); syncPlayerInventory(inventoryLocator, slot); //Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares - return ValueConversions.of(removedStack); + return ValueConversions.of(removedStack, regs); } if (lv.size() < inventoryLocator.offset()+3) { @@ -266,7 +271,7 @@ public class Inventories { newStack.setCount(count); inventoryLocator.inventory().setItem(slot, newStack); syncPlayerInventory(inventoryLocator, slot); - return ValueConversions.of(previousStack); + return ValueConversions.of(previousStack, regs); } CompoundTag nbt = null; // skipping one argument if (lv.size() > inventoryLocator.offset()+3) @@ -290,7 +295,7 @@ public class Inventories { { throw new InternalExpressionException(e.getMessage()); } - return ValueConversions.of(previousStack); + return ValueConversions.of(previousStack, regs); }); //inventory_find(, or null (first empty slot), ) -> or null diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index b56add39..cc9a546f 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -279,6 +279,7 @@ public class WorldAccess { BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); BlockPos pos = locator.block.getPos(); PoiManager store = cc.level().getPoiManager(); + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); if (lv.size() == locator.offset) { Optional> foo = store.getType(pos); @@ -297,7 +298,7 @@ public class WorldAccess { if (poi == null) return Value.NULL; return ListValue.of( - ValueConversions.of(BuiltInRegistries.POINT_OF_INTEREST_TYPE.getKey(poi.getPoiType().value())), + ValueConversions.of(poiReg.getKey(poi.getPoiType().value())), new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin)poi).getFreeTickets()) ); } @@ -311,7 +312,7 @@ public class WorldAccess { String poiType = lv.get(locator.offset+1).getString().toLowerCase(Locale.ROOT); if (!"any".equals(poiType)) { - PoiType type = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOptional(InputValidator.identifierOf(poiType)) + PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) .orElseThrow(() -> new ThrowStatement(poiType, Throwables.UNKNOWN_POI)); condition = (tt) -> tt.value() == type; } @@ -337,7 +338,7 @@ public class WorldAccess { store.getInRange(condition, pos, radius, status); return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> ListValue.of( - ValueConversions.of(BuiltInRegistries.POINT_OF_INTEREST_TYPE.getKey(p.getPoiType().value())), + ValueConversions.of(poiReg.getKey(p.getPoiType().value())), new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin)p).getFreeTickets()), ValueConversions.of(p.getPos()) ) @@ -362,9 +363,10 @@ public class WorldAccess { } String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); ResourceLocation resource = InputValidator.identifierOf(poiTypeString); - PoiType type = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOptional(resource) + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + PoiType type = poiReg.getOptional(resource) .orElseThrow(() -> new ThrowStatement(poiTypeString, Throwables.UNKNOWN_POI)); - Holder holder = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); + Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); int occupancy = 0; if (locator.offset + 1 < lv.size()) @@ -822,7 +824,7 @@ public class WorldAccess { { playerBreak = true; String itemString = val.getString(); - item = BuiltInRegistries.ITEM.getOptional(InputValidator.identifierOf(itemString)) + item = cc.registry(Registries.ITEM).getOptional(InputValidator.identifierOf(itemString)) .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } } @@ -971,7 +973,7 @@ public class WorldAccess { attacker = (LivingEntity) attackingEntity; } else throw new InternalExpressionException("Attacking entity needs to be a living thing, "+ - ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(attackingEntity.getType())).getString() +" ain't it."); + ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() +" ain't it."); } else @@ -1131,12 +1133,12 @@ public class WorldAccess { expression.addContextFunction("block_list", -1, (c, t, lv) -> { - if (lv.size() == 0) - return ListValue.wrap(BuiltInRegistries.BLOCK.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; + Registry blocks = cc.registry(Registries.BLOCK); + if (lv.size() == 0) + return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); - Registry blocks = cc.registry(Registries.BLOCK); Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); if (tagset.isEmpty()) return Value.NULL; return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value()))).collect(Collectors.toList())); @@ -1344,7 +1346,7 @@ public class WorldAccess { } else { - StructureType sss = BuiltInRegistries.STRUCTURE_TYPE.get(id); + StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); reg.entrySet().stream().filter(e -> e.getValue().type() ==sss).forEach(e -> structure.add(e.getValue())); } if (structure.isEmpty()) @@ -1371,7 +1373,7 @@ public class WorldAccess { StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); if (start == null) return Value.NULL; if (!needSize) return Value.TRUE; - return ValueConversions.of(start); + return ValueConversions.of(start, cc.registryAccess()); } Map ret = new HashMap<>(); for(Structure str: structure) @@ -1390,7 +1392,7 @@ public class WorldAccess { if (start == null) continue; Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(str))); - ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start)); + ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start, cc.registryAccess())); } return MapValue.wrap(ret); }); @@ -1420,7 +1422,7 @@ public class WorldAccess { return MapValue.wrap(structureList); } String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName)))); + return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName))), cc.registryAccess()); }); expression.addContextFunction("set_structure", -1, (c, t, lv) -> diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index e29d28a3..b2e66c93 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -60,7 +60,7 @@ public class BlockArgument extends Argument } if (acceptString && v1 instanceof StringValue) { - return new BlockArgument(BlockValue.fromString(v1.getString(), c.registryAccess()), 1 + offset); + return new BlockArgument(BlockValue.fromString(v1.getString(), c.level()), 1 + offset); } if (v1 instanceof BlockValue) { diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 67bfb37e..280e10e9 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -2,6 +2,7 @@ package carpet.script.command; import carpet.CarpetServer; import carpet.fakes.BlockStateArgumentInterface; +import carpet.script.CarpetContext; import carpet.script.CarpetScriptHost; import carpet.script.argument.FunctionArgument; import carpet.script.value.BlockValue; @@ -136,7 +137,7 @@ public abstract class CommandArgument new VanillaUnconfigurableArgument( "block", BlockStateArgument::block, (c, p) -> { BlockInput result = BlockStateArgument.getBlock(c, p); - return new BlockValue(result.getState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() ); + return new BlockValue(result.getState(), c.getSource().getLevel(), null, ((BlockStateArgumentInterface)result).getCMTag() ); }, param -> (ctx, builder) -> ctx.getArgument(param, BlockStateArgument.class).listSuggestions(ctx, builder) ), @@ -179,7 +180,7 @@ public abstract class CommandArgument // item_predicate ?? //same as item but accepts tags, not sure right now new SlotArgument(), new VanillaUnconfigurableArgument("item", ItemArgument::item, - (c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false)), + (c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false), c.getSource().registryAccess()), param -> (ctx, builder) -> ctx.getArgument(param, ItemArgument.class).listSuggestions(ctx, builder) ), new VanillaUnconfigurableArgument("message", MessageArgument::message, @@ -211,7 +212,7 @@ public abstract class CommandArgument (c, p) -> ValueConversions.of( ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) ), new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( BuiltInRegistries.LOOT_CONDITION_TYPE.getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) + (c, p) -> ValueConversions.of( c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) ), new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id, (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index d16fdae6..724e9639 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -29,6 +29,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.arguments.ParticleArgument; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.registries.BuiltInRegistries; @@ -67,6 +68,7 @@ import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -214,9 +216,9 @@ public class ShapeDispatcher if (param==null) throw new InternalExpressionException("Unknown feature for shape: "+key); userParams.put(key, param.validate(userParams, server, userParams.get(key))); }); - Function,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); if (factory == null) throw new InternalExpressionException("Unknown shape: "+shapeType); - return factory.apply(userParams); + return factory.apply(userParams, server.registryAccess()); } // client @@ -240,7 +242,7 @@ public class ShapeDispatcher CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys())); return null; } - Function,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); if (factory == null) { CarpetSettings.LOG.info("Unknown shape: "+shapeValue.getString()); @@ -248,7 +250,7 @@ public class ShapeDispatcher } try { - return factory.apply(options); + return factory.apply(options, level.registryAccess()); } catch (InternalExpressionException exc) { @@ -259,7 +261,7 @@ public class ShapeDispatcher public abstract static class ExpiringShape { - public static final Map,ExpiringShape>> shapeProviders = new HashMap, ExpiringShape>>(){{ + public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap, RegistryAccess, ExpiringShape>>(){{ put("line", creator(Line::new)); put("box", creator(Box::new)); put("sphere", creator(Sphere::new)); @@ -269,11 +271,11 @@ public class ShapeDispatcher put("block",creator(()->new DisplayedSprite(false))); put("item",creator(()->new DisplayedSprite(true))); }}; - private static Function,ExpiringShape> creator(Supplier shapeFactory) + private static BiFunction, RegistryAccess, ExpiringShape> creator(Supplier shapeFactory) { - return o -> { + return (o, regs) -> { ExpiringShape shape = shapeFactory.get(); - shape.fromOptions(o); + shape.fromOptions(o, regs); return shape; }; } @@ -305,7 +307,7 @@ public class ShapeDispatcher return tag; } - private void fromOptions(Map options) + private void fromOptions(Map options, RegistryAccess regs) { Set optional = optionalParams(); Set required = requiredParams(); @@ -318,12 +320,12 @@ public class ShapeDispatcher if (!this.canTake(k)) throw new InternalExpressionException("Parameter "+k+" doesn't apply for shape "+options.get("shape").getString()); }); - init(options); + init(options, regs); } - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { duration = NumericValue.asNumber(options.get("duration")).getInt(); @@ -399,13 +401,13 @@ public class ShapeDispatcher public abstract Consumer alternative(); - public long key() + public long key(final RegistryAccess regs) { if (key!=0) return key; - key = calcKey(); + key = calcKey(regs); return key; } - protected long calcKey() + protected long calcKey(final RegistryAccess regs) { // using FNV-1a algorithm long hash = -3750763034362895579L; hash ^= shapeDimension.hashCode(); hash *= 1099511628211L; @@ -487,9 +489,9 @@ public class ShapeDispatcher boolean doublesided; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); pos = vecFromValue(options.get("pos")); value = ((FormattedTextValue)options.get("text")).getText(); text = value.getString(); @@ -543,9 +545,9 @@ public class ShapeDispatcher } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 5; hash *= 1099511628211L; hash ^= vec3dhash(pos); hash *= 1099511628211L; hash ^= text.hashCode(); hash *= 1099511628211L; @@ -607,9 +609,9 @@ public class ShapeDispatcher String itemTransformType; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); pos = vecFromValue(options.get("pos")); if (!this.isitem) { @@ -648,14 +650,15 @@ public class ShapeDispatcher public Consumer alternative() { return p -> { ParticleOptions particle; + final Registry blocks = p.getServer().registryAccess().registryOrThrow(Registries.BLOCK); if(this.isitem) { if (Block.byItem(this.item.getItem()).defaultBlockState().isAir()) return; - particle = getParticleData("block_marker "+ BuiltInRegistries.BLOCK.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess()); + particle = getParticleData("block_marker " + blocks.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess()); } else { - particle = getParticleData("block_marker "+BuiltInRegistries.BLOCK.getKey(this.blockState.getBlock()), p.level.registryAccess()); + particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level.registryAccess()); } Vec3 v = relativiseRender(p.level, this.pos, 0); @@ -664,8 +667,8 @@ public class ShapeDispatcher } @Override - public long calcKey() { - long hash = super.calcKey(); + public long calcKey(final RegistryAccess regs) { + long hash = super.calcKey(regs); hash ^= 7; hash *= 1099511628211L; hash ^= Boolean.hashCode(isitem); hash *= 1099511628211L; hash ^= vec3dhash(pos); hash *= 1099511628211L; @@ -680,7 +683,7 @@ public class ShapeDispatcher hash ^= Float.hashCode(blockLight); hash *= 1099511628211L; if (blockEntity!= null) hash ^= blockEntity.toString().hashCode(); hash *= 1099511628211L; if (blockState!= null) hash ^= blockState.hashCode(); hash *= 1099511628211L; - hash ^= ValueConversions.of(item).getString().hashCode(); hash *= 1099511628211L; + hash ^= ValueConversions.of(item, regs).getString().hashCode(); hash *= 1099511628211L; hash ^= itemTransformType.hashCode(); hash *= 1099511628211L; return hash; @@ -702,9 +705,9 @@ public class ShapeDispatcher Vec3 to; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); from = vecFromValue(options.get("from")); to = vecFromValue(options.get("to")); } @@ -729,9 +732,9 @@ public class ShapeDispatcher } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 1; hash *= 1099511628211L; hash ^= vec3dhash(from); hash *= 1099511628211L; hash ^= vec3dhash(to); hash *= 1099511628211L; @@ -768,8 +771,8 @@ public class ShapeDispatcher public static class Polyface extends ExpiringShape { @Override - public long calcKey(){ - long hash = super.calcKey(); + public long calcKey(final RegistryAccess regs){ + long hash = super.calcKey(regs); hash ^= 6; hash *= 1099511628211L; hash ^= mode.hashCode(); hash *= 1099511628211L; hash ^= relative.hashCode(); hash *= 1099511628211L; @@ -898,9 +901,9 @@ public class ShapeDispatcher ArrayList relative=new ArrayList<>(); boolean inneredges; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); doublesided=options.getOrDefault("doublesided",optional.get("doublesided")).getBoolean(); @@ -962,9 +965,9 @@ public class ShapeDispatcher Vec3 to; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); from = vecFromValue(options.get("from")); to = vecFromValue(options.get("to")); } @@ -986,9 +989,9 @@ public class ShapeDispatcher } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 2; hash *= 1099511628211L; hash ^= vec3dhash(from); hash *= 1099511628211L; hash ^= vec3dhash(to); hash *= 1099511628211L; @@ -1016,9 +1019,9 @@ public class ShapeDispatcher int subdivisions; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); center = vecFromValue(options.get("center")); radius = NumericValue.asNumber(options.get("radius")).getFloat(); level = NumericValue.asNumber(options.getOrDefault("level", optional.get("level"))).getInt(); @@ -1059,9 +1062,9 @@ public class ShapeDispatcher };} @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 3; hash *= 1099511628211L; hash ^= vec3dhash(center); hash *= 1099511628211L; hash ^= Double.hashCode(radius); hash *= 1099511628211L; @@ -1092,9 +1095,9 @@ public class ShapeDispatcher private Cylinder() { super(); } @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); center = vecFromValue(options.get("center")); radius = NumericValue.asNumber(options.get("radius")).getFloat(); level = NumericValue.asNumber(options.getOrDefault("level", optional.get("level"))).getInt(); @@ -1162,9 +1165,9 @@ public class ShapeDispatcher };} @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 4; hash *= 1099511628211L; hash ^= vec3dhash(center); hash *= 1099511628211L; hash ^= Double.hashCode(radius); hash *= 1099511628211L; @@ -1307,7 +1310,7 @@ public class ShapeDispatcher if(value instanceof BlockValue blv){ return value; } - return BlockValue.fromString(value.getString(), server.registryAccess()); + return BlockValue.fromString(value.getString(), server.overworld()); } @Override public Tag toTag(Value value) { @@ -1330,7 +1333,7 @@ public class ShapeDispatcher if (((CompoundTag) tag).contains("TileEntityData", 10)) { compoundTag2 = ((CompoundTag) tag).getCompound("TileEntityData"); } - return new BlockValue(bs, null, null, compoundTag2); + return new BlockValue(bs, level, null, compoundTag2); } } public static class ItemParam extends Param diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 9878c568..e7e14ec1 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -217,9 +217,9 @@ public class ShapesRenderer protected RenderedShape(Minecraft client, T shape) { this.shape = shape; - expiryTick = client.level.getGameTime()+shape.getExpiry(); - renderEpsilon = (3+((double)shape.key())/Long.MAX_VALUE)/1000; this.client = client; + expiryTick = client.level.getGameTime()+shape.getExpiry(); + renderEpsilon = (3+((double)key())/Long.MAX_VALUE)/1000; } public boolean isExpired(long currentTick) @@ -228,7 +228,7 @@ public class ShapesRenderer } public long key() { - return shape.key(); + return shape.key(client.level.registryAccess()); }; public boolean shouldRender(ResourceKey dim) { @@ -365,7 +365,7 @@ public class ShapesRenderer { // draw the item client.getItemRenderer().renderStatic(shape.item, transformType, light, - OverlayTexture.NO_OVERLAY, matrices, immediate, (int) shape.key()); + OverlayTexture.NO_OVERLAY, matrices, immediate, (int) shape.key(client.level.registryAccess())); } } matrices.popPose(); diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index c22f43a3..f42cee84 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -18,7 +18,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.GlobalPos; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -29,23 +29,22 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; public class BlockValue extends Value { - public static final BlockValue AIR = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO); - public static final BlockValue NULL = new BlockValue(null, null, null); private BlockState blockState; private final BlockPos pos; - private final ServerLevel world; + @NotNull private final Level world; private CompoundTag data; public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) @@ -55,19 +54,19 @@ public class BlockValue extends Value } private static final Map bvCache= new HashMap<>(); - public static BlockValue fromString(String str, RegistryAccess regs) + public static BlockValue fromString(String str, Level level) { try { BlockValue bv = bvCache.get(str); // [SCARY SHIT] persistent caches over server reloads if (bv != null) return bv; - BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(regs.lookupOrThrow(Registries.BLOCK), new StringReader(str), true ); + BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true ); if (foo.blockState() != null) { CompoundTag bd = foo.nbt(); if (bd == null) bd = new CompoundTag(); - bv = new BlockValue(foo.blockState(), null, null, bd ); + bv = new BlockValue(foo.blockState(), level, null, bd ); if (bvCache.size()>10000) bvCache.clear(); bvCache.put(str, bv); @@ -92,7 +91,7 @@ public class BlockValue extends Value { return blockState; } - if (world != null && pos != null) + if (pos != null) { blockState = world.getBlockState(pos); return blockState; @@ -100,12 +99,15 @@ public class BlockValue extends Value throw new InternalExpressionException("Attempted to fetch block state without world or stored block state"); } - public static BlockEntity getBlockEntity(ServerLevel world, BlockPos pos) + public static BlockEntity getBlockEntity(Level level, BlockPos pos) { - if (world.getServer().isSameThread()) - return world.getBlockEntity(pos); - else - return world.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + if (level instanceof ServerLevel serverLevel) { + if (serverLevel.getServer().isSameThread()) + return serverLevel.getBlockEntity(pos); + else + return serverLevel.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + } + return null; } @@ -117,7 +119,7 @@ public class BlockValue extends Value return null; return data; } - if (world != null && pos != null) + if (pos != null) { BlockEntity be = getBlockEntity(world, pos); if (be == null) @@ -132,7 +134,7 @@ public class BlockValue extends Value } - public BlockValue(BlockState state, ServerLevel world, BlockPos position) + public BlockValue(BlockState state, @NotNull Level world, BlockPos position) { this.world = world; blockState = state; @@ -140,7 +142,7 @@ public class BlockValue extends Value data = null; } - public BlockValue(BlockState state, ServerLevel world, BlockPos position, CompoundTag nbt) + public BlockValue(BlockState state, @NotNull Level world, BlockPos position, CompoundTag nbt) { this.world = world; blockState = state; @@ -152,13 +154,14 @@ public class BlockValue extends Value @Override public String getString() { - return nameFromRegistryId(BuiltInRegistries.BLOCK.getKey(getBlockState().getBlock())); + Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); + return nameFromRegistryId(blockRegistry.getKey(getBlockState().getBlock())); } @Override public boolean getBoolean() { - return this != NULL && !getBlockState().isAir(); + return !getBlockState().isAir(); } @Override @@ -176,7 +179,7 @@ public class BlockValue extends Value @Override public int hashCode() { - if (world != null && pos != null ) + if (pos != null ) return GlobalPos.of(world.dimension() , pos).hashCode(); //getDimension().getType() return ("b"+getString()).hashCode(); } @@ -186,7 +189,7 @@ public class BlockValue extends Value return pos; } - public ServerLevel getWorld() { return world;} + public Level getWorld() { return world;} @Override public Tag toTag(boolean force) @@ -196,7 +199,7 @@ public class BlockValue extends Value CompoundTag tag = new CompoundTag(); CompoundTag state = new CompoundTag(); BlockState s = getBlockState(); - state.put("Name", StringTag.valueOf(BuiltInRegistries.BLOCK.getKey(s.getBlock()).toString())); + state.put("Name", StringTag.valueOf(world.registryAccess().registryOrThrow(Registries.BLOCK).getKey(s.getBlock()).toString())); Collection> properties = s.getProperties(); if (!properties.isEmpty()) { diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 6141e69e..cdb314bd 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -24,6 +24,8 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -274,7 +276,7 @@ public class EntityValue extends Value } else { - return new EntityClassDescriptor(ANY, e -> !eTag.contains(e.getType()) && e.isAlive(), BuiltInRegistries.ENTITY_TYPE.stream().filter(et -> !eTag.contains(et))); + return new EntityClassDescriptor(ANY, e -> !eTag.contains(e.getType()) && e.isAlive(), server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).stream().filter(et -> !eTag.contains(et))); } } return eDesc; @@ -300,8 +302,9 @@ public class EntityValue extends Value this(type, predicate, types.toList()); } - public Value listValue() { - return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(BuiltInRegistries.ENTITY_TYPE.getKey(et))))); + public Value listValue(RegistryAccess regs) { + final Registry entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE); + return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(entityRegs.getKey(et))))); } public final static Map byName = new HashMap<>() {{ @@ -449,7 +452,7 @@ public class EntityValue extends Value put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName())); put("command_name", (e, a) -> new StringValue(e.getScoreboardName())); put("custom_name", (e, a) -> e.hasCustomName()?new StringValue(e.getCustomName().getString()):Value.NULL); - put("type", (e, a) -> new StringValue(nameFromRegistryId(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType())))); + put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())))); put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger())); put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new).collect(Collectors.toList()))); @@ -529,9 +532,9 @@ public class EntityValue extends Value }); put("item", (e, a) -> { if(e instanceof ItemEntity) - return ValueConversions.of(((ItemEntity) e).getItem()); + return ValueConversions.of(((ItemEntity) e).getItem(), e.getServer().registryAccess()); if(e instanceof ItemFrame) - return ValueConversions.of(((ItemFrame) e).getItem()); + return ValueConversions.of(((ItemFrame) e).getItem(), e.getServer().registryAccess()); return Value.NULL; }); put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getItem().getCount()):Value.NULL); @@ -657,7 +660,7 @@ public class EntityValue extends Value put("brain", (e, a) -> { String module = a.getString(); - MemoryModuleType moduleType = BuiltInRegistries.MEMORY_MODULE_TYPE.get(InputValidator.identifierOf(module)); + MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); if (moduleType == MemoryModuleType.DUMMY) return Value.NULL; if (e instanceof LivingEntity livingEntity) { @@ -820,7 +823,7 @@ public class EntityValue extends Value if (where == null) throw new InternalExpressionException("Unknown inventory slot: "+a.getString()); if (e instanceof LivingEntity) - return ValueConversions.of(((LivingEntity)e).getItemBySlot(where)); + return ValueConversions.of(((LivingEntity)e).getItemBySlot(where), e.getServer().registryAccess()); return Value.NULL; }); @@ -931,13 +934,14 @@ public class EntityValue extends Value put("attribute", (e, a) ->{ if (!(e instanceof LivingEntity)) return Value.NULL; LivingEntity el = (LivingEntity)e; + final Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE); if (a == null) { AttributeMap container = el.getAttributes(); - return MapValue.wrap(BuiltInRegistries.ATTRIBUTE.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(BuiltInRegistries.ATTRIBUTE.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); + return MapValue.wrap(attributes.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(attributes.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); } ResourceLocation id = InputValidator.identifierOf(a.getString()); - Attribute attrib = BuiltInRegistries.ATTRIBUTE.getOptional(id).orElseThrow( + Attribute attrib = attributes.getOptional(id).orElseThrow( () -> new InternalExpressionException("Unknown attribute: "+a.getString()) ); if (!el.getAttributes().hasAttribute(attrib)) return Value.NULL; @@ -1717,7 +1721,8 @@ public class EntityValue extends Value if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); CompoundTag tag = new CompoundTag(); tag.put("Data", getEntity().saveWithoutId( new CompoundTag())); - tag.put("Name", StringTag.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(getEntity().getType()).toString())); + final Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE); + tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString())); return tag; } } diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 80139a9d..8ab0ab78 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -228,7 +228,7 @@ public class ScreenValue extends Value { public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) { Map data = new HashMap<>(); data.put(StringValue.of("slot"),NumericValue.of(slotId)); - data.put(StringValue.of("stack"),ValueConversions.of(stack)); + data.put(StringValue.of("stack"),ValueConversions.of(stack, player.level.registryAccess())); ScreenValue.this.callListener(ScreenValue.this.player,"slot_update",data); } @Override diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 05c4f44c..6b28bfd0 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -11,6 +11,7 @@ import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.Vec3i; import net.minecraft.core.particles.ParticleOptions; @@ -31,6 +32,7 @@ import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities; import net.minecraft.world.entity.ai.memory.WalkTarget; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.pattern.BlockInWorld; import net.minecraft.world.level.block.state.properties.Property; @@ -80,6 +82,7 @@ public class ValueConversions public static Value of(MinMaxBounds range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} + @Deprecated public static Value of(ItemStack stack) { if (stack == null || stack.isEmpty()) @@ -90,6 +93,15 @@ public class ValueConversions NBTSerializableValue.fromStack(stack) ); } + public static Value of(ItemStack stack, RegistryAccess regs) { + if (stack == null || stack.isEmpty()) + return Value.NULL; + return ListValue.of( + of(regs.registryOrThrow(Registries.ITEM).getKey(stack.getItem())), + new NumericValue(stack.getCount()), + NBTSerializableValue.fromStack(stack) + ); + } public static Value of(Objective objective) { @@ -318,7 +330,7 @@ public class ValueConversions ); } - public static Value of(StructureStart structure) + public static Value of(StructureStart structure, final RegistryAccess regs) { if (structure == null || structure == StructureStart.INVALID_START) return Value.NULL; BoundingBox boundingBox = structure.getBoundingBox(); @@ -332,7 +344,7 @@ public class ValueConversions if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ()) { pieces.add(ListValue.of( - new StringValue(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()))), + new StringValue(NBTSerializableValue.nameFromRegistryId(regs.registryOrThrow(Registries.STRUCTURE_PIECE).getKey(piece.getType()))), (piece.getOrientation() == null) ? Value.NULL : new StringValue(piece.getOrientation().getName()), ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ()) @@ -406,9 +418,10 @@ public class ValueConversions public static Value ofBlockPredicate(RegistryAccess registryAccess, Predicate blockPredicate) { BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + final Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); return ListValue.of( - predicateData.getCMBlockState()==null?Value.NULL:of(BuiltInRegistries.BLOCK.getKey(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTagKey()==null?Value.NULL:of(registryAccess.registryOrThrow(Registries.BLOCK).getTag(predicateData.getCMBlockTagKey()).get().key()), + predicateData.getCMBlockState()==null?Value.NULL:of(blocks.getKey(predicateData.getCMBlockState().getBlock())), + predicateData.getCMBlockTagKey()==null?Value.NULL:of(blocks.getTag(predicateData.getCMBlockTagKey()).get().key()), MapValue.wrap(predicateData.getCMProperties()), predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag()) ); @@ -481,7 +494,7 @@ public class ValueConversions if (o instanceof BoundingBox) return of((BoundingBox) o); if (o instanceof ItemStack) - return of((ItemStack)o); + return of((ItemStack)o, serverWorld.registryAccess()); if (o instanceof Boolean) return BooleanValue.of((Boolean) o); if (o instanceof Number) diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index a9431fd8..e1c01773 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -4,7 +4,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.EntityType; @@ -227,6 +229,7 @@ public class BlockInfo Material material = state.getMaterial(); Block block = state.getBlock(); String metastring = ""; + final Registry blocks = world.registryAccess().registryOrThrow(Registries.BLOCK); for (net.minecraft.world.level.block.state.properties.Property iproperty : state.getProperties()) { metastring += ", "+iproperty.getName() + '='+state.getValue(iproperty); @@ -234,7 +237,7 @@ public class BlockInfo List lst = new ArrayList<>(); lst.add(Messenger.s("")); lst.add(Messenger.s("=====================================")); - lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", BuiltInRegistries.BLOCK.getKey(block),metastring, BuiltInRegistries.BLOCK.getId(block), metastring ))); + lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", blocks.getKey(block),metastring, blocks.getId(block), metastring ))); lst.add(Messenger.s(String.format(" - Material: %s", materialName.get(material)))); lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getMapColor(world, pos))))); lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundType(state))))); diff --git a/src/main/java/carpet/utils/CarpetProfiler.java b/src/main/java/carpet/utils/CarpetProfiler.java index 7218db74..a4a02067 100644 --- a/src/main/java/carpet/utils/CarpetProfiler.java +++ b/src/main/java/carpet/utils/CarpetProfiler.java @@ -3,7 +3,9 @@ package carpet.utils; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.RegistryAccess; 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.server.MinecraftServer; @@ -274,13 +276,14 @@ public class CarpetProfiler private static String sectionName(Pair section) { ResourceLocation id; + final RegistryAccess regs = section.getKey().registryAccess(); if (section.getValue() instanceof EntityType) { - id = BuiltInRegistries.ENTITY_TYPE.getKey((EntityType) section.getValue()); + id = regs.registryOrThrow(Registries.ENTITY_TYPE).getKey((EntityType) section.getValue()); } else { - id = BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey((BlockEntityType) section.getValue()); + id = regs.registryOrThrow(Registries.BLOCK_ENTITY_TYPE).getKey((BlockEntityType) section.getValue()); } String name = "minecraft".equals(id.getNamespace())?id.getPath():id.toString(); if (section.getKey().isClientSide) diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index fd49f467..c13fd594 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -8,8 +8,11 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; + +import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; @@ -54,14 +57,14 @@ public class MobAI aiTrackers.get(e).add(type); } - public static List availbleTypes() + public static List availbleTypes(CommandSourceStack source) { Set> types = new HashSet<>(); for (TrackingType type: TrackingType.values()) { types.addAll(type.types); } - return types.stream().map(t -> BuiltInRegistries.ENTITY_TYPE.getKey(t).getPath()).collect(Collectors.toList()); + return types.stream().map(t -> source.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(t).getPath()).collect(Collectors.toList()); } public static List availableFor(EntityType entityType)