refactor limit access to built-in registries

This commit is contained in:
gnembon committed 2023-01-18 04:07:55 +01:00
1 parent 8dd08d5cb1
commit bd5dfdbf9f
25 files changed
+243 -176

No files matched your search

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