Migrate the Carpet codebase to Mojang Mappings

This commit is contained in:
altrisi committed 2022-01-24 20:33:16 +01:00
1 parent a1a2488bc3
commit 06af9ce8b1
346 files changed
+8353 -8492

No files matched your search

@@ -15,10 +15,9 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.command.CommandException;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.WorldSavePath;
import net.minecraft.commands.CommandRuntimeException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.world.level.storage.LevelResource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -58,7 +57,7 @@ public class AppStoreManager
public static class ScarpetAppStoreValidator extends Validator<String>
{
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string)
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string)
{
APP_STORE_ROOT.sealed = false;
APP_STORE_ROOT.children = new HashMap<>();
@@ -251,13 +250,13 @@ public class AppStoreManager
* @return {@code 1} if we succesfully saved the script, {@code 0} otherwise
*/
public static int downloadScript(ServerCommandSource source, String path)
public static int downloadScript(CommandSourceStack source, String path)
{
AppInfo nodeInfo = getFileNode(path);
return downloadScript(source, path, nodeInfo, false);
}
private static int downloadScript(ServerCommandSource source, String path, AppInfo nodeInfo, boolean useTrash)
private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash)
{
String code;
try
@@ -266,7 +265,7 @@ public class AppStoreManager
}
catch (IOException e)
{
throw new CommandException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage()));
throw new CommandRuntimeException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage()));
}
if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) return 0;
boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source());
@@ -297,21 +296,21 @@ public class AppStoreManager
}
catch (IOException e)
{
throw new CommandException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage()));
throw new CommandRuntimeException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage()));
}
}
public static boolean saveScriptToFile(ServerCommandSource source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash)
public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash)
{
Path scriptLocation;
if (globalSavePath && !source.getServer().isDedicated()) // never happens, this is always called with globalSavePath being false
if (globalSavePath && !source.getServer().isDedicatedServer()) // never happens, this is always called with globalSavePath being false
{ //cos config folder only is in clients
scriptLocation = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts/appstore").toAbsolutePath().resolve(path);
}
else
{
scriptLocation = source.getServer().getSavePath(WorldSavePath.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName);
scriptLocation = source.getServer().getWorldPath(LevelResource.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName);
}
try
{
@@ -463,7 +462,7 @@ public class AppStoreManager
{
downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true);
}
catch (CommandException e)
catch (CommandRuntimeException e)
{
throw new InternalExpressionException("Error when installing app dependencies: " + e.toString());
}
@@ -7,39 +7,37 @@ import carpet.script.value.NumericValue;
import carpet.script.value.StringValue;
import carpet.script.value.Value;
import carpet.script.value.ValueConversions;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.ConfiguredStructureFeature;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import net.minecraft.core.Registry;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
public class BiomeInfo
{
public final static Map<String, BiFunction<ServerWorld, Biome, Value>> biomeFeatures = new HashMap<String, BiFunction<ServerWorld, Biome, Value>>(){{
public final static Map<String, BiFunction<ServerLevel, Biome, Value>> biomeFeatures = new HashMap<String, BiFunction<ServerLevel, Biome, Value>>(){{
//put("top_material", (w, b) -> new BlockValue( b.getGenerationSettings(). getSurfaceConfig().getTopMaterial(), null, null));
//put("under_material", (w, b) -> new BlockValue( b.getGenerationSettings().getSurfaceConfig().getUnderMaterial(), null, null));
put("category", (w, b) -> StringValue.of(b.getCategory().getName()));
put("temperature", (w, b) -> NumericValue.of(b.getTemperature()));
put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFogColor()));
put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFoliageColor().orElse(4764952))); // client Biome.getDefaultFoliageColor
put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getSkyColor()));
put("water_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterColor()));
put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterFogColor()));
put("category", (w, b) -> StringValue.of(b.getBiomeCategory().getName()));
put("temperature", (w, b) -> NumericValue.of(b.getBaseTemperature()));
put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFogColor()));
put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFoliageColorOverride().orElse(4764952))); // client Biome.getDefaultFoliageColor
put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getSkyColor()));
put("water_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterColor()));
put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterFogColor()));
put("humidity", (w, b) -> NumericValue.of(b.getDownfall()));
put("precipitation", (w, b) -> StringValue.of(b.getPrecipitation().getName()));
//put("depth", (w, b) -> NumericValue.of(b.getDepth()));
//put("scale", (w, b) -> NumericValue.of(b.getScale()));
put("features", (w, b) -> {
Registry<ConfiguredFeature<?,?>> registry = w.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY);
Registry<ConfiguredFeature<?,?>> registry = w.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY);
return ListValue.wrap(
b.getGenerationSettings().getFeatures().stream().map(step ->
b.getGenerationSettings().features().stream().map(step ->
ListValue.wrap(step.stream().map(cfp ->
ValueConversions.of(registry.getId(((PlacedFeatureInterface)cfp.get()).getRawFeature()))
ValueConversions.of(registry.getKey(((PlacedFeatureInterface)cfp.get()).getRawFeature()))
))
)
);
@@ -1,15 +1,14 @@
package carpet.script.utils;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import java.util.Arrays;
import java.util.List;
import net.minecraft.world.Container;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
public class EquipmentInventory implements Inventory
public class EquipmentInventory implements Container
{
private static final List<EquipmentSlot> slotToSlot = Arrays.asList(
EquipmentSlot.MAINHAND,
@@ -24,7 +23,7 @@ public class EquipmentInventory implements Inventory
}
@Override
public int size()
public int getContainerSize()
{
return 6;
}
@@ -33,12 +32,12 @@ public class EquipmentInventory implements Inventory
public boolean isEmpty()
{
for (EquipmentSlot slot: slotToSlot)
if (!mob.getEquippedStack(slot).isEmpty()) return false;
if (!mob.getItemBySlot(slot).isEmpty()) return false;
return true;
}
@Override
public ItemStack getStack(int slot)
public ItemStack getItem(int slot)
{
EquipmentSlot slotSlot;
try
@@ -50,11 +49,11 @@ public class EquipmentInventory implements Inventory
//going out of the index should be really exceptional
return ItemStack.EMPTY;
}
return mob.getEquippedStack(slotSlot);
return mob.getItemBySlot(slotSlot);
}
@Override
public ItemStack removeStack(int slot, int amount)
public ItemStack removeItem(int slot, int amount)
{
EquipmentSlot slotSlot;
try
@@ -66,11 +65,11 @@ public class EquipmentInventory implements Inventory
//going out of the index should be really exceptional
return ItemStack.EMPTY;
}
return mob.getEquippedStack(slotSlot).split(amount);
return mob.getItemBySlot(slotSlot).split(amount);
}
@Override
public ItemStack removeStack(int slot)
public ItemStack removeItemNoUpdate(int slot)
{
EquipmentSlot slotSlot;
try
@@ -82,13 +81,13 @@ public class EquipmentInventory implements Inventory
//going out of the index should be really exceptional
return ItemStack.EMPTY;
}
ItemStack previous = mob.getEquippedStack(slotSlot);
mob.equipStack(slotSlot, ItemStack.EMPTY);
ItemStack previous = mob.getItemBySlot(slotSlot);
mob.setItemSlot(slotSlot, ItemStack.EMPTY);
return previous;
}
@Override
public void setStack(int slot, ItemStack stack)
public void setItem(int slot, ItemStack stack)
{
EquipmentSlot slotSlot;
try
@@ -100,25 +99,25 @@ public class EquipmentInventory implements Inventory
//going out of the index should be really exceptional
return;
}
mob.equipStack(slotSlot, stack);
mob.setItemSlot(slotSlot, stack);
}
@Override
public void markDirty()
public void setChanged()
{
}
@Override
public boolean canPlayerUse(PlayerEntity player)
public boolean stillValid(Player player)
{
return false;
}
@Override
public void clear()
public void clearContent()
{
for (EquipmentSlot slot: slotToSlot)
mob.equipStack(slot, ItemStack.EMPTY);
mob.setItemSlot(slot, ItemStack.EMPTY);
}
}
@@ -1,11 +1,11 @@
package carpet.script.utils;
import carpet.script.exception.InternalExpressionException;
import net.minecraft.util.Identifier;
import net.minecraft.util.InvalidIdentifierException;
import org.lwjgl.system.CallbackI;
import java.util.Locale;
import net.minecraft.ResourceLocationException;
import net.minecraft.resources.ResourceLocation;
public class InputValidator {
public static String validateSimpleString(String input, boolean strict)
@@ -16,13 +16,13 @@ public class InputValidator {
return simplified;
}
public static Identifier identifierOf(String string)
public static ResourceLocation identifierOf(String string)
{
try
{
return new Identifier(string);
return new ResourceLocation(string);
}
catch (InvalidIdentifierException iie)
catch (ResourceLocationException iie)
{
throw new InternalExpressionException("Incorrect identifier format '"+string+"': "+iie.getMessage());
}
@@ -18,31 +18,30 @@ import carpet.script.value.Value;
import com.google.common.collect.Sets;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.argument.ParticleEffectArgumentType;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NbtByte;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtDouble;
import net.minecraft.nbt.NbtFloat;
import net.minecraft.nbt.NbtInt;
import net.minecraft.nbt.NbtList;
import net.minecraft.nbt.NbtString;
import net.minecraft.nbt.NbtElement;
import net.minecraft.particle.ParticleEffect;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Registry;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.nbt.ByteTag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.DoubleTag;
import net.minecraft.nbt.FloatTag;
import net.minecraft.nbt.IntTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -60,13 +59,13 @@ import static java.util.Map.entry;
public class ShapeDispatcher
{
private static final Map<String, ParticleEffect> particleCache = new HashMap<>();
private static final Map<String, ParticleOptions> particleCache = new HashMap<>();
public static record ShapeWithConfig(ExpiringShape shape, Map<String, Value> config) {}
public static ShapeWithConfig fromFunctionArgs(
MinecraftServer server, ServerWorld world,
MinecraftServer server, ServerLevel world,
List<Value> lv,
Set<ServerPlayerEntity> playerSet
Set<ServerPlayer> playerSet
)
{
if (lv.size() < 3) throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params");
@@ -93,7 +92,7 @@ public class ShapeDispatcher
for (int i=2; i < lv.size(); i++) paramList.add(lv.get(i));
params = ShapeDispatcher.parseParams(paramList);
}
params.putIfAbsent("dim", new StringValue(world.getRegistryKey().getValue().toString()));
params.putIfAbsent("dim", new StringValue(world.dimension().location().toString()));
params.putIfAbsent("duration", duration);
if (params.containsKey("player"))
@@ -106,7 +105,7 @@ public class ShapeDispatcher
playerVals = Collections.singletonList(players);
for (Value pVal : playerVals)
{
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pVal);
ServerPlayer player = EntityValue.getPlayerByValue(server, pVal);
if (player == null)
throw new InternalExpressionException("'player' parameter needs to represent an existing player, not "+pVal.getString());
playerSet.add(player);
@@ -116,11 +115,11 @@ public class ShapeDispatcher
return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params);
}
public static void sendShape(Collection<ServerPlayerEntity> players, List<ShapeWithConfig> shapes)
public static void sendShape(Collection<ServerPlayer> players, List<ShapeWithConfig> shapes)
{
List<ServerPlayerEntity> clientPlayers = new ArrayList<>();
List<ServerPlayerEntity> alternativePlayers = new ArrayList<>();
for (ServerPlayerEntity player : players)
List<ServerPlayer> clientPlayers = new ArrayList<>();
List<ServerPlayer> alternativePlayers = new ArrayList<>();
for (ServerPlayer player : players)
{
if (ServerNetworkHandler.isValidCarpetPlayer(player))
{
@@ -134,7 +133,7 @@ public class ShapeDispatcher
if (!clientPlayers.isEmpty())
{
NbtList tag = new NbtList();
ListTag tag = new ListTag();
int tagcount = 0;
for (ShapeWithConfig s : shapes)
{
@@ -142,30 +141,30 @@ public class ShapeDispatcher
if (tagcount++>1000)
{
tagcount = 0;
NbtElement finalTag = tag;
Tag finalTag = tag;
clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag));
tag = new NbtList();
tag = new ListTag();
}
}
NbtElement finalTag = tag;
Tag finalTag = tag;
if (tag.size() > 0) clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag));
}
if (!alternativePlayers.isEmpty())
{
List<Consumer<ServerPlayerEntity>> alternatives = new ArrayList<>();
List<Consumer<ServerPlayer>> alternatives = new ArrayList<>();
shapes.forEach(s -> alternatives.add(s.shape().alternative()));
alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p)));
}
}
public static ParticleEffect getParticleData(String name)
public static ParticleOptions getParticleData(String name)
{
ParticleEffect particle = particleCache.get(name);
ParticleOptions particle = particleCache.get(name);
if (particle != null)
return particle;
try
{
particle = ParticleEffectArgumentType.readParameters(new StringReader(name));
particle = ParticleArgument.readParticle(new StringReader(name));
}
catch (CommandSyntaxException e)
{
@@ -205,10 +204,10 @@ public class ShapeDispatcher
}
// client
public static ExpiringShape fromTag(NbtCompound tag)
public static ExpiringShape fromTag(CompoundTag tag)
{
Map<String, Value> options = new HashMap<>();
for (String key : tag.getKeys())
for (String key : tag.getAllKeys())
{
Param decoder = Param.of.get(key);
if (decoder==null)
@@ -222,7 +221,7 @@ public class ShapeDispatcher
Value shapeValue = options.get("shape");
if (shapeValue == null)
{
CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getKeys()));
CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys()));
return null;
}
Function<Map<String, Value>,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString());
@@ -271,16 +270,16 @@ public class ShapeDispatcher
protected String snapTo;
protected boolean snapX, snapY, snapZ;
protected boolean discreteX, discreteY, discreteZ;
protected RegistryKey<World> shapeDimension;
protected ResourceKey<Level> shapeDimension;
protected ExpiringShape() { }
public static NbtCompound toTag(Map<String, Value> params)
public static CompoundTag toTag(Map<String, Value> params)
{
NbtCompound tag = new NbtCompound();
CompoundTag tag = new CompoundTag();
params.forEach((k, v) -> {
NbtElement valTag = Param.of.get(k).toTag(v);
Tag valTag = Param.of.get(k).toTag(v);
if (valTag != null) tag.put(k, valTag);
});
return tag;
@@ -325,7 +324,7 @@ public class ShapeDispatcher
key = 0;
followEntity = -1;
shapeDimension = RegistryKey.of(Registry.WORLD_KEY, new Identifier(options.get("dim").getString()));
shapeDimension = ResourceKey.create(Registry.DIMENSION_REGISTRY, new ResourceLocation(options.get("dim").getString()));
if (options.containsKey("follow"))
{
followEntity = NumericValue.asNumber(options.getOrDefault("follow", optional.get("follow"))).getInt();
@@ -339,33 +338,33 @@ public class ShapeDispatcher
}
}
public int getExpiry() { return duration; }
public Vec3d toAbsolute(Entity e, Vec3d vec, float partialTick)
public Vec3 toAbsolute(Entity e, Vec3 vec, float partialTick)
{
return vec.add(
snapX?(discreteX ?MathHelper.floor(e.getX()):MathHelper.lerp(partialTick, e.prevX, e.getX())):0.0,
snapY?(discreteY ?MathHelper.floor(e.getY()):MathHelper.lerp(partialTick, e.prevY, e.getY())):0.0,
snapZ?(discreteZ ?MathHelper.floor(e.getZ()):MathHelper.lerp(partialTick, e.prevZ, e.getZ())):0.0
snapX?(discreteX ?Mth.floor(e.getX()):Mth.lerp(partialTick, e.xo, e.getX())):0.0,
snapY?(discreteY ?Mth.floor(e.getY()):Mth.lerp(partialTick, e.yo, e.getY())):0.0,
snapZ?(discreteZ ?Mth.floor(e.getZ()):Mth.lerp(partialTick, e.zo, e.getZ())):0.0
);
}
public Vec3d relativiseRender(World world, Vec3d vec, float partialTick)
public Vec3 relativiseRender(Level world, Vec3 vec, float partialTick)
{
if (followEntity < 0) return vec;
Entity e = world.getEntityById(followEntity);
Entity e = world.getEntity(followEntity);
if (e == null) return vec;
return toAbsolute(e, vec, partialTick);
}
public Vec3d vecFromValue(Value value)
public Vec3 vecFromValue(Value value)
{
if (!(value instanceof ListValue)) throw new InternalExpressionException("decoded value of "+value.getPrettyString()+" is not a triple");
List<Value> elements = ((ListValue) value).getItems();
return new Vec3d(
return new Vec3(
NumericValue.asNumber( elements.get(0)).getDouble(),
NumericValue.asNumber( elements.get(1)).getDouble(),
NumericValue.asNumber( elements.get(2)).getDouble()
);
}
protected ParticleEffect replacementParticle()
protected ParticleOptions replacementParticle()
{
String particleName = fa ==0 ?
String.format(Locale.ROOT , "dust %.1f %.1f %.1f 1.0", r, g, b):
@@ -374,7 +373,7 @@ public class ShapeDispatcher
}
public abstract Consumer<ServerPlayerEntity> alternative();
public abstract Consumer<ServerPlayer> alternative();
public long key()
{
if (key!=0) return key;
@@ -398,7 +397,7 @@ public class ShapeDispatcher
private static final double xdif = new Random().nextDouble();
private static final double ydif = new Random().nextDouble();
private static final double zdif = new Random().nextDouble();
int vec3dhash(Vec3d vec)
int vec3dhash(Vec3 vec)
{
return vec.add(xdif, ydif, zdif).hashCode();
}
@@ -443,7 +442,7 @@ public class ShapeDispatcher
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
public DisplayedText() { }
Vec3d pos;
Vec3 pos;
String text;
int textcolor;
int textbck;
@@ -457,7 +456,7 @@ public class ShapeDispatcher
float indent;
int align;
float height;
Text value;
Component value;
boolean doublesided;
@Override
@@ -520,7 +519,7 @@ public class ShapeDispatcher
@Override
public Consumer<ServerPlayerEntity> alternative()
public Consumer<ServerPlayer> alternative()
{
return s -> {};
}
@@ -558,8 +557,8 @@ public class ShapeDispatcher
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
public Box() { }
Vec3d from;
Vec3d to;
Vec3 from;
Vec3 to;
@Override
protected void init(Map<String, Value> options)
@@ -570,20 +569,20 @@ public class ShapeDispatcher
}
@Override
public Consumer<ServerPlayerEntity> alternative()
public Consumer<ServerPlayer> alternative()
{
ParticleEffect particle = replacementParticle();
ParticleOptions particle = replacementParticle();
double density = Math.max(2.0, from.distanceTo(to) /50/ (a+0.1)) ;
return p ->
{
if (p.world.getRegistryKey() == shapeDimension)
if (p.level.dimension() == shapeDimension)
{
particleMesh(
Collections.singletonList(p),
particle,
density,
relativiseRender(p.world, from, 0),
relativiseRender(p.world, to, 0)
relativiseRender(p.level, from, 0),
relativiseRender(p.level, to, 0)
);
}
};
@@ -599,8 +598,8 @@ public class ShapeDispatcher
return hash;
}
public static int particleMesh(List<ServerPlayerEntity> playerList, ParticleEffect particle, double density,
Vec3d from, Vec3d to)
public static int particleMesh(List<ServerPlayer> playerList, ParticleOptions particle, double density,
Vec3 from, Vec3 to)
{
double x1 = from.x;
double y1 = from.y;
@@ -609,20 +608,20 @@ public class ShapeDispatcher
double y2 = to.y;
double z2 = to.z;
return
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y2, z1), density)+
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x2, y2, z1), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y1, z1), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x1, y1, z1), density)+
drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y2, z1), density)+
drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x2, y2, z1), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y1, z1), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x1, y1, z1), density)+
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z2), new Vec3d(x1, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z2), new Vec3d(x2, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z2), new Vec3d(x2, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z2), new Vec3d(x1, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x1, y1, z2), new Vec3(x1, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x1, y2, z2), new Vec3(x2, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y2, z2), new Vec3(x2, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y1, z2), new Vec3(x1, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x1, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x2, y1, z2), density);
drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y1, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x1, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y2, z2), density)+
drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x2, y1, z2), density);
}
}
@@ -640,8 +639,8 @@ public class ShapeDispatcher
super();
}
Vec3d from;
Vec3d to;
Vec3 from;
Vec3 to;
@Override
protected void init(Map<String, Value> options)
@@ -652,17 +651,17 @@ public class ShapeDispatcher
}
@Override
public Consumer<ServerPlayerEntity> alternative()
public Consumer<ServerPlayer> alternative()
{
ParticleEffect particle = replacementParticle();
ParticleOptions particle = replacementParticle();
double density = Math.max(2.0, from.distanceTo(to) /50) / (a+0.1);
return p ->
{
if (p.world.getRegistryKey() == shapeDimension) drawParticleLine(
if (p.level.dimension() == shapeDimension) drawParticleLine(
Collections.singletonList(p),
particle,
relativiseRender(p.world, from, 0),
relativiseRender(p.world, to, 0),
relativiseRender(p.level, from, 0),
relativiseRender(p.level, to, 0),
density
);
};
@@ -693,7 +692,7 @@ public class ShapeDispatcher
super();
}
Vec3d center;
Vec3 center;
float radius;
int level;
int subdivisions;
@@ -713,14 +712,14 @@ public class ShapeDispatcher
}
@Override
public Consumer<ServerPlayerEntity> alternative() { return p ->
public Consumer<ServerPlayer> alternative() { return p ->
{
ParticleEffect particle = replacementParticle();
ParticleOptions particle = replacementParticle();
int partno = Math.min(1000,20*subdivisions);
Random rand = p.world.getRandom();
ServerWorld world = p.getWorld();
Random rand = p.level.getRandom();
ServerLevel world = p.getLevel();
Vec3d ccenter = relativiseRender(world, center, 0 );
Vec3 ccenter = relativiseRender(world, center, 0 );
double ccx = ccenter.x;
double ccy = ccenter.y;
@@ -731,10 +730,10 @@ public class ShapeDispatcher
float theta = (float)Math.asin(rand.nextDouble()*2.0-1.0);
float phi = (float)(2*Math.PI*rand.nextDouble());
double x = radius * MathHelper.cos(theta) * MathHelper.cos(phi);
double y = radius * MathHelper.cos(theta) * MathHelper.sin(phi);
double z = radius * MathHelper.sin(theta);
world.spawnParticles(p, particle, true,
double x = radius * Mth.cos(theta) * Mth.cos(phi);
double y = radius * Mth.cos(theta) * Mth.sin(phi);
double z = radius * Mth.sin(theta);
world.sendParticles(p, particle, true,
x+ccx, y+ccy, z+ccz, 1,
0.0, 0.0, 0.0, 0.0);
}
@@ -764,7 +763,7 @@ public class ShapeDispatcher
@Override
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
Vec3d center;
Vec3 center;
float height;
float radius;
int level;
@@ -786,19 +785,19 @@ public class ShapeDispatcher
subdivisions = Math.max(10, (int)(10*Math.sqrt(radius)));
}
height = NumericValue.asNumber(options.getOrDefault("height", optional.get("height"))).getFloat();
axis = Direction.Axis.fromName(options.getOrDefault("axis", optional.get("axis")).getString());
axis = Direction.Axis.byName(options.getOrDefault("axis", optional.get("axis")).getString());
}
@Override
public Consumer<ServerPlayerEntity> alternative() { return p ->
public Consumer<ServerPlayer> alternative() { return p ->
{
ParticleEffect particle = replacementParticle();
ParticleOptions particle = replacementParticle();
int partno = (int)Math.min(1000,Math.sqrt(20*subdivisions*(1+height)));
Random rand = p.world.getRandom();
ServerWorld world = p.getWorld();
Random rand = p.level.getRandom();
ServerLevel world = p.getLevel();
Vec3d ccenter = relativiseRender(world, center, 0 );
Vec3 ccenter = relativiseRender(world, center, 0 );
double ccx = ccenter.x;
double ccy = ccenter.y;
@@ -810,10 +809,10 @@ public class ShapeDispatcher
{
float d = rand.nextFloat()*height;
float phi = (float)(2*Math.PI*rand.nextDouble());
double x = radius * MathHelper.cos(phi);
double x = radius * Mth.cos(phi);
double y = d;
double z = radius * MathHelper.sin(phi);
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
double z = radius * Mth.sin(phi);
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
}
}
else if (axis== Direction.Axis.X)
@@ -823,9 +822,9 @@ public class ShapeDispatcher
float d = rand.nextFloat()*height;
float phi = (float)(2*Math.PI*rand.nextDouble());
double x = d;
double y = radius * MathHelper.cos(phi);
double z = radius * MathHelper.sin(phi);
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
double y = radius * Mth.cos(phi);
double z = radius * Mth.sin(phi);
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
}
}
else // Z
@@ -834,10 +833,10 @@ public class ShapeDispatcher
{
float d = rand.nextFloat()*height;
float phi = (float)(2*Math.PI*rand.nextDouble());
double x = radius * MathHelper.sin(phi);
double y = radius * MathHelper.cos(phi);
double x = radius * Mth.sin(phi);
double y = radius * Mth.cos(phi);
double z = d;
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
}
}
};}
@@ -900,9 +899,9 @@ public class ShapeDispatcher
this.id = id;
}
public abstract NbtElement toTag(Value value); //validates value, returning null if not necessary to keep it and serialize
public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize
public abstract Value validate(Map<String, Value> options, MinecraftServer server, Value value); // makes sure the value is proper
public abstract Value decode(NbtElement tag);
public abstract Value decode(Tag tag);
}
public abstract static class StringParam extends Param
@@ -910,9 +909,9 @@ public class ShapeDispatcher
protected StringParam(String id) { super(id); }
@Override
public NbtElement toTag(Value value) { return NbtString.of(value.getString()); }
public Tag toTag(Value value) { return StringTag.valueOf(value.getString()); }
@Override
public Value decode(NbtElement tag) { return new StringValue(tag.asString()); }
public Value decode(Tag tag) { return new StringValue(tag.getAsString()); }
}
public static class TextParam extends StringParam
{
@@ -937,22 +936,22 @@ public class ShapeDispatcher
public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
{
if (!(value instanceof FormattedTextValue))
value = new FormattedTextValue(new LiteralText(value.getString()));
value = new FormattedTextValue(new TextComponent(value.getString()));
return value;
}
@Override
public NbtElement toTag(Value value)
public Tag toTag(Value value)
{
if (!(value instanceof FormattedTextValue))
value = new FormattedTextValue(new LiteralText(value.getString()));
return NbtString.of(((FormattedTextValue)value).serialize());
value = new FormattedTextValue(new TextComponent(value.getString()));
return StringTag.valueOf(((FormattedTextValue)value).serialize());
}
@Override
public Value decode(NbtElement tag)
public Value decode(Tag tag)
{
return FormattedTextValue.deserialize(tag.asString());
return FormattedTextValue.deserialize(tag.getAsString());
}
}
@@ -1015,24 +1014,24 @@ public class ShapeDispatcher
}
@Override
public NbtElement toTag(Value value)
public Tag toTag(Value value)
{
return NbtByte.of(value.getBoolean());
return ByteTag.valueOf(value.getBoolean());
}
@Override
public Value decode(NbtElement tag)
public Value decode(Tag tag)
{
return BooleanValue.of(((NbtByte) tag).byteValue() > 0);
return BooleanValue.of(((ByteTag) tag).getAsByte() > 0);
}
}
public static class FloatParam extends NumericParam
{
protected FloatParam(String id) { super(id); }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
@Override
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
}
public static abstract class PositiveParam extends NumericParam
@@ -1049,27 +1048,27 @@ public class ShapeDispatcher
{
protected PositiveFloatParam(String id) { super(id); }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
@Override
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
}
public static class PositiveIntParam extends PositiveParam
{
protected PositiveIntParam(String id) { super(id); }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
@Override
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
}
public static class NonNegativeIntParam extends NumericParam
{
protected NonNegativeIntParam(String id) { super(id); }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
@Override
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
@Override public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
{
Value ret = super.validate(options, server, value);
@@ -1081,9 +1080,9 @@ public class ShapeDispatcher
{
protected NonNegativeFloatParam(String id) { super(id); }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
@Override
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
@Override public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
{
Value ret = super.validate(options, server, value);
@@ -1149,9 +1148,9 @@ public class ShapeDispatcher
}
@Override
public Value decode(NbtElement tag)
public Value decode(Tag tag)
{
NbtList ctag = (NbtList)tag;
ListTag ctag = (ListTag)tag;
return ListValue.of(
new NumericValue(ctag.getDouble(0)),
new NumericValue(ctag.getDouble(1)),
@@ -1159,13 +1158,13 @@ public class ShapeDispatcher
);
}
@Override
public NbtElement toTag(Value value)
public Tag toTag(Value value)
{
List<Value> lv = ((ListValue)value).getItems();
NbtList tag = new NbtList();
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble()));
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble()));
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble()));
ListTag tag = new ListTag();
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble()));
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble()));
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble()));
return tag;
}
}
@@ -1188,13 +1187,13 @@ public class ShapeDispatcher
}
@Override
public Value decode(NbtElement tag)
public Value decode(Tag tag)
{
NbtList ltag = (NbtList)tag;
ListTag ltag = (ListTag)tag;
List<Value> points = new ArrayList<>();
for (int i=0, ll = ltag.size(); i<ll; i++)
{
NbtList ptag = ltag.getList(i);
ListTag ptag = ltag.getList(i);
points.add(ListValue.of(
new NumericValue(ptag.getDouble(0)),
new NumericValue(ptag.getDouble(1)),
@@ -1204,17 +1203,17 @@ public class ShapeDispatcher
return ListValue.wrap(points);
}
@Override
public NbtElement toTag(Value pointsValue)
public Tag toTag(Value pointsValue)
{
List<Value> lv = ((ListValue)pointsValue).getItems();
NbtList ltag = new NbtList();
ListTag ltag = new ListTag();
for (Value value : lv)
{
List<Value> coords = ((ListValue)value).getItems();
NbtList tag = new NbtList();
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble()));
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble()));
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble()));
ListTag tag = new ListTag();
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble()));
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble()));
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble()));
ltag.add(tag);
}
return ltag;
@@ -1230,9 +1229,9 @@ public class ShapeDispatcher
}
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
@Override
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
}
public static class EntityParam extends Param
@@ -1241,47 +1240,47 @@ public class ShapeDispatcher
protected EntityParam(String id) { super(id); }
@Override
public NbtElement toTag(Value value)
public Tag toTag(Value value)
{
return NbtInt.of(NumericValue.asNumber(value, id).getInt());
return IntTag.valueOf(NumericValue.asNumber(value, id).getInt());
}
@Override
public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
{
if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getId());
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, value);
ServerPlayer player = EntityValue.getPlayerByValue(server, value);
if (player == null)
throw new InternalExpressionException(id+" parameter needs to represent an entity or player");
return new NumericValue(player.getId());
}
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
}
private static boolean isStraight(Vec3d from, Vec3d to, double density)
private static boolean isStraight(Vec3 from, Vec3 to, double density)
{
if ( (from.x == to.x && from.y == to.y) || (from.x == to.x && from.z == to.z) || (from.y == to.y && from.z == to.z))
return from.distanceTo(to) / density > 20;
return false;
}
private static int drawOptimizedParticleLine(List<ServerPlayerEntity> playerList, ParticleEffect particle, Vec3d from, Vec3d to, double density)
private static int drawOptimizedParticleLine(List<ServerPlayer> playerList, ParticleOptions particle, Vec3 from, Vec3 to, double density)
{
double distance = from.distanceTo(to);
int particles = (int)(distance/density);
Vec3d towards = to.subtract(from);
Vec3 towards = to.subtract(from);
int parts = 0;
for (ServerPlayerEntity player : playerList)
for (ServerPlayer player : playerList)
{
ServerWorld world = player.getWorld();
world.spawnParticles(player, particle, true,
ServerLevel world = player.getLevel();
world.sendParticles(player, particle, true,
(towards.x)/2+from.x, (towards.y)/2+from.y, (towards.z)/2+from.z, particles/3,
towards.x/6, towards.y/6, towards.z/6, 0.0);
world.spawnParticles(player, particle, true,
world.sendParticles(player, particle, true,
from.x, from.y, from.z,1,0.0,0.0,0.0,0.0);
world.spawnParticles(player, particle, true,
world.sendParticles(player, particle, true,
to.x, to.y, to.z,1,0.0,0.0,0.0,0.0);
parts += particles/3+2;
}
@@ -1290,13 +1289,13 @@ public class ShapeDispatcher
{
int center = (divider*2)/3;
int dev = 2*divider;
for (ServerPlayerEntity player : playerList)
for (ServerPlayer player : playerList)
{
ServerWorld world = player.getWorld();
world.spawnParticles(player, particle, true,
ServerLevel world = player.getLevel();
world.sendParticles(player, particle, true,
(towards.x)/center+from.x, (towards.y)/center+from.y, (towards.z)/center+from.z, particles/divider,
towards.x/dev, towards.y/dev, towards.z/dev, 0.0);
world.spawnParticles(player, particle, true,
world.sendParticles(player, particle, true,
(towards.x)*(1.0-1.0/center)+from.x, (towards.y)*(1.0-1.0/center)+from.y, (towards.z)*(1.0-1.0/center)+from.z, particles/divider,
towards.x/dev, towards.y/dev, towards.z/dev, 0.0);
}
@@ -1306,22 +1305,22 @@ public class ShapeDispatcher
return parts;
}
public static int drawParticleLine(List<ServerPlayerEntity> players, ParticleEffect particle, Vec3d from, Vec3d to, double density)
public static int drawParticleLine(List<ServerPlayer> players, ParticleOptions particle, Vec3 from, Vec3 to, double density)
{
double distance = from.squaredDistanceTo(to);
double distance = from.distanceToSqr(to);
if (distance == 0) return 0;
int pcount = 0;
if (distance < 100)
{
Random rand = players.get(0).world.random;
Random rand = players.get(0).level.random;
int particles = (int)(distance/density)+1;
Vec3d towards = to.subtract(from);
Vec3 towards = to.subtract(from);
for (int i = 0; i < particles; i++)
{
Vec3d at = from.add(towards.multiply( rand.nextDouble()));
for (ServerPlayerEntity player : players)
Vec3 at = from.add(towards.scale( rand.nextDouble()));
for (ServerPlayer player : players)
{
player.getWorld().spawnParticles(player, particle, true,
player.getLevel().sendParticles(player, particle, true,
at.x, at.y, at.z, 1,
0.0, 0.0, 0.0, 0.0);
pcount ++;
@@ -1331,15 +1330,15 @@ public class ShapeDispatcher
}
if (isStraight(from, to, density)) return drawOptimizedParticleLine(players, particle, from, to, density);
Vec3d incvec = to.subtract(from).multiply(2*density/Math.sqrt(distance));
Vec3 incvec = to.subtract(from).scale(2*density/Math.sqrt(distance));
for (Vec3d delta = new Vec3d(0.0,0.0,0.0);
delta.lengthSquared()<distance;
delta = delta.add(incvec.multiply(Sys.randomizer.nextFloat())))
for (Vec3 delta = new Vec3(0.0,0.0,0.0);
delta.lengthSqr()<distance;
delta = delta.add(incvec.scale(Sys.randomizer.nextFloat())))
{
for (ServerPlayerEntity player : players)
for (ServerPlayer player : players)
{
player.getWorld().spawnParticles(player, particle, true,
player.getLevel().sendParticles(player, particle, true,
delta.x+from.x, delta.y+from.y, delta.z+from.z, 1,
0.0, 0.0, 0.0, 0.0);
pcount ++;
File diff suppressed because it is too large. Load diff
@@ -2,83 +2,83 @@ package carpet.script.utils;
import carpet.CarpetSettings;
import com.mojang.brigadier.ResultConsumer;
import net.minecraft.command.argument.EntityAnchorArgumentType;
import net.minecraft.entity.Entity;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandOutput;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec2f;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.BinaryOperator;
public class SnoopyCommandSource extends ServerCommandSource
public class SnoopyCommandSource extends CommandSourceStack
{
private final CommandOutput output;
private final Vec3d position;
private final ServerWorld world;
private final CommandSource output;
private final Vec3 position;
private final ServerLevel world;
private final int level;
private final String simpleName;
private final Text name;
private final Component name;
private final MinecraftServer server;
// skipping silent since snooper is never silent
private final Entity entity;
private final ResultConsumer<ServerCommandSource> resultConsumer;
private final EntityAnchorArgumentType.EntityAnchor entityAnchor;
private final Vec2f rotation;
private final ResultConsumer<CommandSourceStack> resultConsumer;
private final EntityAnchorArgument.Anchor entityAnchor;
private final Vec2 rotation;
// good stuff
private final Text[] error;
private final List<Text> chatOutput;
private final Component[] error;
private final List<Component> chatOutput;
public SnoopyCommandSource(ServerCommandSource original, Text[] error, List<Text> chatOutput)
public SnoopyCommandSource(CommandSourceStack original, Component[] error, List<Component> chatOutput)
{
super(CommandOutput.DUMMY, original.getPosition(), original.getRotation(), original.getWorld(), CarpetSettings.runPermissionLevel,
original.getName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
(ctx, succ, res) -> { }, EntityAnchorArgumentType.EntityAnchor.FEET);
this.output = CommandOutput.DUMMY;
super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), CarpetSettings.runPermissionLevel,
original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
(ctx, succ, res) -> { }, EntityAnchorArgument.Anchor.FEET);
this.output = CommandSource.NULL;
this.position = original.getPosition();
this.world = original.getWorld();
this.world = original.getLevel();
this.level = CarpetSettings.runPermissionLevel;
this.simpleName = original.getName();
this.simpleName = original.getTextName();
this.name = original.getDisplayName();
this.server = original.getServer();
this.entity = original.getEntity();
this.resultConsumer = (ctx, succ, res) -> { };
this.entityAnchor = original.getEntityAnchor();
this.entityAnchor = original.getAnchor();
this.rotation = original.getRotation();
this.error = error;
this.chatOutput = chatOutput;
}
public SnoopyCommandSource(ServerPlayerEntity player, Text[] error, List<Text> output) {
super(player, player.getPos(), player.getRotationClient(),
player.world instanceof ServerWorld ? (ServerWorld) player.world : null,
player.server.getPermissionLevel(player.getGameProfile()), player.getName().getString(), player.getDisplayName(),
player.world.getServer(), player);
public SnoopyCommandSource(ServerPlayer player, Component[] error, List<Component> output) {
super(player, player.position(), player.getRotationVector(),
player.level instanceof ServerLevel ? (ServerLevel) player.level : null,
player.server.getProfilePermissions(player.getGameProfile()), player.getName().getString(), player.getDisplayName(),
player.level.getServer(), player);
this.output = player;
this.position = player.getPos();
this.world = player.world instanceof ServerWorld ? (ServerWorld) player.world : null;
this.level = player.server.getPermissionLevel(player.getGameProfile());
this.position = player.position();
this.world = player.level instanceof ServerLevel ? (ServerLevel) player.level : null;
this.level = player.server.getProfilePermissions(player.getGameProfile());
this.simpleName = player.getName().getString();
this.name = player.getDisplayName();
this.server = player.world.getServer();
this.server = player.level.getServer();
this.entity = player;
this.resultConsumer = (ctx, succ, res) -> { };
this.entityAnchor = EntityAnchorArgumentType.EntityAnchor.FEET;
this.rotation = player.getRotationClient(); // not a client call really
this.entityAnchor = EntityAnchorArgument.Anchor.FEET;
this.rotation = player.getRotationVector(); // not a client call really
this.error = error;
this.chatOutput = output;
}
private SnoopyCommandSource(CommandOutput output, Vec3d pos, Vec2f rot, ServerWorld world, int level, String simpleName, Text name, MinecraftServer server, @Nullable Entity entity, ResultConsumer<ServerCommandSource> consumer, EntityAnchorArgumentType.EntityAnchor entityAnchor,
Text[] error, List<Text> chatOutput
private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer<CommandSourceStack> consumer, EntityAnchorArgument.Anchor entityAnchor,
Component[] error, List<Component> chatOutput
) {
super(output, pos, rot, world, level,
simpleName, name, server, entity, false,
@@ -99,34 +99,34 @@ public class SnoopyCommandSource extends ServerCommandSource
}
@Override
public ServerCommandSource withEntity(Entity entity)
public CommandSourceStack withEntity(Entity entity)
{
return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, error, chatOutput);
}
@Override
public ServerCommandSource withPosition(Vec3d position)
public CommandSourceStack withPosition(Vec3 position)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
}
@Override
public ServerCommandSource withRotation(Vec2f rotation)
public CommandSourceStack withRotation(Vec2 rotation)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
}
@Override
public ServerCommandSource withConsumer(ResultConsumer<ServerCommandSource> consumer)
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput);
}
@Override
public ServerCommandSource mergeConsumers(ResultConsumer<ServerCommandSource> consumer, BinaryOperator<ResultConsumer<ServerCommandSource>> binaryOperator)
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer, BinaryOperator<ResultConsumer<CommandSourceStack>> binaryOperator)
{
ResultConsumer<ServerCommandSource> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
return this.withConsumer(resultConsumer);
ResultConsumer<CommandSourceStack> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
return this.withCallback(resultConsumer);
}
//@Override // only used in fuctions and we really don't care to track these actually, besides the basic output
@@ -134,51 +134,51 @@ public class SnoopyCommandSource extends ServerCommandSource
//public ServerCommandSource withSilent() { return this; }
@Override
public ServerCommandSource withLevel(int level)
public CommandSourceStack withPermission(int level)
{
return this;
}
@Override
public ServerCommandSource withMaxLevel(int level)
public CommandSourceStack withMaximumPermission(int level)
{
return this;
}
@Override
public ServerCommandSource withEntityAnchor(EntityAnchorArgumentType.EntityAnchor anchor)
public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor)
{
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, error, chatOutput);
}
@Override
public ServerCommandSource withWorld(ServerWorld world)
public CommandSourceStack withLevel(ServerLevel world)
{
double d = DimensionType.getCoordinateScaleFactor(this.world.getDimension(), world.getDimension());
Vec3d position = new Vec3d(this.position.x * d, this.position.y, this.position.z * d);
double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType());
Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d);
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
}
@Override
public ServerCommandSource withLookingAt(Vec3d position)
public CommandSourceStack facing(Vec3 position)
{
Vec3d vec3d = this.entityAnchor.positionAt(this);
Vec3 vec3d = this.entityAnchor.apply(this);
double d = position.x - vec3d.x;
double e = position.y - vec3d.y;
double f = position.z - vec3d.z;
double g = (double) Math.sqrt(d * d + f * f);
float h = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(e, g) * 57.2957763671875D)));
float i = MathHelper.wrapDegrees((float)(MathHelper.atan2(f, d) * 57.2957763671875D) - 90.0F);
return this.withRotation(new Vec2f(h, i));
float h = Mth.wrapDegrees((float)(-(Mth.atan2(e, g) * 57.2957763671875D)));
float i = Mth.wrapDegrees((float)(Mth.atan2(f, d) * 57.2957763671875D) - 90.0F);
return this.withRotation(new Vec2(h, i));
}
@Override
public void sendError(Text message)
public void sendFailure(Component message)
{
error[0] = message;
}
@Override
public void sendFeedback(Text message, boolean broadcastToOps)
public void sendSuccess(Component message, boolean broadcastToOps)
{
chatOutput.add(message);
}
@@ -18,12 +18,11 @@ import com.sun.management.OperatingSystemMXBean;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.SharedConstants;
import net.minecraft.util.WorldSavePath;
import net.minecraft.util.math.Vec2f;
import net.minecraft.world.GameRules;
import net.minecraft.world.WorldProperties;
import net.minecraft.world.border.WorldBorder;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.border.WorldBorder;
import net.minecraft.world.level.storage.LevelData;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.phys.Vec2;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -47,65 +46,65 @@ public class SystemInfo {
put("app_scope", c -> StringValue.of((c.host).isPerUser()?"player":"global"));
put("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new).collect(Collectors.toList())));
put("world_name", c -> new StringValue(c.s.getServer().getSaveProperties().getLevelName()));
put("world_seed", c -> new NumericValue(c.s.getWorld().getSeed()));
put("server_motd", c -> StringValue.of(c.s.getServer().getServerMotd()));
put("world_path", c -> StringValue.of(c.s.getServer().getSavePath(WorldSavePath.ROOT).toString()));
put("world_name", c -> new StringValue(c.s.getServer().getWorldData().getLevelName()));
put("world_seed", c -> new NumericValue(c.s.getLevel().getSeed()));
put("server_motd", c -> StringValue.of(c.s.getServer().getMotd()));
put("world_path", c -> StringValue.of(c.s.getServer().getWorldPath(LevelResource.ROOT).toString()));
put("world_folder", c -> {
Path serverPath = c.s.getServer().getSavePath(WorldSavePath.ROOT);
Path serverPath = c.s.getServer().getWorldPath(LevelResource.ROOT);
int nodeCount = serverPath.getNameCount();
if (nodeCount < 2) return Value.NULL;
String tlf = serverPath.getName(nodeCount-2).toString();
return StringValue.of(tlf);
});
put("world_dimensions", c -> ListValue.wrap(c.s.getServer().getWorldRegistryKeys().stream().map(k -> ValueConversions.of(k.getValue())).collect(Collectors.toList())));
put("world_dimensions", c -> ListValue.wrap(c.s.getServer().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList())));
put("world_spawn_point", c -> {
WorldProperties prop = c.s.getServer().getOverworld().getLevelProperties();
return ListValue.of(NumericValue.of(prop.getSpawnX()), NumericValue.of(prop.getSpawnY()), NumericValue.of(prop.getSpawnZ()));
LevelData prop = c.s.getServer().overworld().getLevelData();
return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn()));
});
put("world_bottom", c-> new NumericValue(c.s.getWorld().getBottomY()));
put("world_bottom", c-> new NumericValue(c.s.getLevel().getMinBuildHeight()));
put("world_top", c-> new NumericValue(c.s.getWorld().getTopY()));
put("world_top", c-> new NumericValue(c.s.getLevel().getMaxBuildHeight()));
put("world_center", c-> {
WorldBorder worldBorder = c.s.getWorld().getWorldBorder();
WorldBorder worldBorder = c.s.getLevel().getWorldBorder();
return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ());
});
put("world_size", c -> new NumericValue(c.s.getWorld().getWorldBorder().getSize() / 2));
put("world_size", c -> new NumericValue(c.s.getLevel().getWorldBorder().getSize() / 2));
put("world_max_size", c-> new NumericValue( c.s.getWorld().getWorldBorder().getMaxRadius()));
put("world_max_size", c-> new NumericValue( c.s.getLevel().getWorldBorder().getAbsoluteMaxSize()));
put("world_time", c -> new NumericValue(c.s.getWorld().getTime()));
put("world_time", c -> new NumericValue(c.s.getLevel().getGameTime()));
put("game_difficulty", c -> StringValue.of(c.s.getServer().getSaveProperties().getDifficulty().getName()));
put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getSaveProperties().isHardcore()));
put("game_storage_format", c -> StringValue.of(c.s.getServer().getSaveProperties().getFormatName(c.s.getServer().getSaveProperties().getVersion())));
put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameMode().getName()));
put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayerCount()));
put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerManager().getViewDistance()));
put("game_difficulty", c -> StringValue.of(c.s.getServer().getWorldData().getDifficulty().getKey()));
put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getWorldData().isHardcore()));
put("game_storage_format", c -> StringValue.of(c.s.getServer().getWorldData().getStorageVersionName(c.s.getServer().getWorldData().getVersion())));
put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameType().getName()));
put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayers()));
put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerList().getViewDistance()));
put("game_mod_name", c -> StringValue.of(c.s.getServer().getServerModName()));
put("game_version", c -> StringValue.of(c.s.getServer().getVersion()));
put("game_target", c -> StringValue.of(SharedConstants.getGameVersion().getReleaseTarget()));
put("game_version", c -> StringValue.of(c.s.getServer().getServerVersion()));
put("game_target", c -> StringValue.of(SharedConstants.getCurrentVersion().getReleaseTarget()));
put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion()));
put("game_major_target", c -> {
String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\.");
String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\.");
return NumericValue.of((vers.length > 1)?Integer.parseInt(vers[1]):0);
});
put("game_minor_target", c -> {
String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\.");
String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\.");
return NumericValue.of((vers.length > 2)?Integer.parseInt(vers[2]):0);
});
put("game_stable", c -> BooleanValue.of(SharedConstants.getGameVersion().isStable()));
put("game_data_version", c->NumericValue.of(SharedConstants.getGameVersion().getWorldVersion()));
put("game_pack_version", c->NumericValue.of(SharedConstants.getGameVersion().getPackVersion()));
put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable()));
put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getWorldVersion()));
put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion()));
put("server_ip", c -> StringValue.of(c.s.getServer().getServerIp()));
put("server_ip", c -> StringValue.of(c.s.getServer().getLocalIp()));
put("server_whitelisted", c -> BooleanValue.of(c.s.getServer().isEnforceWhitelist()));
put("server_whitelist", c -> {
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s: c.s.getServer().getPlayerManager().getWhitelistedNames())
for (String s: c.s.getServer().getPlayerList().getWhiteListNames())
{
whitelist.append(StringValue.of(s));
}
@@ -113,7 +112,7 @@ public class SystemInfo {
});
put("server_banned_players", c -> {
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s: c.s.getServer().getPlayerManager().getUserBanList().getNames())
for (String s: c.s.getServer().getPlayerList().getBans().getUserList())
{
whitelist.append(StringValue.of(s));
}
@@ -121,7 +120,7 @@ public class SystemInfo {
});
put("server_banned_ips", c -> {
MapValue whitelist = new MapValue(Collections.emptyList());
for (String s: c.s.getServer().getPlayerManager().getIpBanList().getNames())
for (String s: c.s.getServer().getPlayerList().getIpBans().getUserList())
{
whitelist.append(StringValue.of(s));
}
@@ -137,9 +136,9 @@ public class SystemInfo {
put("server_last_tick_times", c -> {
//assuming we are in the tick world section
// might be off one tick when run in the off tasks or asynchronously.
int currentReportedTick = c.s.getServer().getTicks()-1;
int currentReportedTick = c.s.getServer().getTickCount()-1;
List<Value> ticks = new ArrayList<>(100);
final long[] tickArray = c.s.getServer().lastTickLengths;
final long[] tickArray = c.s.getServer().tickTimes;
for (int i=currentReportedTick+100; i > currentReportedTick; i--)
{
ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0));
@@ -191,11 +190,11 @@ public class SystemInfo {
});
put("world_gamerules", c->{
Map<Value, Value> rules = new HashMap<>();
final GameRules gameRules = c.s.getWorld().getGameRules();
GameRules.accept(new GameRules.Visitor() {
final GameRules gameRules = c.s.getLevel().getGameRules();
GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
@Override
public <T extends GameRules.Rule<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
rules.put(StringValue.of(key.getName()), StringValue.of(gameRules.get(key).toString()));
public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString()));
}
});
return MapValue.wrap(rules);
@@ -203,9 +202,9 @@ public class SystemInfo {
put("source_entity", c -> EntityValue.of(c.s.getEntity()));
put("source_position", c -> ValueConversions.of(c.s.getPosition()));
put("source_dimension", c -> ValueConversions.of(c.s.getWorld()));
put("source_dimension", c -> ValueConversions.of(c.s.getLevel()));
put("source_rotation", c -> {
Vec2f rotation = c.s.getRotation();
Vec2 rotation = c.s.getRotation();
return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y));
});
@@ -3,35 +3,34 @@ package carpet.script.utils;
import carpet.fakes.MinecraftServerInterface;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.WorldGenerationProgressListener;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.util.registry.SimpleRegistry;
import net.minecraft.world.World;
import net.minecraft.world.biome.source.BiomeAccess;
import net.minecraft.world.biome.source.MultiNoiseBiomeSource;
import net.minecraft.world.border.WorldBorderListener;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.WorldChunk;
import net.minecraft.world.dimension.DimensionOptions;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.GeneratorOptions;
import net.minecraft.world.gen.Spawner;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.ChunkGeneratorSettings;
import net.minecraft.world.gen.chunk.NoiseChunkGenerator;
import net.minecraft.world.level.ServerWorldProperties;
import net.minecraft.world.level.UnmodifiableLevelProperties;
import net.minecraft.world.storage.RegionFile;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.CustomSpawner;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
import net.minecraft.world.level.border.BorderChangeListener;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.storage.RegionFile;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.storage.DerivedLevelData;
import net.minecraft.world.level.storage.ServerLevelData;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@@ -43,7 +42,7 @@ import java.util.Set;
public class WorldTools
{
public static boolean canHasChunk(ServerWorld world, ChunkPos chpos, Map<String, RegionFile> regionCache, boolean deepcheck)
public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, Map<String, RegionFile> regionCache, boolean deepcheck)
{
if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null)
return true;
@@ -54,7 +53,7 @@ public class WorldTools
if (region == null) return false;
return region.hasChunk(chpos);
}
Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getWorldDirectory(world.getRegistryKey()).toFile(), "region").toPath();
Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getDimensionPath(world.dimension()).toFile(), "region").toPath();
Path regionFilePath = regionPath.resolve(currentRegionName);
File regionFile = regionFilePath.toFile();
if (!regionFile.exists())
@@ -75,37 +74,37 @@ public class WorldTools
public static boolean createWorld(MinecraftServer server, String worldKey, Long seed)
{
Identifier worldId = new Identifier(worldKey);
ServerWorld overWorld = server.getOverworld();
ResourceLocation worldId = new ResourceLocation(worldKey);
ServerLevel overWorld = server.overworld();
Set<RegistryKey<World>> worldKeys = server.getWorldRegistryKeys();
for (RegistryKey<World> worldRegistryKey : worldKeys)
Set<ResourceKey<Level>> worldKeys = server.levelKeys();
for (ResourceKey<Level> worldRegistryKey : worldKeys)
{
if (worldRegistryKey.getValue().equals(worldId))
if (worldRegistryKey.location().equals(worldId))
{
// world with this id already exists
return false;
}
}
ServerWorldProperties serverWorldProperties = server.getSaveProperties().getMainWorldProperties();
GeneratorOptions generatorOptions = server.getSaveProperties().getGeneratorOptions();
boolean bl = generatorOptions.isDebugWorld();
long l = generatorOptions.getSeed();
long m = BiomeAccess.hashSeed(l);
List<Spawner> list = List.of();
SimpleRegistry<DimensionOptions> simpleRegistry = generatorOptions.getDimensions();
DimensionOptions dimensionOptions = simpleRegistry.get(DimensionOptions.OVERWORLD);
ServerLevelData serverWorldProperties = server.getWorldData().overworldData();
WorldGenSettings generatorOptions = server.getWorldData().worldGenSettings();
boolean bl = generatorOptions.isDebug();
long l = generatorOptions.seed();
long m = BiomeManager.obfuscateSeed(l);
List<CustomSpawner> list = List.of();
MappedRegistry<LevelStem> simpleRegistry = generatorOptions.dimensions();
LevelStem dimensionOptions = simpleRegistry.get(LevelStem.OVERWORLD);
ChunkGenerator chunkGenerator2;
DimensionType dimensionType2;
if (dimensionOptions == null) {
dimensionType2 = server.getRegistryManager().getMutable(Registry.DIMENSION_TYPE_KEY).getOrThrow(DimensionType.OVERWORLD_REGISTRY_KEY);
chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager(), (new Random()).nextLong());
dimensionType2 = server.registryAccess().ownedRegistryOrThrow(Registry.DIMENSION_TYPE_REGISTRY).getOrThrow(DimensionType.OVERWORLD_LOCATION);
chunkGenerator2 = WorldGenSettings.makeDefaultOverworld(server.registryAccess(), (new Random()).nextLong());
} else {
dimensionType2 = dimensionOptions.getDimensionType();
chunkGenerator2 = dimensionOptions.getChunkGenerator();
dimensionType2 = dimensionOptions.type();
chunkGenerator2 = dimensionOptions.generator();
}
RegistryKey<World> customWorld = RegistryKey.of(Registry.WORLD_KEY, worldId);
ResourceKey<Level> customWorld = ResourceKey.create(Registry.DIMENSION_REGISTRY, worldId);
//chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN), (seed==null)?l:seed);
@@ -114,15 +113,15 @@ public class WorldTools
// return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD);
//});
chunkGenerator2 = new NoiseChunkGenerator(server.getRegistryManager().get(Registry.NOISE_WORLDGEN), MultiNoiseBiomeSource.Preset.OVERWORLD.getBiomeSource(server.getRegistryManager().get(Registry.BIOME_KEY)), seed, () -> {
return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD);
chunkGenerator2 = new NoiseBasedChunkGenerator(server.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY), MultiNoiseBiomeSource.Preset.OVERWORLD.biomeSource(server.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY)), seed, () -> {
return server.registryAccess().registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
});
ServerWorld serverWorld = new ServerWorld(
ServerLevel serverWorld = new ServerLevel(
server,
Util.getMainWorkerExecutor(),
Util.backgroundExecutor(),
((MinecraftServerInterface) server).getCMSession(),
new UnmodifiableLevelProperties(server.getSaveProperties(), serverWorldProperties),
new DerivedLevelData(server.getWorldData(), serverWorldProperties),
customWorld,
dimensionType2,
NOOP_LISTENER,
@@ -131,37 +130,37 @@ public class WorldTools
(seed==null)?l:seed,
list,
false);
overWorld.getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld.getWorldBorder()));
overWorld.getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld.getWorldBorder()));
((MinecraftServerInterface) server).getCMWorlds().put(customWorld, serverWorld);
return true;
}
public static void forceChunkUpdate(BlockPos pos, ServerWorld world)
public static void forceChunkUpdate(BlockPos pos, ServerLevel world)
{
WorldChunk worldChunk = world.getChunkManager().getWorldChunk(pos.getX()>>4, pos.getZ()>>4, false);
LevelChunk worldChunk = world.getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false);
if (worldChunk != null)
{
int vd = world.getServer().getPlayerManager().getViewDistance() * 16;
int vd = world.getServer().getPlayerList().getViewDistance() * 16;
int vvd = vd * vd;
List<ServerPlayerEntity> nearbyPlayers = world.getPlayers(p -> pos.getSquaredDistance(p.getX(), pos.getY(), p.getZ(), true) < vvd);
List<ServerPlayer> nearbyPlayers = world.getPlayers(p -> pos.distSqr(p.getX(), pos.getY(), p.getZ(), true) < vvd);
if (!nearbyPlayers.isEmpty())
{
ChunkDataS2CPacket packet = new ChunkDataS2CPacket(worldChunk, world.getLightingProvider(), null, null, false); // false seems to update neighbours as well.
ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well.
ChunkPos chpos = new ChunkPos(pos);
nearbyPlayers.forEach(p -> p.networkHandler.sendPacket(packet));
nearbyPlayers.forEach(p -> p.connection.send(packet));
}
}
}
private static class NoopWorldGenerationProgressListener implements WorldGenerationProgressListener
private static class NoopWorldGenerationProgressListener implements ChunkProgressListener
{
@Override public void start(ChunkPos spawnPos) { }
@Override public void setChunkStatus(ChunkPos pos, ChunkStatus status) { }
@Override public void updateSpawnPos(ChunkPos spawnPos) { }
@Override public void onStatusChange(ChunkPos pos, ChunkStatus status) { }
@Environment(EnvType.CLIENT)
@Override public void start() { }
@Override public void stop() { }
}
public static final WorldGenerationProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener();
public static final ChunkProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener();
}