Migrate the Carpet codebase to Mojang Mappings
This commit is contained in:
346 files changed
+8353
-8492
No files matched your search
@@ -41,68 +41,64 @@ import carpet.script.value.ValueConversions;
|
||||
import carpet.utils.Messenger;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.command.DataCommandStorage;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.decoration.ArmorStandEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtHelper;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.Rotations;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtIo;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.network.Packet;
|
||||
import net.minecraft.network.packet.s2c.play.ClearTitleS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.PlaySoundIdS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket;
|
||||
//import net.minecraft.network.packet.s2c.play.TitleS2CPacket;
|
||||
//import net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action;
|
||||
import net.minecraft.network.packet.s2c.play.SubtitleS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.TitleFadeS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.TitleS2CPacket;
|
||||
import net.minecraft.particle.ParticleEffect;
|
||||
import net.minecraft.resource.DataPackSettings;
|
||||
import net.minecraft.resource.ReloadableResourceManagerImpl;
|
||||
import net.minecraft.resource.ResourcePackManager;
|
||||
import net.minecraft.resource.ResourcePackProfile;
|
||||
import net.minecraft.resource.ServerResourceManager;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.BaseComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket;
|
||||
import net.minecraft.resources.RegistryReadOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.stat.Stat;
|
||||
import net.minecraft.stat.StatType;
|
||||
import net.minecraft.text.BaseText;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.InvalidIdentifierException;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
import net.minecraft.util.dynamic.RegistryOps;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.ChunkPos;
|
||||
import net.minecraft.util.math.EulerAngle;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.DynamicRegistryManager;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.world.SaveProperties;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.source.BiomeAccess;
|
||||
import net.minecraft.world.border.WorldBorderListener;
|
||||
import net.minecraft.world.dimension.DimensionOptions;
|
||||
import net.minecraft.world.dimension.DimensionType;
|
||||
import net.minecraft.world.gen.GeneratorOptions;
|
||||
import net.minecraft.world.gen.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.UnmodifiableLevelProperties;
|
||||
import net.minecraft.world.level.storage.LevelStorage;
|
||||
import net.minecraft.server.ServerResources;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.packs.repository.Pack;
|
||||
import net.minecraft.server.packs.repository.PackRepository;
|
||||
import net.minecraft.server.packs.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.stats.Stat;
|
||||
import net.minecraft.stats.StatType;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.decoration.ArmorStand;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.BorderChangeListener;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.storage.CommandStorage;
|
||||
import net.minecraft.world.level.storage.DerivedLevelData;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.WorldData;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
@@ -136,7 +132,7 @@ import static java.lang.Math.min;
|
||||
|
||||
public class Auxiliary {
|
||||
public static final String MARKER_STRING = "__scarpet_marker";
|
||||
private static final Map<String, SoundCategory> mixerMap = Arrays.stream(SoundCategory.values()).collect(Collectors.toMap(SoundCategory::getName, k -> k));
|
||||
private static final Map<String, SoundSource> mixerMap = Arrays.stream(SoundSource.values()).collect(Collectors.toMap(SoundSource::getName, k -> k));
|
||||
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().registerTypeAdapter(Value.class, new ScarpetJsonDeserializer()).create();
|
||||
|
||||
@Deprecated
|
||||
@@ -158,16 +154,16 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (lv.size() == 0)
|
||||
{
|
||||
return ListValue.wrap(Registry.SOUND_EVENT.getIds().stream().map(ValueConversions::of));
|
||||
return ListValue.wrap(Registry.SOUND_EVENT.keySet().stream().map(ValueConversions::of));
|
||||
}
|
||||
String rawString = lv.get(0).getString();
|
||||
Identifier soundName = InputValidator.identifierOf(rawString);
|
||||
ResourceLocation soundName = InputValidator.identifierOf(rawString);
|
||||
Vector3Argument locator = Vector3Argument.findIn(lv, 1);
|
||||
if (Registry.SOUND_EVENT.get(soundName) == null)
|
||||
throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND);
|
||||
float volume = 1.0F;
|
||||
float pitch = 1.0F;
|
||||
SoundCategory mixer = SoundCategory.MASTER;
|
||||
SoundSource mixer = SoundSource.MASTER;
|
||||
if (lv.size() > 0+locator.offset)
|
||||
{
|
||||
volume = (float) NumericValue.asNumber(lv.get(0+locator.offset)).getDouble();
|
||||
@@ -182,13 +178,13 @@ public class Auxiliary {
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec3d vec = locator.vec;
|
||||
Vec3 vec = locator.vec;
|
||||
double d0 = Math.pow(volume > 1.0F ? (double)(volume * 16.0F) : 16.0D, 2.0D);
|
||||
int count = 0;
|
||||
for (ServerPlayerEntity player : cc.s.getWorld().getPlayers( (p) -> p.squaredDistanceTo(vec) < d0))
|
||||
for (ServerPlayer player : cc.s.getLevel().getPlayers( (p) -> p.distanceToSqr(vec) < d0))
|
||||
{
|
||||
count++;
|
||||
player.networkHandler.sendPacket(new PlaySoundIdS2CPacket(soundName, mixer, vec, volume, pitch));
|
||||
player.connection.send(new ClientboundCustomSoundPacket(soundName, mixer, vec, volume, pitch));
|
||||
}
|
||||
return new NumericValue(count);
|
||||
});
|
||||
@@ -196,15 +192,15 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.getIds().stream().map(ValueConversions::of));
|
||||
if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of));
|
||||
MinecraftServer ms = cc.s.getServer();
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
Vector3Argument locator = Vector3Argument.findIn(lv, 1);
|
||||
String particleName = lv.get(0).getString();
|
||||
int count = 10;
|
||||
double speed = 0;
|
||||
float spread = 0.5f;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > locator.offset)
|
||||
{
|
||||
count = (int) NumericValue.asNumber(lv.get(locator.offset)).getLong();
|
||||
@@ -216,24 +212,24 @@ public class Auxiliary {
|
||||
speed = NumericValue.asNumber(lv.get(2 + locator.offset)).getDouble();
|
||||
if (lv.size() > 3 + locator.offset) // should accept entity as well as long as it is player
|
||||
{
|
||||
player = ms.getPlayerManager().getPlayer(lv.get(3 + locator.offset).getString());
|
||||
player = ms.getPlayerList().getPlayerByName(lv.get(3 + locator.offset).getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vec3d vec = locator.vec;
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vec3 vec = locator.vec;
|
||||
if (player == null)
|
||||
{
|
||||
for (PlayerEntity p : (world.getPlayers()))
|
||||
for (Player p : (world.players()))
|
||||
{
|
||||
world.spawnParticles((ServerPlayerEntity)p, particle, true, vec.x, vec.y, vec.z, count,
|
||||
world.sendParticles((ServerPlayer)p, particle, true, vec.x, vec.y, vec.z, count,
|
||||
spread, spread, spread, speed);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
world.spawnParticles(player,
|
||||
world.sendParticles(player,
|
||||
particle, true, vec.x, vec.y, vec.z, count,
|
||||
spread, spread, spread, speed);
|
||||
}
|
||||
@@ -244,13 +240,13 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle_line", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
String particleName = lv.get(0).getString();
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vector3Argument pos1 = Vector3Argument.findIn(lv, 1);
|
||||
Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset);
|
||||
double density = 1.0;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > pos2.offset+0 )
|
||||
{
|
||||
density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble();
|
||||
@@ -264,18 +260,18 @@ public class Auxiliary {
|
||||
if (playerValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) playerValue).getEntity();
|
||||
if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_line' player argument has to be a player");
|
||||
player = (ServerPlayerEntity) e;
|
||||
if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_line' player argument has to be a player");
|
||||
player = (ServerPlayer) e;
|
||||
}
|
||||
else
|
||||
{
|
||||
player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString());
|
||||
player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new NumericValue(ShapeDispatcher.drawParticleLine(
|
||||
(player == null)?world.getPlayers(): Collections.singletonList(player),
|
||||
(player == null)?world.players(): Collections.singletonList(player),
|
||||
particle, pos1.vec, pos2.vec, density
|
||||
));
|
||||
});
|
||||
@@ -283,14 +279,14 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle_box", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
String particleName = lv.get(0).getString();
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vector3Argument pos1 = Vector3Argument.findIn(lv, 1);
|
||||
Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset);
|
||||
|
||||
double density = 1.0;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > pos2.offset+0 )
|
||||
{
|
||||
density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble();
|
||||
@@ -304,21 +300,21 @@ public class Auxiliary {
|
||||
if (playerValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) playerValue).getEntity();
|
||||
if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_box' player argument has to be a player");
|
||||
player = (ServerPlayerEntity) e;
|
||||
if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_box' player argument has to be a player");
|
||||
player = (ServerPlayer) e;
|
||||
}
|
||||
else
|
||||
{
|
||||
player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString());
|
||||
player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec3d a = pos1.vec;
|
||||
Vec3d b = pos2.vec;
|
||||
Vec3d from = new Vec3d(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
|
||||
Vec3d to = new Vec3d(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
|
||||
Vec3 a = pos1.vec;
|
||||
Vec3 b = pos2.vec;
|
||||
Vec3 from = new Vec3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
|
||||
Vec3 to = new Vec3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
|
||||
int particleCount = ShapeDispatcher.Box.particleMesh(
|
||||
player==null?world.getPlayers():Collections.singletonList(player),
|
||||
player==null?world.players():Collections.singletonList(player),
|
||||
particle, density, from, to
|
||||
);
|
||||
return new NumericValue(particleCount);
|
||||
@@ -330,9 +326,9 @@ public class Auxiliary {
|
||||
expression.addContextFunction("draw_shape", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
MinecraftServer server = world.getServer();
|
||||
Set<ServerPlayerEntity> playerTargets = new HashSet<>();
|
||||
Set<ServerPlayer> playerTargets = new HashSet<>();
|
||||
List<ShapeDispatcher.ShapeWithConfig> shapes = new ArrayList<>();
|
||||
if (lv.size() == 1) // bulk
|
||||
{
|
||||
@@ -350,7 +346,7 @@ public class Auxiliary {
|
||||
}
|
||||
|
||||
ShapeDispatcher.sendShape(
|
||||
(playerTargets.isEmpty())?cc.s.getWorld().getPlayers():playerTargets,
|
||||
(playerTargets.isEmpty())?cc.s.getLevel().players():playerTargets,
|
||||
shapes
|
||||
);
|
||||
return Value.TRUE;
|
||||
@@ -382,7 +378,7 @@ public class Auxiliary {
|
||||
throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head");
|
||||
}
|
||||
|
||||
ArmorStandEntity armorstand = new ArmorStandEntity(EntityType.ARMOR_STAND, cc.s.getWorld());
|
||||
ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, cc.s.getLevel());
|
||||
double yoffset;
|
||||
if (targetBlock == null && name.isEmpty())
|
||||
{
|
||||
@@ -396,14 +392,14 @@ public class Auxiliary {
|
||||
{
|
||||
if (targetBlock==null)
|
||||
{
|
||||
yoffset = -armorstand.getHeight()-0.41;
|
||||
yoffset = -armorstand.getBbHeight()-0.41;
|
||||
}
|
||||
else
|
||||
{
|
||||
yoffset = -armorstand.getHeight()+0.3;
|
||||
yoffset = -armorstand.getBbHeight()+0.3;
|
||||
}
|
||||
}
|
||||
armorstand.refreshPositionAndAngles(
|
||||
armorstand.moveTo(
|
||||
pointLocator.vec.x,
|
||||
//pointLocator.vec.y - ((!interactable && targetBlock == null)?0.41f:((targetBlock==null)?(armorstand.getHeight()+0.41):(armorstand.getHeight()-0.3))),
|
||||
pointLocator.vec.y + yoffset,
|
||||
@@ -411,21 +407,21 @@ public class Auxiliary {
|
||||
(float)pointLocator.yaw,
|
||||
(float) pointLocator.pitch
|
||||
);
|
||||
armorstand.addScoreboardTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()));
|
||||
armorstand.addScoreboardTag(MARKER_STRING);
|
||||
armorstand.addTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()));
|
||||
armorstand.addTag(MARKER_STRING);
|
||||
if (targetBlock != null)
|
||||
armorstand.equipStack(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem()));
|
||||
armorstand.setItemSlot(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem()));
|
||||
if (!name.isEmpty())
|
||||
{
|
||||
armorstand.setCustomName(new LiteralText(name));
|
||||
armorstand.setCustomName(new TextComponent(name));
|
||||
armorstand.setCustomNameVisible(true);
|
||||
}
|
||||
armorstand.setHeadRotation(new EulerAngle((int)pointLocator.pitch,0,0));
|
||||
armorstand.setHeadPose(new Rotations((int)pointLocator.pitch,0,0));
|
||||
armorstand.setNoGravity(true);
|
||||
armorstand.setInvisible(true);
|
||||
armorstand.setInvulnerable(true);
|
||||
armorstand.getDataTracker().set(ArmorStandEntity.ARMOR_STAND_FLAGS, (byte)(interactable?8 : 16|8));
|
||||
cc.s.getWorld().spawnEntity(armorstand);
|
||||
armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte)(interactable?8 : 16|8));
|
||||
cc.s.getLevel().addFreshEntity(armorstand);
|
||||
return new EntityValue(armorstand);
|
||||
});
|
||||
|
||||
@@ -433,7 +429,7 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
int total = 0;
|
||||
String markerName = MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName());
|
||||
for (Entity e : cc.s.getWorld().getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName)))
|
||||
for (Entity e : cc.s.getLevel().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName)))
|
||||
{
|
||||
total ++;
|
||||
e.discard(); // discard // remove();
|
||||
@@ -443,7 +439,7 @@ public class Auxiliary {
|
||||
|
||||
expression.addUnaryFunction("nbt", NBTSerializableValue::fromValue);
|
||||
|
||||
expression.addUnaryFunction("escape_nbt", v -> new StringValue(NbtString.escape(v.getString())));
|
||||
expression.addUnaryFunction("escape_nbt", v -> new StringValue(StringTag.quoteAndEscape(v.getString())));
|
||||
|
||||
expression.addUnaryFunction("parse_nbt", v -> {
|
||||
if (v instanceof NBTSerializableValue) return ((NBTSerializableValue) v).toValue();
|
||||
@@ -457,9 +453,9 @@ public class Auxiliary {
|
||||
if (numParam != 2 && numParam != 3) throw new InternalExpressionException("'tag_matches' requires 2 or 3 arguments");
|
||||
if (lv.get(1).isNull()) return Value.TRUE;
|
||||
if (lv.get(0).isNull()) return Value.FALSE;
|
||||
NbtElement source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag();
|
||||
NbtElement match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag();
|
||||
return BooleanValue.of(NbtHelper.matches(match, source, numParam == 2 || lv.get(2).getBoolean()));
|
||||
Tag source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag();
|
||||
Tag match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag();
|
||||
return BooleanValue.of(NbtUtils.compareNbt(match, source, numParam == 2 || lv.get(2).getBoolean()));
|
||||
});
|
||||
|
||||
expression.addFunction("encode_nbt", lv -> {
|
||||
@@ -467,7 +463,7 @@ public class Auxiliary {
|
||||
if (argSize==0 || argSize > 2) throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters");
|
||||
Value v = lv.get(0);
|
||||
boolean force = (argSize > 1) && lv.get(1).getBoolean();
|
||||
NbtElement tag;
|
||||
Tag tag;
|
||||
try
|
||||
{
|
||||
tag = v.toTag(force);
|
||||
@@ -483,30 +479,30 @@ public class Auxiliary {
|
||||
expression.addContextFunction("print", -1, (c, t, lv) ->
|
||||
{
|
||||
if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments");
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
MinecraftServer server = s.getServer();
|
||||
Value res = lv.get(0);
|
||||
List<ServerPlayerEntity> targets = null;
|
||||
List<ServerPlayer> targets = null;
|
||||
if (lv.size() == 2)
|
||||
{
|
||||
List<Value> playerValues = (res instanceof ListValue)?((ListValue) res).getItems():Collections.singletonList(res);
|
||||
List<ServerPlayerEntity> playerTargets = new ArrayList<>();
|
||||
List<ServerPlayer> playerTargets = new ArrayList<>();
|
||||
playerValues.forEach(pv -> {
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pv);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, pv);
|
||||
if (player == null) throw new InternalExpressionException("Cannot target player "+pv.getString()+" in print");
|
||||
playerTargets.add(player);
|
||||
});
|
||||
targets = playerTargets;
|
||||
res = lv.get(1);
|
||||
}
|
||||
Text message = FormattedTextValue.getTextByValue(res);
|
||||
Component message = FormattedTextValue.getTextByValue(res);
|
||||
if (targets == null)
|
||||
{
|
||||
s.sendFeedback(message, false);
|
||||
s.sendSuccess(message, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
targets.forEach(p -> p.getCommandSource().sendFeedback(message, false));
|
||||
targets.forEach(p -> p.createCommandSourceStack().sendSuccess(message, false));
|
||||
}
|
||||
return res; // pass through for variables
|
||||
});
|
||||
@@ -516,40 +512,40 @@ public class Auxiliary {
|
||||
Value pVal = lv.get(0);
|
||||
if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal);
|
||||
MinecraftServer server = ((CarpetContext)c).s.getServer();
|
||||
Stream<ServerPlayerEntity> targets = ((ListValue) pVal).getItems().stream().map(v ->
|
||||
Stream<ServerPlayer> targets = ((ListValue) pVal).getItems().stream().map(v ->
|
||||
{
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, v);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, v);
|
||||
if (player == null) throw new InternalExpressionException("'display_title' requires a valid online player or a list of players as first argument. "+v.getString()+" is not a player.");
|
||||
return player;
|
||||
});
|
||||
Function<Text, Packet<?>> packetGetter = null;
|
||||
Function<Component, Packet<?>> packetGetter = null;
|
||||
//TitleS2CPacket.Action action;
|
||||
String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT);
|
||||
switch (actionString)
|
||||
{
|
||||
case "title":
|
||||
packetGetter = TitleS2CPacket::new;
|
||||
packetGetter = ClientboundSetTitleTextPacket::new;
|
||||
//action = Action.TITLE;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
break;
|
||||
case "subtitle":
|
||||
packetGetter = SubtitleS2CPacket::new;
|
||||
packetGetter = ClientboundSetSubtitleTextPacket::new;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
//action = Action.SUBTITLE;
|
||||
break;
|
||||
case "actionbar":
|
||||
packetGetter = OverlayMessageS2CPacket::new;
|
||||
packetGetter = ClientboundSetActionBarTextPacket::new;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
//action = Action.ACTIONBAR;
|
||||
break;
|
||||
case "clear":
|
||||
packetGetter = (x) -> new ClearTitleS2CPacket(true); // resetting default fade
|
||||
packetGetter = (x) -> new ClientboundClearTitlesPacket(true); // resetting default fade
|
||||
//action = Action.CLEAR;
|
||||
break;
|
||||
case "player_list_header":
|
||||
@@ -560,7 +556,7 @@ public class Auxiliary {
|
||||
}
|
||||
//if (action != Action.CLEAR && lv.size() < 3)
|
||||
// throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
Text title;
|
||||
Component title;
|
||||
boolean soundsTrue = false;
|
||||
if (lv.size() > 2)
|
||||
{
|
||||
@@ -571,35 +567,35 @@ public class Auxiliary {
|
||||
else title = null; // Will never happen, just to make lambda happy
|
||||
if (packetGetter == null)
|
||||
{
|
||||
Map<String, BaseText> map;
|
||||
Map<String, BaseComponent> map;
|
||||
if (actionString.equals("player_list_header"))
|
||||
map = HUDController.scarpet_headers;
|
||||
else
|
||||
map = HUDController.scarpet_footers;
|
||||
|
||||
AtomicInteger total = new AtomicInteger(0);
|
||||
List<ServerPlayerEntity> targetList = targets.collect(Collectors.toList());
|
||||
List<ServerPlayer> targetList = targets.collect(Collectors.toList());
|
||||
if (!soundsTrue) // null or empty string
|
||||
targetList.forEach(target -> {
|
||||
map.remove(target.getEntityName());
|
||||
map.remove(target.getScoreboardName());
|
||||
total.getAndIncrement();
|
||||
});
|
||||
else
|
||||
targetList.forEach(target -> {
|
||||
map.put(target.getEntityName(), (BaseText) title);
|
||||
map.put(target.getScoreboardName(), (BaseComponent) title);
|
||||
total.getAndIncrement();
|
||||
});
|
||||
HUDController.update_hud(((CarpetContext)c).s.getServer(), targetList);
|
||||
return NumericValue.of(total.get());
|
||||
}
|
||||
TitleFadeS2CPacket timesPacket; // TimesPacket
|
||||
ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket
|
||||
if (lv.size() > 3)
|
||||
{
|
||||
if (lv.size() != 6) throw new InternalExpressionException("'display_title' needs all fade-in, stay and fade-out times");
|
||||
int in = NumericValue.asNumber(lv.get(3),"fade in for display_title" ).getInt();
|
||||
int stay = NumericValue.asNumber(lv.get(4),"stay for display_title" ).getInt();
|
||||
int out = NumericValue.asNumber(lv.get(5),"fade out for display_title" ).getInt();
|
||||
timesPacket = new TitleFadeS2CPacket(in, stay, out);
|
||||
timesPacket = new ClientboundSetTitlesAnimationPacket(in, stay, out);
|
||||
//timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out);
|
||||
}
|
||||
else timesPacket = null;
|
||||
@@ -608,8 +604,8 @@ public class Auxiliary {
|
||||
//TitleS2CPacket packet = new TitleS2CPacket(action, title);
|
||||
AtomicInteger total = new AtomicInteger(0);
|
||||
targets.forEach(p -> {
|
||||
if (timesPacket != null) p.networkHandler.sendPacket(timesPacket);
|
||||
p.networkHandler.sendPacket(packet);
|
||||
if (timesPacket != null) p.connection.send(timesPacket);
|
||||
p.connection.send(packet);
|
||||
total.getAndIncrement();
|
||||
});
|
||||
return NumericValue.of(total.get());
|
||||
@@ -624,12 +620,12 @@ public class Auxiliary {
|
||||
|
||||
expression.addContextFunction("run", 1, (c, t, lv) ->
|
||||
{
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
try
|
||||
{
|
||||
Text[] error = {null};
|
||||
List<Text> output = new ArrayList<>();
|
||||
Value retval = new NumericValue(s.getServer().getCommandManager().execute(
|
||||
Component[] error = {null};
|
||||
List<Component> output = new ArrayList<>();
|
||||
Value retval = new NumericValue(s.getServer().getCommands().performCommand(
|
||||
new SnoopyCommandSource(s, error, output),
|
||||
lv.get(0).getString())
|
||||
);
|
||||
@@ -641,39 +637,39 @@ public class Auxiliary {
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new LiteralText(exc.getMessage())));
|
||||
return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new TextComponent(exc.getMessage())));
|
||||
}
|
||||
});
|
||||
|
||||
expression.addContextFunction("save", 0, (c, t, lv) ->
|
||||
{
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
s.getServer().getPlayerManager().saveAllPlayerData();
|
||||
s.getServer().save(true,true,true);
|
||||
for (ServerWorld world : s.getServer().getWorlds())
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
s.getServer().getPlayerList().saveAll();
|
||||
s.getServer().saveAllChunks(true,true,true);
|
||||
for (ServerLevel world : s.getServer().getAllLevels())
|
||||
{
|
||||
world.getChunkManager().tick(() -> true, false);
|
||||
world.getChunkSource().tick(() -> true, false);
|
||||
}
|
||||
CarpetScriptServer.LOG.warn("Saved chunks");
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
expression.addContextFunction("tick_time", 0, (c, t, lv) ->
|
||||
new NumericValue(((CarpetContext) c).s.getServer().getTicks()));
|
||||
new NumericValue(((CarpetContext) c).s.getServer().getTickCount()));
|
||||
|
||||
expression.addContextFunction("world_time", 0, (c, t, lv) -> {
|
||||
c.host.issueDeprecation("world_time()");
|
||||
return new NumericValue(((CarpetContext) c).s.getWorld().getTime());
|
||||
return new NumericValue(((CarpetContext) c).s.getLevel().getGameTime());
|
||||
});
|
||||
|
||||
expression.addContextFunction("day_time", -1, (c, t, lv) ->
|
||||
{
|
||||
Value time = new NumericValue(((CarpetContext) c).s.getWorld().getTimeOfDay());
|
||||
Value time = new NumericValue(((CarpetContext) c).s.getLevel().getDayTime());
|
||||
if (lv.size() > 0)
|
||||
{
|
||||
long newTime = NumericValue.asNumber(lv.get(0)).getLong();
|
||||
if (newTime < 0) newTime = 0;
|
||||
((CarpetContext) c).s.getWorld().setTimeOfDay(newTime);// setTimeOfDay(newTime);
|
||||
((CarpetContext) c).s.getLevel().setDayTime(newTime);// setTimeOfDay(newTime);
|
||||
}
|
||||
return time;
|
||||
});
|
||||
@@ -687,9 +683,9 @@ public class Auxiliary {
|
||||
|
||||
expression.addContextFunction("game_tick", -1, (c, t, lv) -> {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerCommandSource s = cc.s;
|
||||
CommandSourceStack s = cc.s;
|
||||
if (CarpetServer.scriptServer == null) return Value.NULL;
|
||||
if (!s.getServer().isOnThread()) throw new InternalExpressionException("Unable to run ticks from threads");
|
||||
if (!s.getServer().isSameThread()) throw new InternalExpressionException("Unable to run ticks from threads");
|
||||
if (CarpetServer.scriptServer.tickDepth > 16) throw new InternalExpressionException("'game_tick' function caused other 'game_tick' functions to run. You should not allow that.");
|
||||
try
|
||||
{
|
||||
@@ -725,9 +721,9 @@ public class Auxiliary {
|
||||
});
|
||||
|
||||
expression.addContextFunction("seed", -1, (c, t, lv) -> {
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
c.host.issueDeprecation("seed()");
|
||||
return new NumericValue(s.getWorld().getSeed());
|
||||
return new NumericValue(s.getLevel().getSeed());
|
||||
});
|
||||
|
||||
expression.addContextFunction("relight", -1, (c, t, lv) ->
|
||||
@@ -735,28 +731,28 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
BlockArgument locator = BlockArgument.findIn(cc, lv, 0);
|
||||
BlockPos pos = locator.block.getPos();
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
((ThreadedAnvilChunkStorageInterface) world.getChunkManager().threadedAnvilChunkStorage).relightChunk(new ChunkPos(pos));
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos));
|
||||
WorldTools.forceChunkUpdate(pos, world);
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
// Should this be deprecated for system_info('source_dimension')?
|
||||
expression.addContextFunction("current_dimension", 0, (c, t, lv) ->
|
||||
ValueConversions.of( ((CarpetContext)c).s.getWorld()));
|
||||
ValueConversions.of( ((CarpetContext)c).s.getLevel()));
|
||||
|
||||
expression.addContextFunction("view_distance", 0, (c, t, lv) -> {
|
||||
c.host.issueDeprecation("view_distance()");
|
||||
return new NumericValue(((CarpetContext)c).s.getServer().getPlayerManager().getViewDistance());
|
||||
return new NumericValue(((CarpetContext)c).s.getServer().getPlayerList().getViewDistance());
|
||||
});
|
||||
|
||||
// lazy due to passthrough and context changing ability
|
||||
expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> {
|
||||
ServerCommandSource outerSource = ((CarpetContext)c).s;
|
||||
CommandSourceStack outerSource = ((CarpetContext)c).s;
|
||||
Value dimensionValue = lv.get(0).evalValue(c);
|
||||
World world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer());
|
||||
if (world == outerSource.getWorld()) return lv.get(1);
|
||||
ServerCommandSource innerSource = outerSource.withWorld((ServerWorld)world);
|
||||
Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer());
|
||||
if (world == outerSource.getLevel()) return lv.get(1);
|
||||
CommandSourceStack innerSource = outerSource.withLevel((ServerLevel)world);
|
||||
Context newCtx = c.recreate();
|
||||
((CarpetContext) newCtx).s = innerSource;
|
||||
newCtx.variables = c.variables;
|
||||
@@ -769,21 +765,21 @@ public class Auxiliary {
|
||||
{
|
||||
Map<Value, Value> plopData = new HashMap<>();
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
DynamicRegistryManager registryManager = cc.s.getWorld().getRegistryManager();
|
||||
RegistryAccess registryManager = cc.s.getLevel().registryAccess();
|
||||
plopData.put(StringValue.of("scarpet_custom"),
|
||||
ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("features"),
|
||||
ListValue.wrap(Registry.FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(Registry.FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("configured_features"),
|
||||
ListValue.wrap(registryManager.get(Registry.CONFIGURED_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("structures"),
|
||||
ListValue.wrap(Registry.STRUCTURE_FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(Registry.STRUCTURE_FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("configured_structures"),
|
||||
ListValue.wrap(registryManager.get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
return MapValue.wrap(plopData);
|
||||
}
|
||||
@@ -792,14 +788,14 @@ public class Auxiliary {
|
||||
throw new InternalExpressionException("'plop' needs extra argument indicating what to plop");
|
||||
String what = lv.get(locator.offset).getString();
|
||||
Value [] result = new Value[]{Value.NULL};
|
||||
((CarpetContext)c).s.getServer().submitAndJoin( () ->
|
||||
((CarpetContext)c).s.getServer().executeBlocking( () ->
|
||||
{
|
||||
Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getWorld(), locator.block.getPos());
|
||||
Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getLevel(), locator.block.getPos());
|
||||
|
||||
if (res == null)
|
||||
return;
|
||||
if (what.equalsIgnoreCase("boulder")) // there might be more of those
|
||||
WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getWorld());
|
||||
WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getLevel());
|
||||
result[0] = BooleanValue.of(res);
|
||||
});
|
||||
return result[0];
|
||||
@@ -861,7 +857,7 @@ public class Auxiliary {
|
||||
Value retVal;
|
||||
if (fdesc.type == FileArgument.Type.NBT)
|
||||
{
|
||||
NbtElement state = ((CarpetScriptHost) c.host).readFileTag(fdesc);
|
||||
Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc);
|
||||
if (state == null) return Value.NULL;
|
||||
retVal = new NBTSerializableValue(state);
|
||||
}
|
||||
@@ -898,7 +894,7 @@ public class Auxiliary {
|
||||
NBTSerializableValue tagValue = (val instanceof NBTSerializableValue)
|
||||
? (NBTSerializableValue) val
|
||||
: new NBTSerializableValue(val.getString());
|
||||
NbtElement tag = tagValue.getTag();
|
||||
Tag tag = tagValue.getTag();
|
||||
success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc);
|
||||
}
|
||||
else if (fdesc.type == FileArgument.Type.JSON)
|
||||
@@ -970,17 +966,17 @@ public class Auxiliary {
|
||||
expression.addContextFunction("statistic", 3, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0));
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0));
|
||||
if (player == null) return Value.NULL;
|
||||
Identifier category;
|
||||
Identifier statName;
|
||||
ResourceLocation category;
|
||||
ResourceLocation statName;
|
||||
category = InputValidator.identifierOf(lv.get(1).getString());
|
||||
statName = InputValidator.identifierOf(lv.get(2).getString());
|
||||
StatType<?> type = Registry.STAT_TYPE.get(category);
|
||||
if (type == null) return Value.NULL;
|
||||
Stat<?> stat = getStat(type, statName);
|
||||
if (stat == null) return Value.NULL;
|
||||
return new NumericValue(player.getStatHandler().getStat(stat));
|
||||
return new NumericValue(player.getStats().getValue(stat));
|
||||
});
|
||||
|
||||
//handle_event('event', function...)
|
||||
@@ -1006,7 +1002,7 @@ public class Auxiliary {
|
||||
String eventName = lv.get(0).getString();
|
||||
// no such event yet
|
||||
if (CarpetEventServer.Event.getEvent(eventName, server) == null) return Value.NULL;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
List<Value> args = Collections.emptyList();
|
||||
if (lv.size() > 1)
|
||||
{
|
||||
@@ -1024,11 +1020,11 @@ public class Auxiliary {
|
||||
expression.addContextFunction("nbt_storage", -1, (c, t, lv) -> {
|
||||
if (lv.size() > 2) throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments.");
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
DataCommandStorage storage = cc.s.getServer().getDataCommandStorage();
|
||||
CommandStorage storage = cc.s.getServer().getCommandStorage();
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(storage.getIds().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList()));
|
||||
return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList()));
|
||||
String key = lv.get(0).getString();
|
||||
NbtCompound old_nbt = storage.get(InputValidator.identifierOf(key));
|
||||
CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key));
|
||||
if (lv.size() == 2) {
|
||||
Value nbt = lv.get(1);
|
||||
NBTSerializableValue new_nbt = (nbt instanceof NBTSerializableValue) ? (NBTSerializableValue) nbt
|
||||
@@ -1044,7 +1040,7 @@ public class Auxiliary {
|
||||
String origName = lv.get(0).getString();
|
||||
String name = InputValidator.validateSimpleString(origName, true);
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
for (String dpName : server.getDataPackManager().getNames())
|
||||
for (String dpName : server.getPackRepository().getAvailableIds())
|
||||
{
|
||||
if (dpName.equalsIgnoreCase("file/"+name+".zip") ||
|
||||
dpName.equalsIgnoreCase("file/"+name))
|
||||
@@ -1054,12 +1050,12 @@ public class Auxiliary {
|
||||
Value dpdata = lv.get(1);
|
||||
if (!(dpdata instanceof MapValue))
|
||||
throw new InternalExpressionException("datapack data needs to be a valid map type");
|
||||
ResourcePackManager packManager = server.getDataPackManager();
|
||||
Path dbFloder = server.getSavePath(WorldSavePath.DATAPACKS);
|
||||
PackRepository packManager = server.getPackRepository();
|
||||
Path dbFloder = server.getWorldPath(LevelResource.DATAPACK_DIR);
|
||||
Path packFloder = dbFloder.resolve(name+".zip");
|
||||
if (Files.exists(packFloder) || Files.exists(dbFloder.resolve(name))) return Value.NULL;
|
||||
Boolean [] successful = new Boolean[]{true};
|
||||
server.submitAndJoin( () ->
|
||||
server.executeBlocking( () ->
|
||||
{
|
||||
try {
|
||||
//Files.createDirectory(packFloder);
|
||||
@@ -1067,23 +1063,23 @@ public class Auxiliary {
|
||||
Path zipRoot = zipfs.getPath("/");
|
||||
zipValueToJson(zipRoot.resolve("pack.mcmeta"), MapValue.wrap(
|
||||
Map.of(StringValue.of("pack"), MapValue.wrap(Map.of(
|
||||
StringValue.of("pack_format"), new NumericValue(SharedConstants.getGameVersion().getPackVersion()),
|
||||
StringValue.of("pack_format"), new NumericValue(SharedConstants.getCurrentVersion().getPackVersion()),
|
||||
StringValue.of("description"), StringValue.of(name),
|
||||
StringValue.of("source"), StringValue.of("scarpet")
|
||||
)))
|
||||
));
|
||||
walkTheDPMap((MapValue) dpdata, zipRoot);
|
||||
}
|
||||
packManager.scanPacks();
|
||||
ResourcePackProfile resourcePackProfile = packManager.getProfile("file/" + name + ".zip");
|
||||
if (resourcePackProfile == null || packManager.getEnabledProfiles().contains(resourcePackProfile)) {
|
||||
packManager.reload();
|
||||
Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip");
|
||||
if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) {
|
||||
throw new IOException();
|
||||
}
|
||||
List<ResourcePackProfile> list = Lists.newArrayList(packManager.getEnabledProfiles());
|
||||
resourcePackProfile.getInitialPosition().insert(list, resourcePackProfile, p -> p, false);
|
||||
List<Pack> list = Lists.newArrayList(packManager.getSelectedPacks());
|
||||
resourcePackProfile.getDefaultPosition().insert(list, resourcePackProfile, p -> p, false);
|
||||
|
||||
|
||||
server.reloadResources(list.stream().map(ResourcePackProfile::getName).collect(Collectors.toList())).
|
||||
server.reloadResources(list.stream().map(Pack::getId).collect(Collectors.toList())).
|
||||
exceptionally(exc -> {
|
||||
successful[0] = false;
|
||||
return null;
|
||||
@@ -1109,44 +1105,44 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
// from minecraft.server.Main.main
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
LevelStorage.Session session = ((MinecraftServerInterface)server).getCMSession();
|
||||
DataPackSettings dataPackSettings = session.getDataPackSettings();
|
||||
ResourcePackManager resourcePackManager = server.getDataPackManager();
|
||||
DataPackSettings dataPackSettings2 = MinecraftServer.loadDataPacks(resourcePackManager, dataPackSettings == null ? DataPackSettings.SAFE_MODE : dataPackSettings, false);
|
||||
ServerResourceManager serverRM = ((MinecraftServerInterface)server).getResourceManager();
|
||||
ReloadableResourceManagerImpl resourceManager = (ReloadableResourceManagerImpl) serverRM.getResourceManager();
|
||||
LevelStorageSource.LevelStorageAccess session = ((MinecraftServerInterface)server).getCMSession();
|
||||
DataPackConfig dataPackSettings = session.getDataPacks();
|
||||
PackRepository resourcePackManager = server.getPackRepository();
|
||||
DataPackConfig dataPackSettings2 = MinecraftServer.configurePackRepository(resourcePackManager, dataPackSettings == null ? DataPackConfig.DEFAULT : dataPackSettings, false);
|
||||
ServerResources serverRM = ((MinecraftServerInterface)server).getResourceManager();
|
||||
SimpleReloadableResourceManager resourceManager = (SimpleReloadableResourceManager) serverRM.getResourceManager();
|
||||
|
||||
//believe the other one will fillup based on the datapacks only.
|
||||
resourceManager.close();
|
||||
resourcePackManager.createResourcePacks().forEach(resourceManager::addPack);
|
||||
resourcePackManager.openAllSelected().forEach(resourceManager::add);
|
||||
|
||||
//not sure its needed, but doesn't seem to have a negative effect and might be used in some custom shtuff
|
||||
serverRM.loadRegistryTags();
|
||||
serverRM.updateGlobals();
|
||||
|
||||
RegistryOps<NbtElement> registryOps = RegistryOps.of(NbtOps.INSTANCE, serverRM.getResourceManager(), (DynamicRegistryManager.Impl) server.getRegistryManager());
|
||||
SaveProperties saveProperties = session.readLevelProperties(registryOps, dataPackSettings2);
|
||||
RegistryReadOps<Tag> registryOps = RegistryReadOps.create(NbtOps.INSTANCE, serverRM.getResourceManager(), (RegistryAccess.RegistryHolder) server.registryAccess());
|
||||
WorldData saveProperties = session.getDataTag(registryOps, dataPackSettings2);
|
||||
if (saveProperties == null) return Value.NULL;
|
||||
//session.backupLevelDataFile(server.getRegistryManager(), saveProperties); // no need
|
||||
|
||||
// MinecraftServer.createWorlds
|
||||
// save properties should now contain dimension settings
|
||||
GeneratorOptions generatorOptions = saveProperties.getGeneratorOptions();
|
||||
boolean bl = generatorOptions.isDebugWorld();
|
||||
long l = generatorOptions.getSeed();
|
||||
long m = BiomeAccess.hashSeed(l);
|
||||
Map<RegistryKey<World>, ServerWorld> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds();
|
||||
WorldGenSettings generatorOptions = saveProperties.worldGenSettings();
|
||||
boolean bl = generatorOptions.isDebug();
|
||||
long l = generatorOptions.seed();
|
||||
long m = BiomeManager.obfuscateSeed(l);
|
||||
Map<ResourceKey<Level>, ServerLevel> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds();
|
||||
List<Value> addeds = new ArrayList<>();
|
||||
for (Map.Entry<RegistryKey<DimensionOptions>, DimensionOptions> entry : generatorOptions.getDimensions().getEntries()) {
|
||||
RegistryKey<DimensionOptions> registryKey = entry.getKey();
|
||||
for (Map.Entry<ResourceKey<LevelStem>, LevelStem> entry : generatorOptions.dimensions().entrySet()) {
|
||||
ResourceKey<LevelStem> registryKey = entry.getKey();
|
||||
if (!existing_worlds.containsKey(registryKey))
|
||||
{
|
||||
addeds.add(ValueConversions.of(registryKey.getValue()));
|
||||
RegistryKey<World> registryKey2 = RegistryKey.of(Registry.WORLD_KEY, registryKey.getValue());
|
||||
DimensionType dimensionType3 = entry.getValue().getDimensionType();
|
||||
ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator();
|
||||
UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM());
|
||||
ServerWorld serverWorld2 = new ServerWorld(server, Util.getMainWorkerExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false);
|
||||
server.getOverworld().getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld2.getWorldBorder()));
|
||||
addeds.add(ValueConversions.of(registryKey.location()));
|
||||
ResourceKey<Level> registryKey2 = ResourceKey.create(Registry.DIMENSION_REGISTRY, registryKey.location());
|
||||
DimensionType dimensionType3 = entry.getValue().type();
|
||||
ChunkGenerator chunkGenerator3 = entry.getValue().generator();
|
||||
DerivedLevelData unmodifiableLevelProperties = new DerivedLevelData(saveProperties, ((ServerWorldInterface) server.overworld()).getWorldPropertiesCM());
|
||||
ServerLevel serverWorld2 = new ServerLevel(server, Util.backgroundExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false);
|
||||
server.overworld().getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld2.getWorldBorder()));
|
||||
existing_worlds.put(registryKey2, serverWorld2);
|
||||
}
|
||||
}
|
||||
@@ -1240,14 +1236,14 @@ public class Auxiliary {
|
||||
NBTSerializableValue tagValue = (output instanceof NBTSerializableValue)
|
||||
? (NBTSerializableValue) output
|
||||
: new NBTSerializableValue(output.getString());
|
||||
NbtElement tag = tagValue.getTag();
|
||||
Tag tag = tagValue.getTag();
|
||||
Files.createDirectories(path.getParent());
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
if (tag instanceof NbtCompound)
|
||||
NbtIo.writeCompressed((NbtCompound) tag, Files.newOutputStream(path));
|
||||
if (tag instanceof CompoundTag)
|
||||
NbtIo.writeCompressed((CompoundTag) tag, Files.newOutputStream(path));
|
||||
}
|
||||
catch (Throwable shitHappened)
|
||||
{
|
||||
@@ -1282,11 +1278,11 @@ public class Auxiliary {
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Stat<T> getStat(StatType<T> type, Identifier id)
|
||||
private static <T> Stat<T> getStat(StatType<T> type, ResourceLocation id)
|
||||
{
|
||||
T key = type.getRegistry().get(id);
|
||||
if (key == null || !type.hasStat(key))
|
||||
if (key == null || !type.contains(key))
|
||||
return null;
|
||||
return type.getOrCreateStat(key);
|
||||
return type.get(key);
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,13 @@ import carpet.script.value.LazyListValue;
|
||||
import carpet.script.value.ListValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3i;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.util.Mth;
|
||||
|
||||
import static java.lang.Math.abs;
|
||||
import static java.lang.Math.max;
|
||||
@@ -217,11 +216,11 @@ public class BlockIterators {
|
||||
expression.addContextFunction("neighbours", -1, (c, t, lv)->
|
||||
{
|
||||
BlockPos center = BlockArgument.findIn((CarpetContext) c, lv,0).block.getPos();
|
||||
ServerWorld world = ((CarpetContext) c).s.getWorld();
|
||||
ServerLevel world = ((CarpetContext) c).s.getLevel();
|
||||
|
||||
List<Value> neighbours = new ArrayList<>();
|
||||
neighbours.add(new BlockValue(null, world, center.up()));
|
||||
neighbours.add(new BlockValue(null, world, center.down()));
|
||||
neighbours.add(new BlockValue(null, world, center.above()));
|
||||
neighbours.add(new BlockValue(null, world, center.below()));
|
||||
neighbours.add(new BlockValue(null, world, center.north()));
|
||||
neighbours.add(new BlockValue(null, world, center.south()));
|
||||
neighbours.add(new BlockValue(null, world, center.east()));
|
||||
@@ -245,30 +244,30 @@ public class BlockIterators {
|
||||
Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset);
|
||||
if (diffLocator.fromBlock)
|
||||
{
|
||||
sminx = MathHelper.floor(abs(diffLocator.vec.x - cx));
|
||||
sminy = MathHelper.floor(abs(diffLocator.vec.y - cx));
|
||||
sminz = MathHelper.floor(abs(diffLocator.vec.z - cx));
|
||||
sminx = Mth.floor(abs(diffLocator.vec.x - cx));
|
||||
sminy = Mth.floor(abs(diffLocator.vec.y - cx));
|
||||
sminz = Mth.floor(abs(diffLocator.vec.z - cx));
|
||||
}
|
||||
else
|
||||
{
|
||||
sminx = MathHelper.floor(abs(diffLocator.vec.x));
|
||||
sminy = MathHelper.floor(abs(diffLocator.vec.y));
|
||||
sminz = MathHelper.floor(abs(diffLocator.vec.z));
|
||||
sminx = Mth.floor(abs(diffLocator.vec.x));
|
||||
sminy = Mth.floor(abs(diffLocator.vec.y));
|
||||
sminz = Mth.floor(abs(diffLocator.vec.z));
|
||||
}
|
||||
if (lv.size() > diffLocator.offset)
|
||||
{
|
||||
Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset);
|
||||
if (posDiff.fromBlock)
|
||||
{
|
||||
smaxx = MathHelper.floor(abs(posDiff.vec.x - cx));
|
||||
smaxy = MathHelper.floor(abs(posDiff.vec.y - cx));
|
||||
smaxz = MathHelper.floor(abs(posDiff.vec.z - cx));
|
||||
smaxx = Mth.floor(abs(posDiff.vec.x - cx));
|
||||
smaxy = Mth.floor(abs(posDiff.vec.y - cx));
|
||||
smaxz = Mth.floor(abs(posDiff.vec.z - cx));
|
||||
}
|
||||
else
|
||||
{
|
||||
smaxx = MathHelper.floor(abs(posDiff.vec.x));
|
||||
smaxy = MathHelper.floor(abs(posDiff.vec.y));
|
||||
smaxz = MathHelper.floor(abs(posDiff.vec.z));
|
||||
smaxx = Mth.floor(abs(posDiff.vec.x));
|
||||
smaxy = Mth.floor(abs(posDiff.vec.y));
|
||||
smaxz = Mth.floor(abs(posDiff.vec.z));
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -15,21 +15,6 @@ import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.entity.SpawnReason;
|
||||
import net.minecraft.entity.mob.MobEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.predicate.entity.EntityPredicates;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Box;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
@@ -39,11 +24,25 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySelector;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.MobSpawnType;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Entities {
|
||||
private static ListValue getPlayersFromWorldMatching(Context c, Predicate<ServerPlayerEntity> condition) {
|
||||
private static ListValue getPlayersFromWorldMatching(Context c, Predicate<ServerPlayer> condition) {
|
||||
List<Value> ret = new ArrayList<>();
|
||||
for (ServerPlayerEntity player: ((CarpetContext) c).s.getWorld().getPlayers()) {
|
||||
for (ServerPlayer player: ((CarpetContext) c).s.getLevel().players()) {
|
||||
if (condition.test(player)) {
|
||||
ret.add(new EntityValue(player));
|
||||
}
|
||||
@@ -60,30 +59,30 @@ public class Entities {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (cc.host.user != null)
|
||||
{
|
||||
ServerPlayerEntity player = cc.s.getServer().getPlayerManager().getPlayer(cc.host.user);
|
||||
ServerPlayer player = cc.s.getServer().getPlayerList().getPlayerByName(cc.host.user);
|
||||
return EntityValue.of(player);
|
||||
}
|
||||
Entity callingEntity = cc.s.getEntity();
|
||||
if (callingEntity instanceof PlayerEntity) return EntityValue.of(callingEntity);
|
||||
Vec3d pos = ((CarpetContext)c).s.getPosition();
|
||||
PlayerEntity closestPlayer = ((CarpetContext)c).s.getWorld().getClosestPlayer(pos.x, pos.y, pos.z, -1.0, EntityPredicates.VALID_ENTITY);
|
||||
if (callingEntity instanceof Player) return EntityValue.of(callingEntity);
|
||||
Vec3 pos = ((CarpetContext)c).s.getPosition();
|
||||
Player closestPlayer = ((CarpetContext)c).s.getLevel().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE);
|
||||
return EntityValue.of(closestPlayer);
|
||||
}
|
||||
String playerName = lv.get(0).getString();
|
||||
return switch (playerName) {
|
||||
case "all" -> {
|
||||
List<Value> ret = new ArrayList<>();
|
||||
for (ServerPlayerEntity player: ((CarpetContext)c).s.getServer().getPlayerManager().getPlayerList())
|
||||
for (ServerPlayer player: ((CarpetContext)c).s.getServer().getPlayerList().getPlayers())
|
||||
ret.add(new EntityValue(player));
|
||||
yield ListValue.wrap(ret);
|
||||
}
|
||||
case "*" -> getPlayersFromWorldMatching(c, p -> true);
|
||||
case "survival" -> getPlayersFromWorldMatching(c, p -> p.interactionManager.isSurvivalLike());
|
||||
case "creative" -> getPlayersFromWorldMatching(c, PlayerEntity::isCreative);
|
||||
case "spectating" -> getPlayersFromWorldMatching(c, PlayerEntity::isSpectator);
|
||||
case "survival" -> getPlayersFromWorldMatching(c, p -> p.gameMode.isSurvival()); // todo assert correct
|
||||
case "creative" -> getPlayersFromWorldMatching(c, ServerPlayer::isCreative);
|
||||
case "spectating" -> getPlayersFromWorldMatching(c, ServerPlayer::isSpectator);
|
||||
case "!spectating" -> getPlayersFromWorldMatching(c, p -> !p.isSpectator());
|
||||
default -> {
|
||||
ServerPlayerEntity player = ((CarpetContext) c).s.getServer().getPlayerManager().getPlayer(playerName);
|
||||
ServerPlayer player = ((CarpetContext) c).s.getServer().getPlayerList().getPlayerByName(playerName);
|
||||
if (player != null) {
|
||||
yield new EntityValue(player);
|
||||
}
|
||||
@@ -98,12 +97,12 @@ public class Entities {
|
||||
if (lv.size() < 2)
|
||||
throw new InternalExpressionException("'spawn' function takes mob name, and position to spawn");
|
||||
String entityString = lv.get(0).getString();
|
||||
Identifier entityId;
|
||||
ResourceLocation entityId;
|
||||
try
|
||||
{
|
||||
entityId = Identifier.fromCommandInput(new StringReader(entityString));
|
||||
EntityType<? extends Entity> type = Registry.ENTITY_TYPE.getOrEmpty(entityId).orElse(null);
|
||||
if (type == null || !type.isSummonable())
|
||||
entityId = ResourceLocation.read(new StringReader(entityString));
|
||||
EntityType<? extends Entity> type = Registry.ENTITY_TYPE.getOptional(entityId).orElse(null);
|
||||
if (type == null || !type.canSummon())
|
||||
return Value.NULL;
|
||||
}
|
||||
catch (CommandSyntaxException exception)
|
||||
@@ -114,7 +113,7 @@ public class Entities {
|
||||
Vector3Argument position = Vector3Argument.findIn(lv, 1);
|
||||
if (position.fromBlock)
|
||||
position.vec = position.vec.subtract(0, 0.5, 0);
|
||||
NbtCompound tag = new NbtCompound();
|
||||
CompoundTag tag = new CompoundTag();
|
||||
boolean hasTag = false;
|
||||
if (lv.size() > position.offset)
|
||||
{
|
||||
@@ -126,18 +125,18 @@ public class Entities {
|
||||
|
||||
}
|
||||
tag.putString("id", entityId.toString());
|
||||
Vec3d vec3d = position.vec;
|
||||
Vec3 vec3d = position.vec;
|
||||
|
||||
ServerWorld serverWorld = cc.s.getWorld();
|
||||
Entity entity_1 = EntityType.loadEntityWithPassengers(tag, serverWorld, (entity_1x) -> {
|
||||
entity_1x.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYaw(), entity_1x.getPitch());
|
||||
return !serverWorld.tryLoadEntity(entity_1x) ? null : entity_1x;
|
||||
ServerLevel serverWorld = cc.s.getLevel();
|
||||
Entity entity_1 = EntityType.loadEntityRecursive(tag, serverWorld, (entity_1x) -> {
|
||||
entity_1x.moveTo(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYRot(), entity_1x.getXRot());
|
||||
return !serverWorld.addWithUUID(entity_1x) ? null : entity_1x;
|
||||
});
|
||||
if (entity_1 == null) {
|
||||
return Value.NULL;
|
||||
} else {
|
||||
if (!hasTag && entity_1 instanceof MobEntity) {
|
||||
((MobEntity)entity_1).initialize(serverWorld, serverWorld.getLocalDifficulty(entity_1.getBlockPos()), SpawnReason.COMMAND, null, null);
|
||||
if (!hasTag && entity_1 instanceof Mob) {
|
||||
((Mob)entity_1).finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(entity_1.blockPosition()), MobSpawnType.COMMAND, null, null);
|
||||
}
|
||||
return new EntityValue(entity_1);
|
||||
}
|
||||
@@ -147,16 +146,16 @@ public class Entities {
|
||||
{
|
||||
Value who = lv.get(0);
|
||||
if (who instanceof NumericValue)
|
||||
return EntityValue.of(((CarpetContext)c).s.getWorld().getEntityById((int)((NumericValue) who).getLong()));
|
||||
return EntityValue.of(((CarpetContext)c).s.getWorld().getEntity(UUID.fromString(who.getString())));
|
||||
return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity((int)((NumericValue) who).getLong()));
|
||||
return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity(UUID.fromString(who.getString())));
|
||||
});
|
||||
|
||||
expression.addContextFunction("entity_list", 1, (c, t, lv) ->
|
||||
{
|
||||
String who = lv.get(0).getString();
|
||||
ServerCommandSource source = ((CarpetContext)c).s;
|
||||
CommandSourceStack source = ((CarpetContext)c).s;
|
||||
EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer());
|
||||
List<? extends Entity> entityList = source.getWorld().getEntitiesByType(eDesc.directType, eDesc.filteringPredicate);
|
||||
List<? extends Entity> entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate);
|
||||
return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
@@ -167,24 +166,24 @@ public class Entities {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true);
|
||||
|
||||
Box centerBox;
|
||||
AABB centerBox;
|
||||
if (centerLocator.entity != null)
|
||||
{
|
||||
centerBox = centerLocator.entity.getBoundingBox();
|
||||
}
|
||||
else
|
||||
{
|
||||
Vec3d center = centerLocator.vec;
|
||||
Vec3 center = centerLocator.vec;
|
||||
if (centerLocator.fromBlock) center.add(0.5, 0.5, 0.5);
|
||||
centerBox = new Box(center, center);
|
||||
centerBox = new AABB(center, center);
|
||||
}
|
||||
Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset);
|
||||
if (rangeLocator.fromBlock)
|
||||
throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument");
|
||||
Vec3d range = rangeLocator.vec;
|
||||
Box area = centerBox.expand(range.x, range.y, range.z);
|
||||
Vec3 range = rangeLocator.vec;
|
||||
AABB area = centerBox.inflate(range.x, range.y, range.z);
|
||||
EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getServer());
|
||||
List<? extends Entity> entityList = cc.s.getWorld().getEntitiesByType(eDesc.directType, area,eDesc.filteringPredicate);
|
||||
List<? extends Entity> entityList = cc.s.getLevel().getEntities(eDesc.directType, area,eDesc.filteringPredicate);
|
||||
return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
|
||||
@@ -23,70 +23,69 @@ import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.command.argument.ItemStackArgument;
|
||||
import net.minecraft.entity.ItemEntity;
|
||||
import net.minecraft.entity.LivingEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemGroup;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.network.packet.s2c.play.ScreenHandlerSlotUpdateS2CPacket;
|
||||
import net.minecraft.recipe.AbstractCookingRecipe;
|
||||
import net.minecraft.recipe.CuttingRecipe;
|
||||
import net.minecraft.recipe.Recipe;
|
||||
import net.minecraft.recipe.RecipeType;
|
||||
import net.minecraft.recipe.ShapedRecipe;
|
||||
import net.minecraft.recipe.ShapelessRecipe;
|
||||
import net.minecraft.recipe.SpecialCraftingRecipe;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.tag.TagManager;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.arguments.item.ItemInput;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.CreativeModeTab;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.AbstractCookingRecipe;
|
||||
import net.minecraft.world.item.crafting.CustomRecipe;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipe;
|
||||
import net.minecraft.world.item.crafting.ShapelessRecipe;
|
||||
import net.minecraft.world.item.crafting.SingleItemRecipe;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Inventories {
|
||||
public static void apply(Expression expression)
|
||||
{
|
||||
expression.addUnaryFunction("stack_limit", v ->
|
||||
new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxCount()));
|
||||
new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxStackSize()));
|
||||
|
||||
expression.addUnaryFunction("item_category", v ->
|
||||
{
|
||||
ItemStackArgument item = NBTSerializableValue.parseItem(v.getString());
|
||||
ItemGroup ig = item.getItem().getGroup();
|
||||
return (ig==null)?Value.NULL:new StringValue(ig.getName());
|
||||
ItemInput item = NBTSerializableValue.parseItem(v.getString());
|
||||
CreativeModeTab ig = item.getItem().getItemCategory();
|
||||
return (ig==null)?Value.NULL:new StringValue(ig.getRecipeFolderName());
|
||||
});
|
||||
|
||||
expression.addContextFunction("item_list", -1, (c, t, lv) ->
|
||||
{
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(Registry.ITEM.getIds().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(Registry.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
TagManager tagManager = cc.s.getServer().getTagManager();
|
||||
TagContainer tagManager = cc.s.getServer().getTags();
|
||||
String tag = lv.get(0).getString();
|
||||
net.minecraft.tag.Tag<Item> itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag));
|
||||
net.minecraft.tags.Tag<Item> itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
|
||||
if (itemTag == null) return Value.NULL;
|
||||
return ListValue.wrap(itemTag.values().stream().map(b -> ValueConversions.of(Registry.ITEM.getId(b))).collect(Collectors.toList()));
|
||||
return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b))).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
expression.addContextFunction("item_tags", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
TagManager tagManager = cc.s.getServer().getTagManager();
|
||||
TagContainer tagManager = cc.s.getServer().getTags();
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem();
|
||||
if (lv.size() == 1)
|
||||
return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList()));
|
||||
return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList()));
|
||||
String tag = lv.get(1).getString();
|
||||
net.minecraft.tag.Tag<Item> itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag));
|
||||
net.minecraft.tags.Tag<Item> itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
|
||||
if (itemTag == null) return Value.NULL;
|
||||
return BooleanValue.of(itemTag.contains(item));
|
||||
});
|
||||
@@ -109,7 +108,7 @@ public class Inventories {
|
||||
List<Value> recipesOutput = new ArrayList<>();
|
||||
for (Recipe<?> recipe: recipes)
|
||||
{
|
||||
ItemStack result = recipe.getOutput();
|
||||
ItemStack result = recipe.getResultItem();
|
||||
List<Value> ingredientValue = new ArrayList<>();
|
||||
recipe.getIngredients().forEach(
|
||||
ingredient ->
|
||||
@@ -147,15 +146,15 @@ public class Inventories {
|
||||
{
|
||||
recipeSpec = ListValue.of(
|
||||
new StringValue("smelting"),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getCookTime()),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getCookingTime()),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getExperience())
|
||||
);
|
||||
}
|
||||
else if (recipe instanceof CuttingRecipe)
|
||||
else if (recipe instanceof SingleItemRecipe)
|
||||
{
|
||||
recipeSpec = ListValue.of(new StringValue("cutting"));
|
||||
}
|
||||
else if (recipe instanceof SpecialCraftingRecipe)
|
||||
else if (recipe instanceof CustomRecipe)
|
||||
{
|
||||
recipeSpec = ListValue.of(new StringValue("special"));
|
||||
}
|
||||
@@ -173,10 +172,10 @@ public class Inventories {
|
||||
{
|
||||
String itemStr = v.getString();
|
||||
Item item;
|
||||
Identifier id = InputValidator.identifierOf(itemStr);
|
||||
item = Registry.ITEM.getOrEmpty(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM));
|
||||
if (!item.hasRecipeRemainder()) return Value.NULL;
|
||||
return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getId(item.getRecipeRemainder())));
|
||||
ResourceLocation id = InputValidator.identifierOf(itemStr);
|
||||
item = Registry.ITEM.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM));
|
||||
if (!item.hasCraftingRemainingItem()) return Value.NULL;
|
||||
return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getKey(item.getCraftingRemainingItem())));
|
||||
});
|
||||
|
||||
expression.addContextFunction("inventory_size", -1, (c, t, lv) ->
|
||||
@@ -184,7 +183,7 @@ public class Inventories {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
return new NumericValue(inventoryLocator.inventory().size());
|
||||
return new NumericValue(inventoryLocator.inventory().getContainerSize());
|
||||
});
|
||||
|
||||
expression.addContextFunction("inventory_has_items", -1, (c, t, lv) ->
|
||||
@@ -204,14 +203,14 @@ public class Inventories {
|
||||
if (lv.size() == inventoryLocator.offset())
|
||||
{
|
||||
List<Value> fullInventory = new ArrayList<>();
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getStack(i)));
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i)));
|
||||
return ListValue.wrap(fullInventory);
|
||||
}
|
||||
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
return ValueConversions.of(inventoryLocator.inventory().getStack(slot));
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
return ValueConversions.of(inventoryLocator.inventory().getItem(slot));
|
||||
});
|
||||
|
||||
//inventory_set(<b,e>, <n>, <count>, <item>, <nbt>)
|
||||
@@ -224,26 +223,26 @@ public class Inventories {
|
||||
throw new InternalExpressionException("'inventory_set' requires at least slot number and new stack size, and optional new item");
|
||||
int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+0)).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
if (count == 0)
|
||||
{
|
||||
// clear slot
|
||||
ItemStack removedStack = inventoryLocator.inventory().removeStack(slot);
|
||||
ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot);
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
//Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares
|
||||
return ValueConversions.of(removedStack);
|
||||
}
|
||||
if (lv.size() < inventoryLocator.offset()+3)
|
||||
{
|
||||
ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getItem(slot);
|
||||
ItemStack newStack = previousStack.copy();
|
||||
newStack.setCount(count);
|
||||
inventoryLocator.inventory().setStack(slot, newStack);
|
||||
inventoryLocator.inventory().setItem(slot, newStack);
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
return ValueConversions.of(previousStack);
|
||||
}
|
||||
NbtCompound nbt = null; // skipping one argument
|
||||
CompoundTag nbt = null; // skipping one argument
|
||||
if (lv.size() > inventoryLocator.offset()+3)
|
||||
{
|
||||
Value nbtValue = lv.get(inventoryLocator.offset()+3);
|
||||
@@ -254,11 +253,11 @@ public class Inventories {
|
||||
else
|
||||
nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag();
|
||||
}
|
||||
ItemStackArgument newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getItem(slot);
|
||||
try
|
||||
{
|
||||
inventoryLocator.inventory().setStack(slot, newitem.createStack(count, false));
|
||||
inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false));
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
@@ -274,7 +273,7 @@ public class Inventories {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
ItemStackArgument itemArg = null;
|
||||
ItemInput itemArg = null;
|
||||
if (lv.size() > inventoryLocator.offset())
|
||||
{
|
||||
Value secondArg = lv.get(inventoryLocator.offset()+0);
|
||||
@@ -287,9 +286,9 @@ public class Inventories {
|
||||
startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
}
|
||||
startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory());
|
||||
for (int i = startIndex, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
for (int i = startIndex, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
{
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(i);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(i);
|
||||
if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) )
|
||||
return new NumericValue(i);
|
||||
}
|
||||
@@ -304,16 +303,16 @@ public class Inventories {
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
if (lv.size() <= inventoryLocator.offset())
|
||||
throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed");
|
||||
ItemStackArgument searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString());
|
||||
ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString());
|
||||
int amount = 1;
|
||||
if (lv.size() > inventoryLocator.offset()+1)
|
||||
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
// not enough
|
||||
if (((amount == 1) && (!inventoryLocator.inventory().containsAny(Sets.newHashSet(searchItem.getItem()))))
|
||||
|| (inventoryLocator.inventory().count(searchItem.getItem()) < amount)) return Value.FALSE;
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
if (((amount == 1) && (!inventoryLocator.inventory().hasAnyOf(Sets.newHashSet(searchItem.getItem()))))
|
||||
|| (inventoryLocator.inventory().countItem(searchItem.getItem()) < amount)) return Value.FALSE;
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
{
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(i);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(i);
|
||||
if (stack.isEmpty())
|
||||
continue;
|
||||
if (!stack.getItem().equals(searchItem.getItem()))
|
||||
@@ -322,13 +321,13 @@ public class Inventories {
|
||||
if (left > 0)
|
||||
{
|
||||
stack.setCount(left);
|
||||
inventoryLocator.inventory().setStack(i, stack);
|
||||
inventoryLocator.inventory().setItem(i, stack);
|
||||
syncPlayerInventory(inventoryLocator, i);
|
||||
return Value.TRUE;
|
||||
}
|
||||
else
|
||||
{
|
||||
inventoryLocator.inventory().removeStack(i);
|
||||
inventoryLocator.inventory().removeItemNoUpdate(i);
|
||||
syncPlayerInventory(inventoryLocator, i);
|
||||
amount -= stack.getCount();
|
||||
}
|
||||
@@ -348,51 +347,51 @@ public class Inventories {
|
||||
throw new InternalExpressionException("Slot number is required for inventory_drop");
|
||||
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
int amount = 0;
|
||||
if (lv.size() > inventoryLocator.offset()+1)
|
||||
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
if (amount < 0)
|
||||
throw new InternalExpressionException("Cannot throw negative number of items");
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(slot);
|
||||
if (stack == null || stack.isEmpty()) return Value.ZERO;
|
||||
if (amount == 0) amount = stack.getCount();
|
||||
ItemStack droppedStack = inventoryLocator.inventory().removeStack(slot, amount);
|
||||
ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount);
|
||||
if (droppedStack.isEmpty()) return Value.ZERO;
|
||||
Object owner = inventoryLocator.owner();
|
||||
ItemEntity item;
|
||||
if (owner instanceof PlayerEntity)
|
||||
if (owner instanceof Player)
|
||||
{
|
||||
item = ((PlayerEntity) owner).dropItem(droppedStack, false, true);
|
||||
item = ((Player) owner).drop(droppedStack, false, true);
|
||||
}
|
||||
else if (owner instanceof LivingEntity villager)
|
||||
{
|
||||
// stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner);
|
||||
double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getStandingEyeHeight();
|
||||
item = new ItemEntity(villager.world, villager.getX(), double_1, villager.getZ(), droppedStack);
|
||||
Vec3d vec3d_1 = villager.getRotationVec(1.0F).normalize().multiply(0.3);// new Vec3d(0, 0.3, 0);
|
||||
item.setVelocity(vec3d_1);
|
||||
item.setToDefaultPickupDelay();
|
||||
cc.s.getWorld().spawnEntity(item);
|
||||
double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getEyeHeight();
|
||||
item = new ItemEntity(villager.level, villager.getX(), double_1, villager.getZ(), droppedStack);
|
||||
Vec3 vec3d_1 = villager.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0);
|
||||
item.setDeltaMovement(vec3d_1);
|
||||
item.setDefaultPickUpDelay();
|
||||
cc.s.getLevel().addFreshEntity(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
Vec3d point = Vec3d.ofCenter(inventoryLocator.position()); //pos+0.5v
|
||||
item = new ItemEntity(cc.s.getWorld(), point.x, point.y, point.z, droppedStack);
|
||||
item.setToDefaultPickupDelay();
|
||||
cc.s.getWorld().spawnEntity(item);
|
||||
Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v
|
||||
item = new ItemEntity(cc.s.getLevel(), point.x, point.y, point.z, droppedStack);
|
||||
item.setDefaultPickUpDelay();
|
||||
cc.s.getLevel().addFreshEntity(item);
|
||||
}
|
||||
return new NumericValue(item.getStack().getCount());
|
||||
return new NumericValue(item.getItem().getCount());
|
||||
});
|
||||
|
||||
expression.addContextFunction("create_screen",-1, (c, t, lv) ->
|
||||
{
|
||||
if(lv.size() < 3) throw new InternalExpressionException("'create_screen' requires at least three arguments");
|
||||
Value playerValue = lv.get(0);
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue);
|
||||
if(player == null) throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument.");
|
||||
String type = lv.get(1).getString();
|
||||
Text name = FormattedTextValue.getTextByValue(lv.get(2));
|
||||
Component name = FormattedTextValue.getTextByValue(lv.get(2));
|
||||
FunctionValue function = null;
|
||||
if(lv.size() > 3)
|
||||
function = FunctionArgument.findIn(c, expression.module, lv, 3, true, false).function;
|
||||
@@ -427,12 +426,12 @@ public class Inventories {
|
||||
|
||||
private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1)
|
||||
{
|
||||
if (inventory.owner() instanceof ServerPlayerEntity player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory))
|
||||
if (inventory.owner() instanceof ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory))
|
||||
{
|
||||
player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket(
|
||||
player.connection.send(new ClientboundContainerSetSlotPacket(
|
||||
-2, 0, // resolve mystery argument
|
||||
int_1,
|
||||
inventory.inventory().getStack(int_1)
|
||||
inventory.inventory().getItem(int_1)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,12 @@ import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.utils.SpawnReporter;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import net.minecraft.entity.SpawnGroup;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.world.SpawnHelper;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraft.world.level.NaturalSpawner;
|
||||
|
||||
public class Monitoring {
|
||||
|
||||
@@ -42,19 +41,19 @@ public class Monitoring {
|
||||
expression.addContextFunction("get_mob_counts", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
SpawnHelper.Info info = world.getChunkManager().getSpawnInfo();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState();
|
||||
if (info == null) return Value.NULL;
|
||||
Object2IntMap<SpawnGroup> mobcounts = info.getGroupToCount();
|
||||
Object2IntMap<MobCategory> mobcounts = info.getMobCategoryCounts();
|
||||
int chunks = ((SpawnHelperInnerInterface)info).cmGetChunkCount();
|
||||
if (lv.size() == 0)
|
||||
{
|
||||
Map<Value, Value> retDict = new HashMap<>();
|
||||
for (SpawnGroup category: mobcounts.keySet())
|
||||
for (MobCategory category: mobcounts.keySet())
|
||||
{
|
||||
int currentCap = (int)(category.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER);
|
||||
int currentCap = (int)(category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER);
|
||||
retDict.put(
|
||||
new StringValue(category.asString().toLowerCase(Locale.ROOT)),
|
||||
new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)),
|
||||
ListValue.of(
|
||||
new NumericValue(mobcounts.getInt(category)),
|
||||
new NumericValue(currentCap))
|
||||
@@ -63,11 +62,11 @@ public class Monitoring {
|
||||
return MapValue.wrap(retDict);
|
||||
}
|
||||
String catString = lv.get(0).getString();
|
||||
SpawnGroup cat = SpawnGroup.byName(catString.toLowerCase(Locale.ROOT));
|
||||
MobCategory cat = MobCategory.byName(catString.toLowerCase(Locale.ROOT));
|
||||
if (cat == null) throw new InternalExpressionException("Unreconized mob category: "+catString);
|
||||
return ListValue.of(
|
||||
new NumericValue(mobcounts.getInt(cat)),
|
||||
new NumericValue((int)(cat.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER))
|
||||
new NumericValue((int)(cat.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,28 +19,26 @@ import carpet.script.value.StringValue;
|
||||
import carpet.script.value.FormattedTextValue;
|
||||
import carpet.script.value.Value;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.boss.BossBar;
|
||||
import net.minecraft.entity.boss.BossBarManager;
|
||||
import net.minecraft.entity.boss.CommandBossBar;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.scoreboard.Scoreboard;
|
||||
import net.minecraft.scoreboard.ServerScoreboard;
|
||||
import net.minecraft.scoreboard.ScoreboardCriterion;
|
||||
import net.minecraft.scoreboard.ScoreboardObjective;
|
||||
import net.minecraft.scoreboard.ScoreboardPlayerScore;
|
||||
import net.minecraft.scoreboard.Team;
|
||||
import net.minecraft.scoreboard.AbstractTeam;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Formatting;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.InvalidIdentifierException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.ServerScoreboard;
|
||||
import net.minecraft.server.bossevents.CustomBossEvent;
|
||||
import net.minecraft.server.bossevents.CustomBossEvents;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.BossEvent;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.PlayerTeam;
|
||||
import net.minecraft.world.scores.Score;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
import net.minecraft.world.scores.Team;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
||||
|
||||
public class Scoreboards {
|
||||
private static String getScoreboardKeyFromValue(Value keyValue)
|
||||
@@ -48,13 +46,13 @@ public class Scoreboards {
|
||||
if (keyValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) keyValue).getEntity();
|
||||
if (e instanceof PlayerEntity)
|
||||
if (e instanceof Player)
|
||||
{
|
||||
return e.getName().getString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return e.getUuidAsString();
|
||||
return e.getStringUUID();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -74,25 +72,25 @@ public class Scoreboards {
|
||||
if (lv.size()==0)
|
||||
return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList()));
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective == null) return Value.NULL;
|
||||
if (lv.size()==1)
|
||||
return ListValue.wrap(scoreboard.getAllPlayerScores(objective).stream().map(s -> new StringValue(s.getPlayerName())).collect(Collectors.toList()));
|
||||
return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner())).collect(Collectors.toList()));
|
||||
String key = getScoreboardKeyFromValue(lv.get(1));
|
||||
if(lv.size()==2)
|
||||
{
|
||||
if(!scoreboard.playerHasObjective(key, objective)) return Value.NULL;
|
||||
return NumericValue.of(scoreboard.getPlayerScore(key,objective).getScore());
|
||||
if(!scoreboard.hasPlayerScore(key, objective)) return Value.NULL;
|
||||
return NumericValue.of(scoreboard.getOrCreatePlayerScore(key,objective).getScore());
|
||||
}
|
||||
|
||||
Value value = lv.get(2);
|
||||
if(value.isNull()) {
|
||||
ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective);
|
||||
Score score = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
scoreboard.resetPlayerScore(key,objective);
|
||||
return NumericValue.of(score.getScore());
|
||||
}
|
||||
if (value instanceof NumericValue) {
|
||||
ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective);
|
||||
Score score = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
score.setScore(NumericValue.asNumber(value).getInt());
|
||||
return NumericValue.of(score.getScore());
|
||||
}
|
||||
@@ -105,7 +103,7 @@ public class Scoreboards {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective == null) return Value.FALSE;
|
||||
if (lv.size() == 1)
|
||||
{
|
||||
@@ -113,8 +111,8 @@ public class Scoreboards {
|
||||
return Value.TRUE;
|
||||
}
|
||||
String key = getScoreboardKeyFromValue(lv.get(1));
|
||||
if (!scoreboard.playerHasObjective(key, objective)) return Value.NULL;
|
||||
ScoreboardPlayerScore scoreboardPlayerScore = scoreboard.getPlayerScore(key, objective);
|
||||
if (!scoreboard.hasPlayerScore(key, objective)) return Value.NULL;
|
||||
Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
Value previous = new NumericValue(scoreboardPlayerScore.getScore());
|
||||
scoreboard.resetPlayerScore(key, objective);
|
||||
return previous;
|
||||
@@ -129,34 +127,34 @@ public class Scoreboards {
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
if (lv.size() == 0 || lv.size()>2) throw new InternalExpressionException("'scoreboard_add' should have one or two parameters");
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardCriterion criterion;
|
||||
ObjectiveCriteria criterion;
|
||||
if (lv.size() == 1 )
|
||||
{
|
||||
criterion = ScoreboardCriterion.DUMMY;
|
||||
criterion = ObjectiveCriteria.DUMMY;
|
||||
}
|
||||
else
|
||||
{
|
||||
String critetionName = lv.get(1).getString();
|
||||
criterion = ScoreboardCriterion.getOrCreateStatCriterion(critetionName).orElse(null);
|
||||
criterion = ObjectiveCriteria.byName(critetionName).orElse(null);
|
||||
if (criterion==null)
|
||||
{
|
||||
throw new ThrowStatement(critetionName, Throwables.UNKNOWN_CRITERION);
|
||||
}
|
||||
}
|
||||
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective != null) {
|
||||
c.host.issueDeprecation("reading or modifying an objective's criterion with scoreboard_add");
|
||||
if(lv.size() == 1) return StringValue.of(objective.getCriterion().getName());
|
||||
if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.NULL;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective);
|
||||
if(lv.size() == 1) return StringValue.of(objective.getCriteria().getName());
|
||||
if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.NULL;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective);
|
||||
((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion);
|
||||
(((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective);
|
||||
scoreboard.updateObjective(objective);
|
||||
scoreboard.onObjectiveAdded(objective);
|
||||
return Value.FALSE;
|
||||
}
|
||||
|
||||
scoreboard.addObjective(objectiveName, criterion, new LiteralText(objectiveName), criterion.getDefaultRenderType());
|
||||
scoreboard.addObjective(objectiveName, criterion, new TextComponent(objectiveName), criterion.getDefaultRenderType());
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -165,7 +163,7 @@ public class Scoreboards {
|
||||
if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters");
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(lv.get(0).getString());
|
||||
Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString());
|
||||
if(objective == null) return Value.NULL;
|
||||
|
||||
boolean modify = lv.size() > 2;
|
||||
@@ -177,37 +175,37 @@ public class Scoreboards {
|
||||
switch (property) {
|
||||
case "criterion":
|
||||
if(modify) {
|
||||
ScoreboardCriterion criterion = ScoreboardCriterion.getOrCreateStatCriterion(setValue.getString()).orElse(null);
|
||||
ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null);
|
||||
if (criterion==null) throw new InternalExpressionException("Unknown scoreboard criterion: "+ setValue.getString());
|
||||
if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.FALSE;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective);
|
||||
if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.FALSE;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective);
|
||||
((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion);
|
||||
(((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective);
|
||||
scoreboard.updateObjective(objective);
|
||||
scoreboard.onObjectiveAdded(objective);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return StringValue.of(objective.getCriterion().getName());
|
||||
return StringValue.of(objective.getCriteria().getName());
|
||||
case "display_name":
|
||||
if(modify) {
|
||||
Text text = FormattedTextValue.getTextByValue(setValue);
|
||||
Component text = FormattedTextValue.getTextByValue(setValue);
|
||||
objective.setDisplayName(text);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return new FormattedTextValue(objective.getDisplayName());
|
||||
case "display_slot":
|
||||
if(modify) {
|
||||
int slotId = Scoreboard.getDisplaySlotId(setValue.getString());
|
||||
int slotId = Scoreboard.getDisplaySlotByName(setValue.getString());
|
||||
if(slotId == -1) throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString());
|
||||
if(objective.equals(scoreboard.getObjectiveForSlot(slotId))) {
|
||||
if(objective.equals(scoreboard.getDisplayObjective(slotId))) {
|
||||
return Value.FALSE;
|
||||
}
|
||||
scoreboard.setObjectiveSlot(slotId,objective);
|
||||
scoreboard.setDisplayObjective(slotId,objective);
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
List<Value> slots = new ArrayList<>();
|
||||
for(int i = 0; i < 19; i++) {
|
||||
if (scoreboard.getObjectiveForSlot(i) == objective) {
|
||||
if (scoreboard.getDisplayObjective(i) == objective) {
|
||||
String slotName = Scoreboard.getDisplaySlotName(i);
|
||||
slots.add(StringValue.of(slotName));
|
||||
}
|
||||
@@ -215,12 +213,12 @@ public class Scoreboards {
|
||||
return ListValue.wrap(slots);
|
||||
case "render_type":
|
||||
if(modify) {
|
||||
ScoreboardCriterion.RenderType renderType = ScoreboardCriterion.RenderType.getType(setValue.getString().toLowerCase());
|
||||
ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase());
|
||||
if(objective.getRenderType().equals(renderType)) return Value.FALSE;
|
||||
objective.setRenderType(renderType);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return StringValue.of(objective.getRenderType().getName());
|
||||
return StringValue.of(objective.getRenderType().getId());
|
||||
default:
|
||||
throw new InternalExpressionException("scoreboard property '" + property + "' is not a valid property");
|
||||
}
|
||||
@@ -231,18 +229,18 @@ public class Scoreboards {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
String location = lv.get(0).getString();
|
||||
int slot = Scoreboard.getDisplaySlotId(location);
|
||||
int slot = Scoreboard.getDisplaySlotByName(location);
|
||||
if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location);
|
||||
Value target = lv.get(1);
|
||||
if (target instanceof NullValue)
|
||||
{
|
||||
scoreboard.setObjectiveSlot(slot, null);
|
||||
scoreboard.setDisplayObjective(slot, null);
|
||||
return new NumericValue(slot);
|
||||
}
|
||||
String objectiveString = target.getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveString);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveString);
|
||||
if (objective == null) return Value.NULL;
|
||||
scoreboard.setObjectiveSlot(slot, objective);
|
||||
scoreboard.setDisplayObjective(slot, objective);
|
||||
return new NumericValue(slot);
|
||||
});
|
||||
|
||||
@@ -254,9 +252,9 @@ public class Scoreboards {
|
||||
if(lv.size() == 0)
|
||||
return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
if (lv.size() != 1) return Value.NULL;
|
||||
Team team = scoreboard.getTeam(lv.get(0).getString());
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString());
|
||||
if(team == null) return Value.NULL;
|
||||
return ListValue.wrap(team.getPlayerList().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(team.getPlayers().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
|
||||
@@ -270,18 +268,18 @@ public class Scoreboards {
|
||||
|
||||
if(lv.size() == 1)
|
||||
{
|
||||
if (scoreboard.getTeam(teamName) != null) return Value.NULL;
|
||||
scoreboard.addTeam(teamName);
|
||||
if (scoreboard.getPlayerTeam(teamName) != null) return Value.NULL;
|
||||
scoreboard.addPlayerTeam(teamName);
|
||||
return new StringValue(teamName);
|
||||
}
|
||||
if(lv.size() != 2) return Value.NULL;
|
||||
Value playerVal = lv.get(1);
|
||||
String player = EntityValue.getPlayerNameByValue(playerVal);
|
||||
if(player == null) return Value.NULL;
|
||||
Team team = scoreboard.getTeam(teamName);
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(teamName);
|
||||
if(team == null) return Value.NULL;
|
||||
if(team.isEqual(scoreboard.getPlayerTeam(player))) return Value.FALSE;
|
||||
scoreboard.addPlayerToTeam(player,scoreboard.getTeam(teamName));
|
||||
if(team.isAlliedTo(scoreboard.getPlayersTeam(player))) return Value.FALSE;
|
||||
scoreboard.addPlayerToTeam(player,scoreboard.getPlayerTeam(teamName));
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -291,8 +289,8 @@ public class Scoreboards {
|
||||
ServerScoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
Value teamVal = lv.get(0);
|
||||
String team = teamVal.getString();
|
||||
if(scoreboard.getTeam(team) == null) return Value.NULL;
|
||||
scoreboard.removeTeam(scoreboard.getTeam(team));
|
||||
if(scoreboard.getPlayerTeam(team) == null) return Value.NULL;
|
||||
scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(team));
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -304,7 +302,7 @@ public class Scoreboards {
|
||||
Value playerVal = lv.get(0);
|
||||
String player = EntityValue.getPlayerNameByValue(playerVal);
|
||||
if(player == null) return Value.NULL;
|
||||
return BooleanValue.of(scoreboard.clearPlayerTeam(player));
|
||||
return BooleanValue.of(scoreboard.removePlayerFromTeam(player));
|
||||
});
|
||||
|
||||
expression.addContextFunction("team_property", -1, (c, t, lv) ->
|
||||
@@ -325,7 +323,7 @@ public class Scoreboards {
|
||||
settingVal = lv.get(2);
|
||||
}
|
||||
|
||||
Team team = scoreboard.getTeam(teamVal.getString());
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString());
|
||||
if(team == null) return Value.NULL;
|
||||
|
||||
if(!(propertyVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the second argument");
|
||||
@@ -334,64 +332,64 @@ public class Scoreboards {
|
||||
case "collisionRule":
|
||||
if(!modifying) return new StringValue(team.getCollisionRule().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.CollisionRule collisionRule = AbstractTeam.CollisionRule.getRule(settingVal.getString());
|
||||
Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString());
|
||||
if(collisionRule == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setCollisionRule(collisionRule);
|
||||
break;
|
||||
case "color":
|
||||
if(!modifying) return new StringValue(((Team_scarpetMixin) team).getColor().getName());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
Formatting color = Formatting.byName(settingVal.getString().toUpperCase());
|
||||
ChatFormatting color = ChatFormatting.getByName(settingVal.getString().toUpperCase());
|
||||
if(color == null || !color.isColor()) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setColor(color);
|
||||
break;
|
||||
case "deathMessageVisibility":
|
||||
if(!modifying) return new StringValue(team.getDeathMessageVisibilityRule().name);
|
||||
if(!modifying) return new StringValue(team.getDeathMessageVisibility().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.VisibilityRule deathMessageVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString());
|
||||
Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString());
|
||||
if(deathMessageVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setDeathMessageVisibilityRule(deathMessageVisibility);
|
||||
team.setDeathMessageVisibility(deathMessageVisibility);
|
||||
break;
|
||||
case "displayName":
|
||||
if(!modifying) return new FormattedTextValue(team.getDisplayName());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text displayName;
|
||||
Component displayName;
|
||||
displayName = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setDisplayName(displayName);
|
||||
break;
|
||||
case "friendlyFire":
|
||||
if(!modifying) return BooleanValue.of(team.isFriendlyFireAllowed());
|
||||
if(!modifying) return BooleanValue.of(team.isAllowFriendlyFire());
|
||||
if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString());
|
||||
boolean friendlyFire = settingVal.getBoolean();
|
||||
team.setFriendlyFireAllowed(friendlyFire);
|
||||
team.setAllowFriendlyFire(friendlyFire);
|
||||
break;
|
||||
case "nametagVisibility":
|
||||
if(!modifying) return new StringValue(team.getNameTagVisibilityRule().name);
|
||||
if(!modifying) return new StringValue(team.getNameTagVisibility().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.VisibilityRule nametagVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString());
|
||||
Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString());
|
||||
if(nametagVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setNameTagVisibilityRule(nametagVisibility);
|
||||
team.setNameTagVisibility(nametagVisibility);
|
||||
|
||||
break;
|
||||
case "prefix":
|
||||
if(!modifying) return new FormattedTextValue(team.getPrefix());
|
||||
if(!modifying) return new FormattedTextValue(team.getPlayerPrefix());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property ' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text prefix;
|
||||
Component prefix;
|
||||
prefix = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setPrefix(prefix);
|
||||
team.setPlayerPrefix(prefix);
|
||||
break;
|
||||
case "seeFriendlyInvisibles":
|
||||
if(!modifying) return BooleanValue.of(team.shouldShowFriendlyInvisibles());
|
||||
if(!modifying) return BooleanValue.of(team.canSeeFriendlyInvisibles());
|
||||
if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString());
|
||||
boolean seeFriendlyInvisibles = settingVal.getBoolean();
|
||||
team.setShowFriendlyInvisibles(seeFriendlyInvisibles);
|
||||
team.setSeeFriendlyInvisibles(seeFriendlyInvisibles);
|
||||
break;
|
||||
case "suffix":
|
||||
if(!modifying) return new FormattedTextValue(team.getSuffix());
|
||||
if(!modifying) return new FormattedTextValue(team.getPlayerSuffix());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text suffix;
|
||||
Component suffix;
|
||||
suffix = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setSuffix(suffix);
|
||||
team.setPlayerSuffix(suffix);
|
||||
break;
|
||||
default:
|
||||
throw new InternalExpressionException("team property '" + propertyVal.getString() + "' is not a valid property");
|
||||
@@ -401,24 +399,24 @@ public class Scoreboards {
|
||||
|
||||
expression.addContextFunction("bossbar", -1, (c, t, lv) ->
|
||||
{
|
||||
BossBarManager bossBarManager = ((CarpetContext)c).s.getServer().getBossBarManager();
|
||||
CustomBossEvents bossBarManager = ((CarpetContext)c).s.getServer().getCustomBossEvents();
|
||||
if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments");
|
||||
|
||||
if(lv.size() == 0) return ListValue.wrap(bossBarManager.getAll().stream().map(CommandBossBar::getId).map(Identifier::toString).map(StringValue::of).collect(Collectors.toList()));
|
||||
if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of).collect(Collectors.toList()));
|
||||
|
||||
String id = lv.get(0).getString();
|
||||
Identifier identifier;
|
||||
ResourceLocation identifier;
|
||||
identifier = InputValidator.identifierOf(id);
|
||||
|
||||
if(lv.size() == 1)
|
||||
{
|
||||
if(bossBarManager.get(identifier) != null) return Value.FALSE;
|
||||
return StringValue.of(bossBarManager.add(identifier,new LiteralText(id)).getId().toString());
|
||||
return StringValue.of(bossBarManager.create(identifier,new TextComponent(id)).getTextId().toString());
|
||||
}
|
||||
|
||||
String property = lv.get(1).getString();
|
||||
|
||||
CommandBossBar bossBar = bossBarManager.get(identifier);
|
||||
CustomBossEvent bossBar = bossBarManager.get(identifier);
|
||||
if(bossBar == null) return Value.NULL;
|
||||
|
||||
Value propertyValue = (lv.size() == 3)?lv.get(2):null;
|
||||
@@ -426,20 +424,20 @@ public class Scoreboards {
|
||||
switch (property) {
|
||||
case "color":
|
||||
if(propertyValue == null) {
|
||||
BossBar.Color color = (bossBar).getColor();
|
||||
BossEvent.BossBarColor color = (bossBar).getColor();
|
||||
if(color == null) return Value.NULL;
|
||||
return StringValue.of(color.getName());
|
||||
}
|
||||
|
||||
BossBar.Color color = BossBar.Color.byName(propertyValue.getString());
|
||||
BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString());
|
||||
if(color == null) return Value.NULL;
|
||||
bossBar.setColor(BossBar.Color.byName(propertyValue.getString()));
|
||||
bossBar.setColor(BossEvent.BossBarColor.byName(propertyValue.getString()));
|
||||
return Value.TRUE;
|
||||
case "max":
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getMaxValue());
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getMax());
|
||||
|
||||
if(!(propertyValue instanceof NumericValue)) throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property);
|
||||
bossBar.setMaxValue(((NumericValue) propertyValue).getInt());
|
||||
bossBar.setMax(((NumericValue) propertyValue).getInt());
|
||||
return Value.TRUE;
|
||||
case "name":
|
||||
if(propertyValue == null) return new FormattedTextValue(bossBar.getName());
|
||||
@@ -451,13 +449,13 @@ public class Scoreboards {
|
||||
|
||||
if(propertyValue instanceof ListValue) {
|
||||
((ListValue) propertyValue).getItems().forEach((v)->{
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue);
|
||||
if(player != null) bossBar.addPlayer(player);
|
||||
});
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
if(player != null) {
|
||||
bossBar.addPlayer(player);
|
||||
return Value.TRUE;
|
||||
@@ -467,27 +465,27 @@ public class Scoreboards {
|
||||
if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
if(propertyValue instanceof ListValue)
|
||||
{
|
||||
bossBar.clearPlayers();
|
||||
bossBar.removeAllPlayers();
|
||||
((ListValue) propertyValue).getItems().forEach((v) -> {
|
||||
ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v);
|
||||
ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v);
|
||||
if (p != null) bossBar.addPlayer(p);
|
||||
});
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
|
||||
ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
bossBar.clearPlayers();
|
||||
ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
bossBar.removeAllPlayers();
|
||||
if (p != null) {
|
||||
bossBar.addPlayer(p);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return Value.FALSE;
|
||||
case "style":
|
||||
if(propertyValue == null) return StringValue.of(bossBar.getStyle().getName());
|
||||
BossBar.Style style = BossBar.Style.byName(propertyValue.getString());
|
||||
if(propertyValue == null) return StringValue.of(bossBar.getOverlay().getName());
|
||||
BossEvent.BossBarOverlay style = BossEvent.BossBarOverlay.byName(propertyValue.getString());
|
||||
if(style == null) throw new InternalExpressionException("'" + propertyValue.getString() + "' is not a valid value for property " + property);
|
||||
bossBar.setStyle(style);
|
||||
bossBar.setOverlay(style);
|
||||
return Value.TRUE;
|
||||
case "value":
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getValue());
|
||||
|
||||
@@ -16,7 +16,7 @@ public class Threading
|
||||
{
|
||||
//"overidden" native call to cancel if on main thread
|
||||
expression.addContextFunction("task_join", 1, (c, t, lv) -> {
|
||||
if (((CarpetContext)c).s.getServer().isOnThread())
|
||||
if (((CarpetContext)c).s.getServer().isSameThread())
|
||||
throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks");
|
||||
Value v = lv.get(0);
|
||||
if (!(v instanceof ThreadValue))
|
||||
@@ -28,12 +28,12 @@ public class Threading
|
||||
expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
if (server.isOnThread()) return lv.get(0); // pass through for on thread tasks
|
||||
if (server.isSameThread()) return lv.get(0); // pass through for on thread tasks
|
||||
Value[] result = new Value[]{Value.NULL};
|
||||
RuntimeException[] internal = new RuntimeException[]{null};
|
||||
try
|
||||
{
|
||||
((CarpetContext) c).s.getServer().submitAndJoin(() ->
|
||||
((CarpetContext) c).s.getServer().executeBlocking(() ->
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user